Subversion Repositories SmartDukaan

Rev

Rev 32951 | Go to most recent revision | 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
 
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
 
79
    public String create(String email) {
80
        try {
81
            return createBuilder().withClaim(EMAIL, email).sign(ALGORITHM);
82
        } catch (JWTCreationException jwtCreationException) {
83
            throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
84
        }
85
    }
86
    public String create() {
87
        String email = "unregistereduser@gmail.com";
88
 
89
        try {
90
            return this.createBuilder().withClaim("email", email).sign(ALGORITHM);
91
        } catch (JWTCreationException var3) {
92
            throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
93
        }
94
    }
95
 
96
    private Builder createBuilder() {
97
        Instant createTimestamp = Instant.now();
98
        Instant expireTimestamp = Instant.now().plusSeconds(EXPIRE_TIME_IN_SECONDS);
99
        //LOGGER.info("Creating token with issuer {}, issuedAt {}, expireAt {}", PROFIT_MANDI, createTimestamp.toString(), expireTimestamp.toString());
100
        return JWT.create()
101
                .withIssuer(PROFIT_MANDI)
102
                .withIssuedAt(Date.from(createTimestamp))
103
                .withExpiresAt(Date.from(expireTimestamp));
104
    }
105
 
106
    public boolean isExpired(String token)
107
            throws ProfitMandiBusinessException {
108
        DecodedJWT decodedJWT = parse(token);
109
        Map<String, Claim> claims = decodedJWT.getClaims();
110
        if (claims.containsKey(USER_ID)) {
111
            final Claim roleIdsClaim = claims.get(ProfitMandiConstants.ROLE_IDS);
112
            if (roleIdsClaim.isNull()) {
113
                return true;
114
            }
115
        }
116
        Instant expireTime = decodedJWT.getExpiresAt().toInstant();
117
        Instant currentTime = Instant.now();
118
        //LOGGER.info("Checking token Expire time of token {} with currentTime {}, expireTime {}", token, currentTime, expireTime);
119
        if (currentTime.toEpochMilli() > expireTime.toEpochMilli()) {
120
            return true;
121
        } else {
122
            return false;
123
        }
124
    }
125
 
126
    public UserInfo getUserInfo(String token)
127
            throws ProfitMandiBusinessException {
128
        LOGGER.info("Getting UserInfo from token {}", token);
129
        DecodedJWT decodedJWT = parse(token);
130
        Map<String, Claim> claims = decodedJWT.getClaims();
131
        LOGGER.info("Claims contains user id - {}", claims.containsKey(USER_ID));
132
        if (claims.containsKey(USER_ID)) {
133
            final Claim userIdclaim = claims.get(USER_ID);
134
            int userId = userIdclaim.asInt();
135
            final Claim retailerIdclaim = claims.get(ProfitMandiConstants.RETAILER_ID);
136
            int retailerId = retailerIdclaim.asInt();
137
            final Claim roleIdsClaim = claims.get(ProfitMandiConstants.ROLE_IDS);
138
            if (roleIdsClaim == null || roleIdsClaim.isNull()) {
139
                throw new ProfitMandiBusinessException("Token", token, "Invalid Token");
140
            }
141
            String emailId = null;
142
            if (claims.containsKey(ProfitMandiConstants.EMAIL_ID)) {
143
                emailId = claims.get(ProfitMandiConstants.EMAIL_ID).asString();
144
            }
145
            final UserInfo userInfo = new UserInfo(userId, retailerId, new HashSet<>(Arrays.asList(roleIdsClaim.asArray(Integer.class))), emailId);
146
            return userInfo;
147
        } else if (claims.containsKey(EMAIL)) {
148
            final Claim emailClaim = claims.get("email");
149
            String email = emailClaim.asString();
150
            int retailerId = -1;
151
            if(email.contains("unregistereduser@gmail.com")) {
152
                try {
153
                    retailerId = partnerTypeChangeService.getBestPartner(ProfitMandiConstants.WAREHOUSE_NAME_MAP.get("RJ"));
154
                    LOGGER.info("Best partner for unregistered user is {}", retailerId);
155
                } catch (Exception e) {
156
                    LOGGER.error("Error while getting best partner for unregistered user", e);
157
                }
158
            }
159
            return new UserInfo(-1, retailerId, null, email);
160
 
161
        } else {
162
            throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1008");
163
        }
164
    }
165
 
166
    public List<String> getRoleNames(String token)
167
            throws ProfitMandiBusinessException {
168
        DecodedJWT decodedJWT = parse(token);
169
        Map<String, Claim> claims = decodedJWT.getClaims();
170
        if (claims.containsKey(ProfitMandiConstants.ROLE_IDS)) {
171
            Claim claim = claims.get(ProfitMandiConstants.ROLE_IDS);
172
            return Arrays.asList(claim.asArray(String.class));
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
    }
21543 ashik.ali 201
}