Subversion Repositories SmartDukaan

Rev

View as "text/plain" | Blame | Last modification | View Log | RSS feed

package com.spice.profitmandi.admin.util;

import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.spice.profitmandi.common.ResponseCodeHolder;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.model.UserInfo;

public class JWTUtil {
        private static final String SECRET_KEY = "profitmandi-admin";
        private static final String USER_ID = "userId";
        private static final String EMAIL = "email";
        private static final String ROLE_NAMES = "roleNames";
        private static final String PROFIT_MANDI = "profitmandi";
        // 60 days
        private static final int EXPIRE_TIME_IN_SECONDS = ((60 * 60) * 24) * 60;
        private static Algorithm ALGORITHM;
        private static final Logger LOGGER = LoggerFactory.getLogger(JWTUtil.class);

        static {
                try {
                        ALGORITHM = Algorithm.HMAC256(SECRET_KEY);
                } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }

        public static String create(long userId, String[] roleNames) {
                try {
                        return createBuilder().withClaim(USER_ID, (int) userId).withArrayClaim(ROLE_NAMES, roleNames)
                                        .sign(ALGORITHM);
                } catch (JWTCreationException jwtCreationException) {
                        throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
                }
        }

        public static String create(String email) {
                try {
                        return createBuilder().withClaim(EMAIL, email).sign(ALGORITHM);
                } catch (JWTCreationException jwtCreationException) {
                        throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
                }
        }

        public static String create(String email, String[] roleNames) {
                try {
                        return createBuilder().withClaim(EMAIL, email).withArrayClaim(ROLE_NAMES, roleNames).sign(ALGORITHM);
                } catch (JWTCreationException jwtCreationException) {
                        throw new RuntimeException(ResponseCodeHolder.getMessage("USR_1011"));
                }
        }

        private static Builder createBuilder() {
                Instant createTimestamp = Instant.now();
                Instant expireTimestamp = Instant.now().plusSeconds(EXPIRE_TIME_IN_SECONDS);
                // LOGGER.info("Creating token with issuer {}, issuedAt {}, expireAt
                // {}", PROFIT_MANDI, createTimestamp.toString(),
                // expireTimestamp.toString());
                return JWT.create().withIssuer(PROFIT_MANDI).withIssuedAt(Date.from(createTimestamp))
                                .withExpiresAt(Date.from(expireTimestamp));
        }

        public static boolean isExpired(String token) throws ProfitMandiBusinessException {
                DecodedJWT decodedJWT = parse(token);
                Instant expireTime = decodedJWT.getExpiresAt().toInstant();
                Instant currentTime = Instant.now();
                // LOGGER.info("Checking token Expire time of token {} with currentTime
                // {}, expireTime {}", token, currentTime, expireTime);
                if (currentTime.toEpochMilli() > expireTime.toEpochMilli()) {
                        return true;
                } else {
                        return false;
                }
        }

        public static List<String> getRoleNames(String token) throws ProfitMandiBusinessException {
                DecodedJWT decodedJWT = parse(token);
                Map<String, Claim> claims = decodedJWT.getClaims();
                if (claims.containsKey(ROLE_NAMES)) {
                        Claim claim = claims.get(ROLE_NAMES);
                        return Arrays.asList(claim.asArray(String.class));
                } else {
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1009");
                }
        }

        private static DecodedJWT parse(String token) throws ProfitMandiBusinessException {
                try {
                        JWTVerifier verifier = JWT.require(ALGORITHM).withIssuer(PROFIT_MANDI).build(); // Reusable
                                                                                                                                                                                        // verifier
                                                                                                                                                                                        // instance
                        return verifier.verify(token);
                } catch (JWTDecodeException exception) {
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1010");
                } catch (InvalidClaimException invalidClaimException) {
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1012");
                }
        }

        public static UserInfo getUserInfo(String token) throws ProfitMandiBusinessException {
                DecodedJWT decodedJWT = parse(token);
                Instant expireTime = decodedJWT.getExpiresAt().toInstant();
                Instant currentTime = Instant.now();
                if (currentTime.toEpochMilli() > expireTime.toEpochMilli()) {
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1012");
                }
                Map<String, Claim> claims = decodedJWT.getClaims();
                if (claims.containsKey(USER_ID)) {
                        final Claim userIdclaim = claims.get(USER_ID);
                        int userId = userIdclaim.asInt();
                        final Claim roleNamesClaim = claims.get(ROLE_NAMES);
                        final UserInfo userInfo = new UserInfo(userId, Arrays.asList(roleNamesClaim.asArray(String.class)), null);
                        return userInfo;
                } else if (claims.containsKey(EMAIL)) {
                        final Claim emailClaim = claims.get("email");
                        final UserInfo userInfo = new UserInfo(-1, null, emailClaim.asString());
                        return userInfo;
                } else {
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.TOKEN, token, "USR_1008");
                }
        }
}