be.bittich.quote.service.impl.TokenServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for be.bittich.quote.service.impl.TokenServiceImpl.java

Source

/*
 * Copyright 2014 nateriver.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package be.bittich.quote.service.impl;

import be.bittich.quote.core.CryptoUtil;
import be.bittich.quote.service.TokenService;
import be.bittich.quote.vo.SecurityToken;
import static com.google.common.base.Preconditions.checkArgument;
import java.time.Duration;
import java.time.Instant;
import static java.time.Instant.now;
import java.util.StringJoiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 *
 * @author nateriver
 */
@Service
public class TokenServiceImpl implements TokenService {

    private static final long serialVersionUID = 2424249343560111909L;
    @Autowired
    private Environment env;

    @Autowired
    private CryptoUtil cryptoUtil;

    private static final Logger LOG = LoggerFactory.getLogger(TokenServiceImpl.class);

    @Override
    public SecurityToken createToken(UserDetails userDetails, String ipAddress) {
        try {
            String encodedKey;
            Long timeCreation = now().toEpochMilli();
            SecurityToken token = new SecurityToken();
            token.setExtendedInformation(userDetails.getUsername());
            token.setIpAddress(ipAddress);
            token.setKeyCreationTime(timeCreation);
            encodedKey = cryptoUtil.encryptBase64(this.serializeToken(token));
            token.setKey(encodedKey);
            return token;
        } catch (Exception ex) {
            LOG.info(String.format("Impossible d'allouer un token: %s", ex.getMessage()));
        }
        return null;
    }

    @Override
    public String getUsernameFromToken(String tokenCrypted) {
        SecurityToken token;
        try {
            token = this.decryptToken(tokenCrypted);
            return token.getExtendedInformation();

        } catch (Exception ex) {
            LOG.info(String.format("Impossible d'extraire le token encrypt: %s", ex.getMessage()));

        }
        return null;

    }

    @Override
    public SecurityToken deserializeToken(String serializedToken, String key) {
        String[] tokenSplitted = serializedToken.split(SEPARATOR);
        checkArgument(tokenSplitted.length == 3, String.format("{%s} est incorrect.", serializedToken));
        SecurityToken token = new SecurityToken();
        token.setKey(key);
        token.setExtendedInformation(tokenSplitted[0]);
        token.setKeyCreationTime(Long.parseLong(tokenSplitted[1]));
        token.setIpAddress(tokenSplitted[2]);
        return token;
    }

    @Override
    public String serializeToken(SecurityToken token) {
        return new StringJoiner(SEPARATOR).add(token.getExtendedInformation()).add("" + token.getKeyCreationTime())
                .add(token.getIpAddress()).toString();
    }

    @Override
    public Boolean validateToken(String encryptedKey, String ipAddr, UserDetails userDetails) {
        try {

            SecurityToken token = this.decryptToken(encryptedKey);
            checkArgument(ipAddr.equals(token.getIpAddress()), "Ip ne correspond pas.");
            checkArgument(verifyDate(token), "Session expire");
            checkArgument(userDetails.getUsername().equals(token.getExtendedInformation()),
                    "Les utilisateurs ne correspondent pas.");
            return true;
        } catch (Exception ex) {
            LOG.info(String.format("Problme avec le token: {%s}", ex.getMessage()));
        }
        return false;
    }

    @Override
    public Boolean verifyDate(SecurityToken token) {
        Long expiredTime = Long.parseLong(env.getProperty("token.life"));
        Instant now = now();
        Instant expiration = Instant.ofEpochMilli(token.getKeyCreationTime()).plus(Duration.ofMinutes(expiredTime));
        boolean before = now.isBefore(expiration);

        return before;

    }

    @Override
    public SecurityToken decryptToken(String encryptedToken) throws Exception {
        String decryptedKey = cryptoUtil.decryptBase64(encryptedToken);
        SecurityToken token = this.deserializeToken(decryptedKey, encryptedToken);
        return token;
    }

}