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