com.xlrit.gears.server.security.internal.TokenManagerImpl Maven / Gradle / Ivy
The newest version!
package com.xlrit.gears.server.security.internal;
import java.util.Date;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.common.base.Strings;
import com.xlrit.gears.base.model.User;
import com.xlrit.gears.base.repository.UserRepository;
import com.xlrit.gears.base.exception.AuthException;
import com.xlrit.gears.server.security.TokenManager;
import com.xlrit.gears.server.security.AuthProperties;
class TokenManagerImpl implements TokenManager {
private static final Logger LOG = LoggerFactory.getLogger(TokenManagerImpl.class);
private final String issuer;
private final Algorithm algorithm;
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public TokenManagerImpl(
AuthProperties authProperties,
UserRepository userRepository,
PasswordEncoder passwordEncoder) {
this.issuer = authProperties.getInternal().getIssuer();
this.algorithm = Algorithm.HMAC256(authProperties.getInternal().getSecret());
this.userRepository = Objects.requireNonNull(userRepository);
this.passwordEncoder = Objects.requireNonNull(passwordEncoder);
}
@Override
public String createToken(String username, String password) {
User user = userRepository.findByUsername(username);
if (user == null
|| user.getActive() != Boolean.TRUE
|| Strings.isNullOrEmpty(user.getPassword())
|| !passwordEncoder.matches(password, user.getPassword())) {
throw new AuthException("Invalid combination of username and password");
}
LOG.debug("createToken: username={}, fullname={}", username, user.getFullName());
return JWT.create()
.withClaim("name", user.getFullName())
.withIssuedAt(new Date())
.withIssuer(issuer)
.withSubject(user.getId())
.sign(algorithm);
}
}