Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
21813 amit.gupta 1
package com.spice.profitmandi.admin.util;
2
 
3
import java.io.UnsupportedEncodingException;
4
import java.time.Instant;
5
import java.util.Arrays;
6
import java.util.Date;
7
import java.util.List;
8
import java.util.Map;
9
 
10
import org.slf4j.Logger;
11
import org.slf4j.LoggerFactory;
12
 
13
import com.auth0.jwt.JWT;
14
import com.auth0.jwt.JWTCreator.Builder;
15
import com.auth0.jwt.JWTVerifier;
16
import com.auth0.jwt.algorithms.Algorithm;
17
import com.auth0.jwt.exceptions.InvalidClaimException;
18
import com.auth0.jwt.exceptions.JWTCreationException;
19
import com.auth0.jwt.exceptions.JWTDecodeException;
20
import com.auth0.jwt.interfaces.Claim;
21
import com.auth0.jwt.interfaces.DecodedJWT;
22
import com.spice.profitmandi.common.ResponseCodeHolder;
23
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
24
import com.spice.profitmandi.common.model.ProfitMandiConstants;
25
import com.spice.profitmandi.common.model.UserInfo;
26
 
27
public class JWTUtil {
28
	private static final String SECRET_KEY = "profitmandi-admin";
29
	private static final String USER_ID = "userId";
30
	private static final String EMAIL = "email";
31
	private static final String ROLE_NAMES = "roleNames";
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;
36
	private static final Logger LOGGER = LoggerFactory.getLogger(JWTUtil.class);
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
 
50
	public static String create(long userId, String[] roleNames) {
51
		try {
52
			return createBuilder().withClaim(USER_ID, (int) userId).withArrayClaim(ROLE_NAMES, roleNames)
53
					.sign(ALGORITHM);
54
		} catch (JWTCreationException jwtCreationException) {
55
			throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
56
		}
57
	}
58
 
59
	public static String create(String email) {
60
		try {
61
			return createBuilder().withClaim(EMAIL, email).sign(ALGORITHM);
62
		} catch (JWTCreationException jwtCreationException) {
63
			throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
64
		}
65
	}
66
 
67
	public static String create(String email, String[] roleNames) {
68
		try {
69
			return createBuilder().withClaim(EMAIL, email).withArrayClaim(ROLE_NAMES, roleNames).sign(ALGORITHM);
70
		} catch (JWTCreationException jwtCreationException) {
71
			throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
72
		}
73
	}
74
 
75
	private static Builder createBuilder() {
76
		Instant createTimestamp = Instant.now();
77
		Instant expireTimestamp = Instant.now().plusSeconds(EXPIRE_TIME_IN_SECONDS);
78
		// LOGGER.info("Creating token with issuer {}, issuedAt {}, expireAt
79
		// {}", PROFIT_MANDI, createTimestamp.toString(),
80
		// expireTimestamp.toString());
81
		return JWT.create().withIssuer(PROFIT_MANDI).withIssuedAt(Date.from(createTimestamp))
82
				.withExpiresAt(Date.from(expireTimestamp));
83
	}
84
 
85
	public static boolean isExpired(String token) throws ProfitMandiBusinessException {
86
		DecodedJWT decodedJWT = parse(token);
87
		Instant expireTime = decodedJWT.getExpiresAt().toInstant();
88
		Instant currentTime = Instant.now();
89
		// LOGGER.info("Checking token Expire time of token {} with currentTime
90
		// {}, expireTime {}", token, currentTime, expireTime);
91
		if (currentTime.toEpochMilli() > expireTime.toEpochMilli()) {
92
			return true;
93
		} else {
94
			return false;
95
		}
96
	}
97
 
98
	public static List<String> getRoleNames(String token) throws ProfitMandiBusinessException {
99
		DecodedJWT decodedJWT = parse(token);
100
		Map<String, Claim> claims = decodedJWT.getClaims();
101
		if (claims.containsKey(ROLE_NAMES)) {
102
			Claim claim = claims.get(ROLE_NAMES);
103
			return Arrays.asList(claim.asArray(String.class));
104
		} else {
105
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1009");
106
		}
107
	}
108
 
109
	private static DecodedJWT parse(String token) throws ProfitMandiBusinessException {
110
		try {
111
			JWTVerifier verifier = JWT.require(ALGORITHM).withIssuer(PROFIT_MANDI).build(); // Reusable
112
																							// verifier
113
																							// instance
114
			return verifier.verify(token);
115
		} catch (JWTDecodeException exception) {
116
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1010");
117
		} catch (InvalidClaimException invalidClaimException) {
118
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1012");
119
		}
120
	}
121
 
122
	public static UserInfo getUserInfo(String token) throws ProfitMandiBusinessException {
123
		DecodedJWT decodedJWT = parse(token);
124
		Instant expireTime = decodedJWT.getExpiresAt().toInstant();
125
		Instant currentTime = Instant.now();
126
		if (currentTime.toEpochMilli() > expireTime.toEpochMilli()) {
127
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1012");
128
		}
129
		Map<String, Claim> claims = decodedJWT.getClaims();
130
		if (claims.containsKey(USER_ID)) {
131
			final Claim userIdclaim = claims.get(USER_ID);
132
			int userId = userIdclaim.asInt();
133
			final Claim roleNamesClaim = claims.get(ROLE_NAMES);
134
			final UserInfo userInfo = new UserInfo(userId, Arrays.asList(roleNamesClaim.asArray(String.class)), null);
135
			return userInfo;
136
		} else if (claims.containsKey(EMAIL)) {
137
			final Claim emailClaim = claims.get("email");
138
			final UserInfo userInfo = new UserInfo(-1, null, emailClaim.asString());
139
			return userInfo;
140
		} else {
141
			throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1008");
142
		}
143
	}
144
}