Subversion Repositories SmartDukaan

Rev

Rev 23568 | Rev 23800 | 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
 
23780 ashik.ali 50
	public static String create(int userId, String[] roleIds){
21543 ashik.ali 51
		try{
52
			return createBuilder()
53
				.withClaim(USER_ID, userId)
23780 ashik.ali 54
				.withArrayClaim(ProfitMandiConstants.ROLE_IDS, roleIds)
21543 ashik.ali 55
				.sign(ALGORITHM);
56
		}catch(JWTCreationException jwtCreationException){
57
			throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
58
		}
59
	}
60
	public static String create(String email){
61
		try{
62
			return createBuilder().withClaim(EMAIL, email).sign(ALGORITHM);
63
		}catch(JWTCreationException jwtCreationException){
64
			throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
65
		}
66
	}
67
 
68
	private static Builder createBuilder(){
69
		Instant createTimestamp = Instant.now();
70
		Instant expireTimestamp = Instant.now().plusSeconds(EXPIRE_TIME_IN_SECONDS);
71
		//LOGGER.info("Creating token with issuer {}, issuedAt {}, expireAt {}", PROFIT_MANDI, createTimestamp.toString(), expireTimestamp.toString());
72
		return JWT.create()
73
		.withIssuer(PROFIT_MANDI)
74
		.withIssuedAt(Date.from(createTimestamp))
75
		.withExpiresAt(Date.from(expireTimestamp));
76
	}
77
 
78
	public static boolean isExpired(String token)
79
		throws ProfitMandiBusinessException{
80
		DecodedJWT decodedJWT = parse(token);
81
		Instant expireTime = decodedJWT.getExpiresAt().toInstant();
82
		Instant currentTime = Instant.now();
83
		//LOGGER.info("Checking token Expire time of token {} with currentTime {}, expireTime {}", token, currentTime, expireTime);
84
		if(currentTime.toEpochMilli() > expireTime.toEpochMilli()){
85
			return true;
86
		}else{
87
			return false;
88
		}
89
	}
90
 
91
	public static UserInfo getUserInfo(String token)
92
		throws ProfitMandiBusinessException{
93
		DecodedJWT decodedJWT = parse(token);
23428 amit.gupta 94
		/*Instant expireTime = decodedJWT.getExpiresAt().toInstant();
21543 ashik.ali 95
		Instant currentTime = Instant.now();
96
		if(currentTime.toEpochMilli() > expireTime.toEpochMilli()) {
97
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1012");
23428 amit.gupta 98
		}*/
21543 ashik.ali 99
		Map<String, Claim> claims = decodedJWT.getClaims();
100
		if(claims.containsKey(USER_ID)){
101
			final Claim userIdclaim = claims.get(USER_ID);
102
			int userId = userIdclaim.asInt();
23780 ashik.ali 103
			final Claim roleIdsClaim = claims.get(ProfitMandiConstants.ROLE_IDS);
104
			final UserInfo userInfo = new UserInfo(userId, new HashSet<>(Arrays.asList(roleIdsClaim.asArray(Integer.class))), null);
21543 ashik.ali 105
			return userInfo;
106
		}else if(claims.containsKey(EMAIL)){
107
			final Claim emailClaim = claims.get("email");
108
			final UserInfo userInfo = new UserInfo(-1, null, emailClaim.asString());
109
			return userInfo;
110
		} else {
111
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1008");
112
		}
113
	}
114
 
115
	public static List<String> getRoleNames(String token)
116
			throws ProfitMandiBusinessException{
117
			DecodedJWT decodedJWT = parse(token);
118
			Map<String, Claim> claims = decodedJWT.getClaims();
23780 ashik.ali 119
			if(claims.containsKey(ProfitMandiConstants.ROLE_IDS)){
120
				Claim claim = claims.get(ProfitMandiConstants.ROLE_IDS);
21543 ashik.ali 121
				return Arrays.asList(claim.asArray(String.class));
122
			}else{
123
				throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1009");
124
			}
125
		}
126
 
127
	private static DecodedJWT parse(String token)
128
		throws ProfitMandiBusinessException{
129
		try{
130
			JWTVerifier verifier = JWT.require(ALGORITHM)
23429 amit.gupta 131
	            .withIssuer(PROFIT_MANDI).acceptExpiresAt(100000000)
21543 ashik.ali 132
	            .build(); //Reusable verifier instance
133
	        return verifier.verify(token);
134
		} catch (JWTDecodeException exception){
135
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1010");
136
		} catch(InvalidClaimException invalidClaimException){
137
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1012");
138
		}
139
	}
23428 amit.gupta 140
 
141
	public static void main(String[] args) throws Throwable{
142
		String token = JWTUtil.create("amit.gupta@shop2020.in");
143
		//System.out.println(token);
144
		//System.out.println(JWTUtil.isExpired(token));
145
		//System.out.println(JWTUtil.getUserInfo(token));
146
		DecodedJWT decodeJwt = JWTUtil.parse("eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJwcm9maXRtYW5kaSIsImV4cCI6MTUxNDk3MDY4OSwiaWF0IjoxNTA5Nzg2Njg5LCJ1c2VySWQiOjMzMjM1LCJyb2xlTmFtZXMiOlsiVVNFUiJdfQ.C1lE6XvGpvQaCISG4IlJKwzEYWa3dWMLn1jXKB7fFvc");
147
		System.out.println(decodeJwt.getExpiresAt());
148
	}
21543 ashik.ali 149
}