| 35272 |
amit |
1 |
package com.spice.profitmandi.service.authentication;
|
| 21543 |
ashik.ali |
2 |
|
|
|
3 |
import com.auth0.jwt.JWT;
|
|
|
4 |
import com.auth0.jwt.JWTCreator.Builder;
|
|
|
5 |
import com.auth0.jwt.JWTVerifier;
|
|
|
6 |
import com.auth0.jwt.algorithms.Algorithm;
|
|
|
7 |
import com.auth0.jwt.exceptions.InvalidClaimException;
|
|
|
8 |
import com.auth0.jwt.exceptions.JWTCreationException;
|
|
|
9 |
import com.auth0.jwt.exceptions.JWTDecodeException;
|
|
|
10 |
import com.auth0.jwt.interfaces.Claim;
|
|
|
11 |
import com.auth0.jwt.interfaces.DecodedJWT;
|
|
|
12 |
import com.spice.profitmandi.common.ResponseCodeHolder;
|
|
|
13 |
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
|
|
|
14 |
import com.spice.profitmandi.common.model.ProfitMandiConstants;
|
|
|
15 |
import com.spice.profitmandi.common.model.UserInfo;
|
| 35272 |
amit |
16 |
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
|
|
|
17 |
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
|
|
|
18 |
import org.apache.logging.log4j.LogManager;
|
|
|
19 |
import org.apache.logging.log4j.Logger;
|
|
|
20 |
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
21 |
import org.springframework.stereotype.Component;
|
| 21543 |
ashik.ali |
22 |
|
| 35272 |
amit |
23 |
import java.io.UnsupportedEncodingException;
|
|
|
24 |
import java.time.Instant;
|
|
|
25 |
import java.util.*;
|
|
|
26 |
|
|
|
27 |
@Component
|
| 21543 |
ashik.ali |
28 |
public class JWTUtil {
|
| 35272 |
amit |
29 |
private static final String SECRET_KEY = "newsecretkey";
|
|
|
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;
|
|
|
36 |
private static final Logger LOGGER = LogManager.getLogger(JWTUtil.class);
|
|
|
37 |
|
|
|
38 |
|
|
|
39 |
@Autowired
|
|
|
40 |
PartnerTypeChangeService partnerTypeChangeService;
|
|
|
41 |
|
|
|
42 |
static {
|
|
|
43 |
try {
|
|
|
44 |
ALGORITHM = Algorithm.HMAC256(SECRET_KEY);
|
|
|
45 |
} catch (IllegalArgumentException e) {
|
|
|
46 |
// TODO Auto-generated catch block
|
|
|
47 |
e.printStackTrace();
|
|
|
48 |
} catch (UnsupportedEncodingException e) {
|
|
|
49 |
// TODO Auto-generated catch block
|
|
|
50 |
e.printStackTrace();
|
|
|
51 |
}
|
|
|
52 |
}
|
|
|
53 |
|
|
|
54 |
public String create(int userId, int retailerId, String[] roleIds) {
|
|
|
55 |
try {
|
|
|
56 |
return createBuilder()
|
|
|
57 |
.withClaim(ProfitMandiConstants.USER_ID, userId)
|
|
|
58 |
.withClaim(ProfitMandiConstants.RETAILER_ID, retailerId)
|
|
|
59 |
.withArrayClaim(ProfitMandiConstants.ROLE_IDS, roleIds)
|
|
|
60 |
.sign(ALGORITHM);
|
|
|
61 |
} catch (JWTCreationException jwtCreationException) {
|
|
|
62 |
throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
|
|
|
63 |
}
|
|
|
64 |
}
|
|
|
65 |
|
|
|
66 |
public String create(String email, int userId, int retailerId, String[] roleIds) {
|
|
|
67 |
try {
|
|
|
68 |
return createBuilder()
|
|
|
69 |
.withClaim(ProfitMandiConstants.EMAIL_ID, email)
|
|
|
70 |
.withClaim(ProfitMandiConstants.USER_ID, userId)
|
|
|
71 |
.withClaim(ProfitMandiConstants.RETAILER_ID, retailerId)
|
|
|
72 |
.withArrayClaim(ProfitMandiConstants.ROLE_IDS, roleIds)
|
|
|
73 |
.sign(ALGORITHM);
|
|
|
74 |
} catch (JWTCreationException jwtCreationException) {
|
|
|
75 |
throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
|
|
|
76 |
}
|
|
|
77 |
}
|
|
|
78 |
|
| 36465 |
vikas |
79 |
public String createImpersonationToken(String targetEmail, int targetUserId, int targetRetailerId,
|
|
|
80 |
String[] targetRoleIds, int authUserId, String authUserEmail) {
|
|
|
81 |
try {
|
|
|
82 |
return createBuilder()
|
|
|
83 |
.withClaim(ProfitMandiConstants.EMAIL_ID, targetEmail)
|
|
|
84 |
.withClaim(ProfitMandiConstants.USER_ID, targetUserId)
|
|
|
85 |
.withClaim(ProfitMandiConstants.RETAILER_ID, targetRetailerId)
|
|
|
86 |
.withArrayClaim(ProfitMandiConstants.ROLE_IDS, targetRoleIds)
|
|
|
87 |
.withClaim(ProfitMandiConstants.AUTH_USER_ID, authUserId)
|
|
|
88 |
.withClaim(ProfitMandiConstants.AUTH_USER_EMAIL, authUserEmail)
|
|
|
89 |
.withClaim(ProfitMandiConstants.IS_IMPERSONATION, true)
|
|
|
90 |
.sign(ALGORITHM);
|
|
|
91 |
} catch (JWTCreationException jwtCreationException) {
|
|
|
92 |
throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
|
|
|
93 |
}
|
|
|
94 |
}
|
|
|
95 |
|
| 35272 |
amit |
96 |
public String create(String email) {
|
|
|
97 |
try {
|
|
|
98 |
return createBuilder().withClaim(EMAIL, email).sign(ALGORITHM);
|
|
|
99 |
} catch (JWTCreationException jwtCreationException) {
|
|
|
100 |
throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
|
|
|
101 |
}
|
|
|
102 |
}
|
|
|
103 |
public String create() {
|
|
|
104 |
String email = "unregistereduser@gmail.com";
|
|
|
105 |
|
|
|
106 |
try {
|
|
|
107 |
return this.createBuilder().withClaim("email", email).sign(ALGORITHM);
|
|
|
108 |
} catch (JWTCreationException var3) {
|
|
|
109 |
throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
|
|
|
110 |
}
|
|
|
111 |
}
|
|
|
112 |
|
|
|
113 |
private Builder createBuilder() {
|
|
|
114 |
Instant createTimestamp = Instant.now();
|
|
|
115 |
Instant expireTimestamp = Instant.now().plusSeconds(EXPIRE_TIME_IN_SECONDS);
|
|
|
116 |
//LOGGER.info("Creating token with issuer {}, issuedAt {}, expireAt {}", PROFIT_MANDI, createTimestamp.toString(), expireTimestamp.toString());
|
|
|
117 |
return JWT.create()
|
|
|
118 |
.withIssuer(PROFIT_MANDI)
|
|
|
119 |
.withIssuedAt(Date.from(createTimestamp))
|
|
|
120 |
.withExpiresAt(Date.from(expireTimestamp));
|
|
|
121 |
}
|
|
|
122 |
|
|
|
123 |
public boolean isExpired(String token)
|
|
|
124 |
throws ProfitMandiBusinessException {
|
|
|
125 |
DecodedJWT decodedJWT = parse(token);
|
|
|
126 |
Map<String, Claim> claims = decodedJWT.getClaims();
|
|
|
127 |
if (claims.containsKey(USER_ID)) {
|
|
|
128 |
final Claim roleIdsClaim = claims.get(ProfitMandiConstants.ROLE_IDS);
|
|
|
129 |
if (roleIdsClaim.isNull()) {
|
|
|
130 |
return true;
|
|
|
131 |
}
|
|
|
132 |
}
|
|
|
133 |
Instant expireTime = decodedJWT.getExpiresAt().toInstant();
|
|
|
134 |
Instant currentTime = Instant.now();
|
|
|
135 |
//LOGGER.info("Checking token Expire time of token {} with currentTime {}, expireTime {}", token, currentTime, expireTime);
|
|
|
136 |
if (currentTime.toEpochMilli() > expireTime.toEpochMilli()) {
|
|
|
137 |
return true;
|
|
|
138 |
} else {
|
|
|
139 |
return false;
|
|
|
140 |
}
|
|
|
141 |
}
|
|
|
142 |
|
|
|
143 |
public UserInfo getUserInfo(String token)
|
|
|
144 |
throws ProfitMandiBusinessException {
|
|
|
145 |
LOGGER.info("Getting UserInfo from token {}", token);
|
|
|
146 |
DecodedJWT decodedJWT = parse(token);
|
|
|
147 |
Map<String, Claim> claims = decodedJWT.getClaims();
|
|
|
148 |
LOGGER.info("Claims contains user id - {}", claims.containsKey(USER_ID));
|
|
|
149 |
if (claims.containsKey(USER_ID)) {
|
|
|
150 |
final Claim userIdclaim = claims.get(USER_ID);
|
|
|
151 |
int userId = userIdclaim.asInt();
|
|
|
152 |
final Claim retailerIdclaim = claims.get(ProfitMandiConstants.RETAILER_ID);
|
|
|
153 |
int retailerId = retailerIdclaim.asInt();
|
|
|
154 |
final Claim roleIdsClaim = claims.get(ProfitMandiConstants.ROLE_IDS);
|
|
|
155 |
if (roleIdsClaim == null || roleIdsClaim.isNull()) {
|
|
|
156 |
throw new ProfitMandiBusinessException("Token", token, "Invalid Token");
|
|
|
157 |
}
|
|
|
158 |
String emailId = null;
|
|
|
159 |
if (claims.containsKey(ProfitMandiConstants.EMAIL_ID)) {
|
|
|
160 |
emailId = claims.get(ProfitMandiConstants.EMAIL_ID).asString();
|
|
|
161 |
}
|
|
|
162 |
final UserInfo userInfo = new UserInfo(userId, retailerId, new HashSet<>(Arrays.asList(roleIdsClaim.asArray(Integer.class))), emailId);
|
| 36465 |
vikas |
163 |
if (claims.containsKey(ProfitMandiConstants.IS_IMPERSONATION)
|
|
|
164 |
&& !claims.get(ProfitMandiConstants.IS_IMPERSONATION).isNull()
|
|
|
165 |
&& claims.get(ProfitMandiConstants.IS_IMPERSONATION).asBoolean()) {
|
|
|
166 |
userInfo.setImpersonation(true);
|
|
|
167 |
userInfo.setAuthUserId(claims.get(ProfitMandiConstants.AUTH_USER_ID).asInt());
|
|
|
168 |
userInfo.setAuthUserEmail(claims.get(ProfitMandiConstants.AUTH_USER_EMAIL).asString());
|
|
|
169 |
}
|
| 35272 |
amit |
170 |
return userInfo;
|
|
|
171 |
} else if (claims.containsKey(EMAIL)) {
|
|
|
172 |
final Claim emailClaim = claims.get("email");
|
|
|
173 |
String email = emailClaim.asString();
|
|
|
174 |
int retailerId = -1;
|
|
|
175 |
if(email.contains("unregistereduser@gmail.com")) {
|
|
|
176 |
try {
|
|
|
177 |
retailerId = partnerTypeChangeService.getBestPartner(ProfitMandiConstants.WAREHOUSE_NAME_MAP.get("RJ"));
|
|
|
178 |
LOGGER.info("Best partner for unregistered user is {}", retailerId);
|
|
|
179 |
} catch (Exception e) {
|
|
|
180 |
LOGGER.error("Error while getting best partner for unregistered user", e);
|
|
|
181 |
}
|
|
|
182 |
}
|
|
|
183 |
return new UserInfo(-1, retailerId, null, email);
|
|
|
184 |
|
|
|
185 |
} else {
|
|
|
186 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1008");
|
|
|
187 |
}
|
|
|
188 |
}
|
|
|
189 |
|
|
|
190 |
public List<String> getRoleNames(String token)
|
|
|
191 |
throws ProfitMandiBusinessException {
|
|
|
192 |
DecodedJWT decodedJWT = parse(token);
|
|
|
193 |
Map<String, Claim> claims = decodedJWT.getClaims();
|
|
|
194 |
if (claims.containsKey(ProfitMandiConstants.ROLE_IDS)) {
|
|
|
195 |
Claim claim = claims.get(ProfitMandiConstants.ROLE_IDS);
|
|
|
196 |
return Arrays.asList(claim.asArray(String.class));
|
|
|
197 |
} else {
|
|
|
198 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1009");
|
|
|
199 |
}
|
|
|
200 |
}
|
|
|
201 |
|
|
|
202 |
private DecodedJWT parse(String token)
|
|
|
203 |
throws ProfitMandiBusinessException {
|
|
|
204 |
try {
|
|
|
205 |
JWTVerifier verifier = JWT.require(ALGORITHM)
|
|
|
206 |
.withIssuer(PROFIT_MANDI).acceptExpiresAt(100000000)
|
|
|
207 |
.build(); //Reusable verifier instance
|
|
|
208 |
return verifier.verify(token);
|
|
|
209 |
} catch (JWTDecodeException exception) {
|
|
|
210 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1010");
|
|
|
211 |
} catch (InvalidClaimException invalidClaimException) {
|
|
|
212 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1012");
|
|
|
213 |
}
|
|
|
214 |
}
|
|
|
215 |
|
|
|
216 |
public void main(String[] args) throws Throwable {
|
|
|
217 |
JWTUtil jwtUtil = new JWTUtil();
|
|
|
218 |
String token = jwtUtil.create("amit.gupta@shop2020.in");
|
|
|
219 |
//System.out.println(token);
|
|
|
220 |
//System.out.println(JWTUtil.isExpired(token));
|
|
|
221 |
//System.out.println(JWTUtil.getUserInfo(token));
|
|
|
222 |
DecodedJWT decodeJwt = jwtUtil.parse("eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJwcm9maXRtYW5kaSIsImV4cCI6MTUxNDk3MDY4OSwiaWF0IjoxNTA5Nzg2Njg5LCJ1c2VySWQiOjMzMjM1LCJyb2xlTmFtZXMiOlsiVVNFUiJdfQ.C1lE6XvGpvQaCISG4IlJKwzEYWa3dWMLn1jXKB7fFvc");
|
|
|
223 |
System.out.println(decodeJwt.getExpiresAt());
|
|
|
224 |
}
|
| 21543 |
ashik.ali |
225 |
}
|