Subversion Repositories SmartDukaan

Rev

Rev 23801 | Rev 24490 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
21543 ashik.ali 1
package com.spice.profitmandi.common.util;
2
 
3
import java.io.UnsupportedEncodingException;
4
import java.time.Instant;
5
import java.util.Arrays;
6
import java.util.Date;
23780 ashik.ali 7
import java.util.HashSet;
21543 ashik.ali 8
import java.util.List;
9
import java.util.Map;
10
 
23568 govind 11
import org.apache.logging.log4j.Logger;
12
import org.apache.logging.log4j.LogManager;
21543 ashik.ali 13
 
14
import com.auth0.jwt.JWT;
15
import com.auth0.jwt.JWTCreator.Builder;
16
import com.auth0.jwt.JWTVerifier;
17
import com.auth0.jwt.algorithms.Algorithm;
18
import com.auth0.jwt.exceptions.InvalidClaimException;
19
import com.auth0.jwt.exceptions.JWTCreationException;
20
import com.auth0.jwt.exceptions.JWTDecodeException;
21
import com.auth0.jwt.interfaces.Claim;
22
import com.auth0.jwt.interfaces.DecodedJWT;
23
import com.spice.profitmandi.common.ResponseCodeHolder;
24
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
25
import com.spice.profitmandi.common.model.ProfitMandiConstants;
26
import com.spice.profitmandi.common.model.UserInfo;
27
 
28
public class JWTUtil {
29
	private static final String SECRET_KEY = "secrate";
30
	private static final String USER_ID = "userId";
31
	private static final String EMAIL = "email";
32
	private static final String PROFIT_MANDI = "profitmandi";
33
	//60 days
34
	private static final int EXPIRE_TIME_IN_SECONDS = ((60 * 60)*24)*60;
35
	private static Algorithm ALGORITHM;
23568 govind 36
	private static final Logger LOGGER = LogManager.getLogger(JWTUtil.class);
21543 ashik.ali 37
 
38
	static{
39
		try {
40
			ALGORITHM = Algorithm.HMAC256(SECRET_KEY);
41
		} catch (IllegalArgumentException e) {
42
			// TODO Auto-generated catch block
43
			e.printStackTrace();
44
		} catch (UnsupportedEncodingException e) {
45
			// TODO Auto-generated catch block
46
			e.printStackTrace();
47
		}
48
	}
49
 
23846 ashik.ali 50
	public static String create(int userId, int retailerId, String[] roleIds){
21543 ashik.ali 51
		try{
52
			return createBuilder()
23846 ashik.ali 53
				.withClaim(ProfitMandiConstants.USER_ID, userId)
54
				.withClaim(ProfitMandiConstants.RETAILER_ID, retailerId)
23780 ashik.ali 55
				.withArrayClaim(ProfitMandiConstants.ROLE_IDS, roleIds)
21543 ashik.ali 56
				.sign(ALGORITHM);
57
		}catch(JWTCreationException jwtCreationException){
58
			throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
59
		}
60
	}
61
	public static String create(String email){
62
		try{
63
			return createBuilder().withClaim(EMAIL, email).sign(ALGORITHM);
64
		}catch(JWTCreationException jwtCreationException){
65
			throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
66
		}
67
	}
68
 
69
	private static Builder createBuilder(){
70
		Instant createTimestamp = Instant.now();
71
		Instant expireTimestamp = Instant.now().plusSeconds(EXPIRE_TIME_IN_SECONDS);
72
		//LOGGER.info("Creating token with issuer {}, issuedAt {}, expireAt {}", PROFIT_MANDI, createTimestamp.toString(), expireTimestamp.toString());
73
		return JWT.create()
74
		.withIssuer(PROFIT_MANDI)
75
		.withIssuedAt(Date.from(createTimestamp))
76
		.withExpiresAt(Date.from(expireTimestamp));
77
	}
78
 
79
	public static boolean isExpired(String token)
80
		throws ProfitMandiBusinessException{
81
		DecodedJWT decodedJWT = parse(token);
23800 amit.gupta 82
		Map<String, Claim> claims = decodedJWT.getClaims();
83
		if(claims.containsKey(USER_ID)){
84
			final Claim roleIdsClaim = claims.get(ProfitMandiConstants.ROLE_IDS);
85
			if(roleIdsClaim.isNull()) {
86
				return true;
87
			}
88
		}
21543 ashik.ali 89
		Instant expireTime = decodedJWT.getExpiresAt().toInstant();
90
		Instant currentTime = Instant.now();
91
		//LOGGER.info("Checking token Expire time of token {} with currentTime {}, expireTime {}", token, currentTime, expireTime);
92
		if(currentTime.toEpochMilli() > expireTime.toEpochMilli()){
93
			return true;
94
		}else{
95
			return false;
96
		}
97
	}
98
 
99
	public static UserInfo getUserInfo(String token)
100
		throws ProfitMandiBusinessException{
101
		DecodedJWT decodedJWT = parse(token);
23428 amit.gupta 102
		/*Instant expireTime = decodedJWT.getExpiresAt().toInstant();
21543 ashik.ali 103
		Instant currentTime = Instant.now();
104
		if(currentTime.toEpochMilli() > expireTime.toEpochMilli()) {
105
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1012");
23428 amit.gupta 106
		}*/
21543 ashik.ali 107
		Map<String, Claim> claims = decodedJWT.getClaims();
108
		if(claims.containsKey(USER_ID)){
109
			final Claim userIdclaim = claims.get(USER_ID);
110
			int userId = userIdclaim.asInt();
23846 ashik.ali 111
			final Claim retailerIdclaim = claims.get(ProfitMandiConstants.RETAILER_ID);
112
			int retailerId = retailerIdclaim.asInt();
23780 ashik.ali 113
			final Claim roleIdsClaim = claims.get(ProfitMandiConstants.ROLE_IDS);
23801 amit.gupta 114
			if(roleIdsClaim==null || roleIdsClaim.isNull()) {
115
				throw new ProfitMandiBusinessException("Token", token, "Invalid Token");
116
			}
23846 ashik.ali 117
			final UserInfo userInfo = new UserInfo(userId, retailerId, new HashSet<>(Arrays.asList(roleIdsClaim.asArray(Integer.class))), null);
21543 ashik.ali 118
			return userInfo;
119
		}else if(claims.containsKey(EMAIL)){
120
			final Claim emailClaim = claims.get("email");
23846 ashik.ali 121
			final UserInfo userInfo = new UserInfo(-1, -1, null, emailClaim.asString());
21543 ashik.ali 122
			return userInfo;
123
		} else {
124
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1008");
125
		}
126
	}
127
 
128
	public static List<String> getRoleNames(String token)
129
			throws ProfitMandiBusinessException{
130
			DecodedJWT decodedJWT = parse(token);
131
			Map<String, Claim> claims = decodedJWT.getClaims();
23780 ashik.ali 132
			if(claims.containsKey(ProfitMandiConstants.ROLE_IDS)){
133
				Claim claim = claims.get(ProfitMandiConstants.ROLE_IDS);
21543 ashik.ali 134
				return Arrays.asList(claim.asArray(String.class));
135
			}else{
136
				throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1009");
137
			}
138
		}
139
 
140
	private static DecodedJWT parse(String token)
141
		throws ProfitMandiBusinessException{
142
		try{
143
			JWTVerifier verifier = JWT.require(ALGORITHM)
23429 amit.gupta 144
	            .withIssuer(PROFIT_MANDI).acceptExpiresAt(100000000)
21543 ashik.ali 145
	            .build(); //Reusable verifier instance
146
	        return verifier.verify(token);
147
		} catch (JWTDecodeException exception){
148
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1010");
149
		} catch(InvalidClaimException invalidClaimException){
150
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1012");
151
		}
152
	}
23428 amit.gupta 153
 
154
	public static void main(String[] args) throws Throwable{
155
		String token = JWTUtil.create("amit.gupta@shop2020.in");
156
		//System.out.println(token);
157
		//System.out.println(JWTUtil.isExpired(token));
158
		//System.out.println(JWTUtil.getUserInfo(token));
159
		DecodedJWT decodeJwt = JWTUtil.parse("eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJwcm9maXRtYW5kaSIsImV4cCI6MTUxNDk3MDY4OSwiaWF0IjoxNTA5Nzg2Njg5LCJ1c2VySWQiOjMzMjM1LCJyb2xlTmFtZXMiOlsiVVNFUiJdfQ.C1lE6XvGpvQaCISG4IlJKwzEYWa3dWMLn1jXKB7fFvc");
160
		System.out.println(decodeJwt.getExpiresAt());
161
	}
21543 ashik.ali 162
}