Subversion Repositories SmartDukaan

Rev

Rev 36465 | Details | Compare with Previous | Last modification | View Log | RSS feed

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