auth
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package ru.gorodar.api.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public final class AuthDtos {
|
||||
|
||||
private AuthDtos() {
|
||||
}
|
||||
|
||||
public record AuthorizeRequest(@NotBlank @Email String email) {
|
||||
}
|
||||
|
||||
public record TokenResponse(@JsonProperty("access_token") String accessToken,
|
||||
@JsonProperty("token_type") String tokenType,
|
||||
@JsonProperty("expires_in") long expiresInSeconds,
|
||||
@JsonProperty("refresh_token") String refreshToken,
|
||||
String scope) {
|
||||
}
|
||||
|
||||
public record TokenErrorResponse(@JsonProperty("error") String error,
|
||||
@JsonProperty("error_description") String errorDescription) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package ru.gorodar.auth;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.gorodar.api.dto.AuthDtos.AuthorizeRequest;
|
||||
import ru.gorodar.api.dto.AuthDtos.TokenErrorResponse;
|
||||
import ru.gorodar.api.dto.AuthDtos.TokenResponse;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "auth")
|
||||
public class AuthController {
|
||||
|
||||
public static final String EMAIL_CODE_GRANT = "urn:gorodar:params:oauth:grant-type:email-code";
|
||||
public static final String REFRESH_TOKEN_GRANT = "refresh_token";
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
@PostMapping("/oauth2/authorize")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void authorize(@Valid @RequestBody AuthorizeRequest request) {
|
||||
authService.requestCode(request.email());
|
||||
}
|
||||
|
||||
/**
|
||||
* Контракт — RFC 6749: form-urlencoded на входе, {error, error_description} на выходе.
|
||||
*/
|
||||
@PostMapping(value = "/oauth2/token", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
|
||||
public ResponseEntity<?> token(@RequestParam Map<String, String> form) {
|
||||
try {
|
||||
AuthService.IssuedTokens tokens = switch (form.getOrDefault("grant_type", "")) {
|
||||
case EMAIL_CODE_GRANT -> authService.tokenByEmailCode(
|
||||
required(form, "email"), required(form, "code"));
|
||||
case REFRESH_TOKEN_GRANT -> authService.tokenByRefresh(required(form, "refresh_token"));
|
||||
default -> throw new ApiException(ErrorCode.VALIDATION_ERROR, "unsupported_grant_type");
|
||||
};
|
||||
return ResponseEntity.ok(new TokenResponse(
|
||||
tokens.accessToken(), "Bearer", tokens.expiresInSeconds(), tokens.refreshToken(), "gorodar"));
|
||||
} catch (ApiException e) {
|
||||
boolean unsupported = "unsupported_grant_type".equals(e.getMessage());
|
||||
String error = unsupported ? "unsupported_grant_type" : "invalid_grant";
|
||||
HttpStatus status = unsupported ? HttpStatus.BAD_REQUEST : HttpStatus.valueOf(e.getCode().getStatus());
|
||||
return ResponseEntity.status(status).body(new TokenErrorResponse(error, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
private String required(Map<String, String> form, String name) {
|
||||
String value = form.get(name);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Отсутствует обязательный параметр " + name);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package ru.gorodar.auth;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.gorodar.auth.TokenService.IssuedAccessToken;
|
||||
import ru.gorodar.dao.AuthCodeRepository;
|
||||
import ru.gorodar.dao.RefreshTokenRepository;
|
||||
import ru.gorodar.dao.UserRepository;
|
||||
import ru.gorodar.dao.UserRoleRepository;
|
||||
import ru.gorodar.dao.entity.AuthCode;
|
||||
import ru.gorodar.dao.entity.RefreshToken;
|
||||
import ru.gorodar.dao.entity.User;
|
||||
import ru.gorodar.dao.entity.UserRole;
|
||||
import ru.gorodar.config.AuthProperties;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AuthService {
|
||||
|
||||
private static final int CODE_LENGTH = 6;
|
||||
private static final int MAX_ATTEMPTS = 5;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final UserRoleRepository userRoleRepository;
|
||||
private final AuthCodeRepository authCodeRepository;
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final TokenService tokenService;
|
||||
private final MailCodeSender mailCodeSender;
|
||||
private final AuthProperties properties;
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
@Transactional
|
||||
public void requestCode(String rawEmail) {
|
||||
String email = rawEmail.trim().toLowerCase();
|
||||
User user = userRepository.findByEmail(email).orElseGet(() -> createUser(email));
|
||||
LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
|
||||
authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(user.getId())
|
||||
.filter(last -> last.getCreatedAt().plus(properties.resendInterval()).isAfter(now))
|
||||
.ifPresent(last -> {
|
||||
throw new ApiException(ErrorCode.AUTH_CODE_RATE_LIMITED);
|
||||
});
|
||||
String code = generateCode();
|
||||
AuthCode authCode = new AuthCode();
|
||||
authCode.setId(UUID.randomUUID());
|
||||
authCode.setUser(user);
|
||||
authCode.setCodeHash(sha256Hex(code));
|
||||
authCode.setExpiresAt(now.plus(properties.codeTtl()));
|
||||
authCode.setAttempts(0);
|
||||
authCodeRepository.save(authCode);
|
||||
mailCodeSender.sendCode(email, code);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public IssuedTokens tokenByEmailCode(String rawEmail, String code) {
|
||||
String email = rawEmail.trim().toLowerCase();
|
||||
User user = userRepository.findByEmail(email)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.INVALID_GRANT));
|
||||
AuthCode authCode = authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(user.getId())
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.INVALID_GRANT));
|
||||
if (authCode.getUsedAt() != null
|
||||
|| authCode.getExpiresAt().isBefore(LocalDateTime.now(ZoneOffset.UTC))
|
||||
|| authCode.getAttempts() >= MAX_ATTEMPTS) {
|
||||
throw new ApiException(ErrorCode.INVALID_GRANT);
|
||||
}
|
||||
if (!MessageDigest.isEqual(sha256Hex(code).getBytes(StandardCharsets.UTF_8),
|
||||
authCode.getCodeHash().getBytes(StandardCharsets.UTF_8))) {
|
||||
authCode.setAttempts(authCode.getAttempts() + 1);
|
||||
authCodeRepository.save(authCode);
|
||||
throw new ApiException(ErrorCode.INVALID_GRANT);
|
||||
}
|
||||
authCode.setUsedAt(LocalDateTime.now(ZoneOffset.UTC));
|
||||
authCodeRepository.save(authCode);
|
||||
return issueTokens(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public IssuedTokens tokenByRefresh(String rawRefreshToken) {
|
||||
RefreshToken refresh = refreshTokenRepository.findByTokenHash(sha256Hex(rawRefreshToken))
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.INVALID_GRANT));
|
||||
if (refresh.getRevokedAt() != null
|
||||
|| refresh.getExpiresAt().isBefore(LocalDateTime.now(ZoneOffset.UTC))) {
|
||||
throw new ApiException(ErrorCode.INVALID_GRANT);
|
||||
}
|
||||
refresh.setRevokedAt(LocalDateTime.now(ZoneOffset.UTC));
|
||||
refreshTokenRepository.save(refresh);
|
||||
return issueTokens(refresh.getUser());
|
||||
}
|
||||
|
||||
private IssuedTokens issueTokens(User user) {
|
||||
List<String> roles = userRoleRepository.findByUserId(user.getId()).stream()
|
||||
.map(UserRole::getRole)
|
||||
.toList();
|
||||
IssuedAccessToken access = tokenService.issueAccessToken(user, roles);
|
||||
String refreshValue = new String(Base64.getUrlEncoder().withoutPadding()
|
||||
.encode(secureRandom.generateSeed(32)), StandardCharsets.UTF_8);
|
||||
RefreshToken refresh = new RefreshToken();
|
||||
refresh.setId(UUID.randomUUID());
|
||||
refresh.setUser(user);
|
||||
refresh.setTokenHash(sha256Hex(refreshValue));
|
||||
refresh.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).plus(properties.refreshTokenTtl()));
|
||||
refreshTokenRepository.save(refresh);
|
||||
return new IssuedTokens(access.token(), access.expiresInSeconds(), refreshValue);
|
||||
}
|
||||
|
||||
private User createUser(String email) {
|
||||
User user = new User();
|
||||
user.setId(UUID.randomUUID());
|
||||
user.setEmail(email);
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
private String generateCode() {
|
||||
StringBuilder code = new StringBuilder(CODE_LENGTH);
|
||||
for (int i = 0; i < CODE_LENGTH; i++) {
|
||||
code.append(secureRandom.nextInt(10));
|
||||
}
|
||||
return code.toString();
|
||||
}
|
||||
|
||||
private String sha256Hex(String value) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 недоступен", e);
|
||||
}
|
||||
}
|
||||
|
||||
public record IssuedTokens(String accessToken, long expiresInSeconds, String refreshToken) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.gorodar.auth;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.gorodar.config.AuthProperties;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class DiscoveryController {
|
||||
|
||||
private final AuthProperties properties;
|
||||
private final JwkKeys jwkKeys;
|
||||
|
||||
@GetMapping("/.well-known/openid-configuration")
|
||||
public Map<String, Object> openidConfiguration() {
|
||||
String issuer = trimTrailingSlash(properties.issuer());
|
||||
return Map.of(
|
||||
"issuer", issuer,
|
||||
"authorization_endpoint", issuer + "/oauth2/authorize",
|
||||
"token_endpoint", issuer + "/oauth2/token",
|
||||
"jwks_uri", issuer + "/oauth2/jwks",
|
||||
"response_modes_supported", List.of("form_post", "query"),
|
||||
"grant_types_supported", List.of(AuthController.EMAIL_CODE_GRANT, AuthController.REFRESH_TOKEN_GRANT),
|
||||
"token_endpoint_auth_methods_supported", List.of("none"),
|
||||
"scopes_supported", List.of("gorodar"));
|
||||
}
|
||||
|
||||
@GetMapping("/oauth2/jwks")
|
||||
public Map<String, Object> jwks() {
|
||||
return jwkKeys.publicKeySet().toJSONObject();
|
||||
}
|
||||
|
||||
private String trimTrailingSlash(String value) {
|
||||
return value.endsWith("/") ? value.substring(0, value.length() - 1) : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package ru.gorodar.auth;
|
||||
|
||||
import com.nimbusds.jose.JOSEException;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.jwk.JWKSet;
|
||||
import com.nimbusds.jose.jwk.KeyUse;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
|
||||
import lombok.Getter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.gorodar.config.AuthProperties;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.text.ParseException;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Подписные ключи RS256 для access-токенов. Хранятся как JWK-JSON в keysDir;
|
||||
* при первом старте генерируются и сохраняются, чтобы токены переживали рестарты.
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class JwkKeys {
|
||||
|
||||
private static final String KEY_FILE = "access-token-rs256.json";
|
||||
|
||||
@Getter
|
||||
private final RSAKey key;
|
||||
|
||||
public JwkKeys(AuthProperties properties) {
|
||||
this.key = loadOrGenerate(properties.keysDir().resolve(KEY_FILE));
|
||||
}
|
||||
|
||||
public JWKSet publicKeySet() {
|
||||
return new JWKSet(key.toPublicJWK());
|
||||
}
|
||||
|
||||
public JWKSet fullKeySet() {
|
||||
return new JWKSet(key);
|
||||
}
|
||||
|
||||
private RSAKey loadOrGenerate(Path file) {
|
||||
try {
|
||||
if (Files.exists(file)) {
|
||||
RSAKey loaded = (RSAKey) JWKSet.parse(Files.readString(file)).getKeys().getFirst();
|
||||
log.info("Загружен подписной ключ access-токенов из {}", file);
|
||||
return loaded;
|
||||
}
|
||||
RSAKey generated = new RSAKeyGenerator(2048)
|
||||
.algorithm(JWSAlgorithm.RS256)
|
||||
.keyUse(KeyUse.SIGNATURE)
|
||||
.keyID(UUID.randomUUID().toString())
|
||||
.generate();
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, new JWKSet(generated).toJSONObject(false).toString());
|
||||
log.info("Сгенерирован новый подписной ключ access-токенов: {}", file);
|
||||
return generated;
|
||||
} catch (IOException | ParseException | JOSEException e) {
|
||||
throw new IllegalStateException("Не удалось загрузить/сгенерировать подписной ключ " + file, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.gorodar.auth;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import ru.gorodar.config.AuthProperties;
|
||||
|
||||
/**
|
||||
* Отправка кода подтверждения. Без настроенного SMTP-хоста переходит в log-only режим —
|
||||
* код пишется в лог, чтобы dev/docker поднимались без почты.
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MailCodeSender {
|
||||
|
||||
private final JavaMailSender mailSender;
|
||||
private final AuthProperties properties;
|
||||
|
||||
@Value("${spring.mail.host:}")
|
||||
private String mailHost;
|
||||
|
||||
public void sendCode(String email, String code) {
|
||||
boolean logOnly = properties.mailLogOnly() || !StringUtils.hasText(mailHost);
|
||||
if (logOnly) {
|
||||
log.warn("SMTP не настроен (log-only): код подтверждения для {} = {}", email, code);
|
||||
return;
|
||||
}
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
message.setFrom(properties.mailFrom());
|
||||
message.setTo(email);
|
||||
message.setSubject("Городар: код подтверждения");
|
||||
message.setText("Ваш код подтверждения: %s\nКод действителен 10 минут.".formatted(code));
|
||||
mailSender.send(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package ru.gorodar.auth;
|
||||
|
||||
import com.nimbusds.jose.jwk.JWKSet;
|
||||
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
|
||||
import org.springframework.security.oauth2.jwt.JwsHeader;
|
||||
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.gorodar.config.AuthProperties;
|
||||
import ru.gorodar.dao.entity.User;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class TokenService {
|
||||
|
||||
public static final String AUDIENCE = "gorodar";
|
||||
|
||||
private final JwtEncoder encoder;
|
||||
private final AuthProperties properties;
|
||||
|
||||
public TokenService(JwkKeys jwkKeys, AuthProperties properties) {
|
||||
JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwkKeys.getKey()));
|
||||
this.encoder = new NimbusJwtEncoder(jwkSource);
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public IssuedAccessToken issueAccessToken(User user, List<String> roles) {
|
||||
Instant now = Instant.now();
|
||||
Instant expiresAt = now.plus(properties.accessTokenTtl());
|
||||
Map<String, Object> resourceAccess = Map.of(AUDIENCE, Map.of("roles", roles));
|
||||
JwtClaimsSet claims = JwtClaimsSet.builder()
|
||||
.issuer(properties.issuer())
|
||||
.subject(user.getId().toString())
|
||||
.audience(List.of(AUDIENCE))
|
||||
.issuedAt(now)
|
||||
.expiresAt(expiresAt)
|
||||
.claim("email", user.getEmail())
|
||||
.claim("resource_access", resourceAccess)
|
||||
.build();
|
||||
String token = encoder.encode(JwtEncoderParameters.from(
|
||||
JwsHeader.with(SignatureAlgorithm.RS256).build(), claims)).getTokenValue();
|
||||
return new IssuedAccessToken(token, properties.accessTokenTtl().toSeconds());
|
||||
}
|
||||
|
||||
public record IssuedAccessToken(String token, long expiresInSeconds) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package ru.gorodar.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.nio.file.Path;
|
||||
|
||||
@ConfigurationProperties(prefix = "gorodar.auth")
|
||||
public record AuthProperties(
|
||||
String issuer,
|
||||
Duration accessTokenTtl,
|
||||
Duration refreshTokenTtl,
|
||||
Duration codeTtl,
|
||||
Duration resendInterval,
|
||||
Path keysDir,
|
||||
boolean mailLogOnly,
|
||||
String mailFrom) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.gorodar.dao.entity.AuthCode;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AuthCodeRepository extends JpaRepository<AuthCode, UUID> {
|
||||
|
||||
Optional<AuthCode> findFirstByUserIdOrderByCreatedAtDesc(UUID userId);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.gorodar.dao.entity.RefreshToken;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, UUID> {
|
||||
|
||||
Optional<RefreshToken> findByTokenHash(String tokenHash);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.gorodar.dao.entity.User;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, UUID> {
|
||||
|
||||
Optional<User> findByEmail(String email);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.gorodar.dao.entity.UserRole;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface UserRoleRepository extends JpaRepository<UserRole, UUID> {
|
||||
|
||||
List<UserRole> findByUserId(UUID userId);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "auth_codes")
|
||||
@Getter
|
||||
@Setter
|
||||
public class AuthCode {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
@Column(name = "code_hash", nullable = false)
|
||||
private String codeHash;
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private LocalDateTime expiresAt;
|
||||
@Column(name = "attempts", nullable = false)
|
||||
private int attempts;
|
||||
@Column(name = "used_at")
|
||||
private LocalDateTime usedAt;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "refresh_tokens")
|
||||
@Getter
|
||||
@Setter
|
||||
public class RefreshToken {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
@Column(name = "token_hash", nullable = false)
|
||||
private String tokenHash;
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private LocalDateTime expiresAt;
|
||||
@Column(name = "revoked_at")
|
||||
private LocalDateTime revokedAt;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
@Getter
|
||||
@Setter
|
||||
public class User {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@Column(name = "email", nullable = false)
|
||||
private String email;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
@UpdateTimestamp
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "user_roles")
|
||||
@Getter
|
||||
@Setter
|
||||
public class UserRole {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
@Column(name = "role", nullable = false)
|
||||
private String role;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import lombok.Getter;
|
||||
public enum ErrorCode {
|
||||
|
||||
VALIDATION_ERROR(400, "Некорректный запрос"),
|
||||
INVALID_GRANT(400, "Неверные учётные данные или код подтверждения"),
|
||||
INVALID_EMAIL(400, "Некорректный email"),
|
||||
INVALID_PHOTO(400, "Некорректный файл фотографии"),
|
||||
AREA_CYCLE(400, "Зона не может быть вложена в саму себя или своего потомка"),
|
||||
SET_NOT_READY(400, "Набор не готов к активации"),
|
||||
@@ -26,6 +28,7 @@ public enum ErrorCode {
|
||||
|
||||
PAYLOAD_TOO_LARGE(413, "Файл превышает допустимый размер"),
|
||||
UNSUPPORTED_MEDIA_TYPE(415, "Неподдерживаемый тип файла"),
|
||||
AUTH_CODE_RATE_LIMITED(429, "Код уже отправлен, повторите через минуту"),
|
||||
|
||||
NO_REFERENCE_PHOTO(503, "У достопримечательности нет эталонного фото с признаками"),
|
||||
REFERENCE_UNAVAILABLE(503, "Эталон недоступен или устарел, требуется пересчёт признаков"),
|
||||
|
||||
+3
-3
@@ -13,15 +13,15 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Извлекает client roles токена Keycloak из claim resource_access.<client_id>.roles.
|
||||
* Извлекает роли из claim resource_access.<client_id>.roles собственных access-токенов.
|
||||
* Роли используются как authorities с точным совпадением имён (manage_area, manage_attraction).
|
||||
*/
|
||||
@Component
|
||||
public class KeycloakJwtAuthenticationConverter implements Converter<Jwt, JwtAuthenticationToken> {
|
||||
public class ClientRolesJwtAuthenticationConverter implements Converter<Jwt, JwtAuthenticationToken> {
|
||||
|
||||
private final String clientId;
|
||||
|
||||
public KeycloakJwtAuthenticationConverter(@Value("${gorodar.keycloak.client-id}") String clientId) {
|
||||
public ClientRolesJwtAuthenticationConverter(@Value("${gorodar.auth.client-id}") String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package ru.gorodar.security;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import com.nimbusds.jose.jwk.JWKSet;
|
||||
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
@@ -9,15 +10,17 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
|
||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtValidators;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import ru.gorodar.auth.JwkKeys;
|
||||
import ru.gorodar.auth.TokenService;
|
||||
import ru.gorodar.config.AuthProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -27,11 +30,14 @@ public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain securityFilterChain(HttpSecurity http,
|
||||
Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter) throws Exception {
|
||||
Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter,
|
||||
JwtDecoder jwtDecoder) throws Exception {
|
||||
http
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
// собственная авторизация (email-код) и OIDC discovery — публичны
|
||||
.requestMatchers("/oauth2/**", "/.well-known/**").permitAll()
|
||||
// manage_area: зоны, наборы, статистика; manage_attraction: достопримечательности и эталоны
|
||||
.requestMatchers("/api/admin/attractions/**").hasAuthority("manage_attraction")
|
||||
.requestMatchers("/api/admin/areas/**", "/api/admin/sets/**", "/api/admin/visits/**")
|
||||
@@ -51,24 +57,18 @@ public class SecurityConfig {
|
||||
}
|
||||
|
||||
/**
|
||||
* Валидация по умолчанию (подпись/срок/issuer) плюс проверка, что токен выдан
|
||||
* нашему клиенту: audience содержит client_id либо azp равен ему.
|
||||
* Валидация собственных access-токенов по локальным ключам (без HTTP): подпись,
|
||||
* срок, issuer и audience = gorodar.
|
||||
*/
|
||||
@Bean
|
||||
JwtDecoder jwtDecoder(@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") String issuerUri,
|
||||
@Value("${gorodar.keycloak.client-id}") String clientId) {
|
||||
NimbusJwtDecoder decoder = NimbusJwtDecoder.withIssuerLocation(issuerUri).build();
|
||||
OAuth2TokenValidator<Jwt> defaultValidators = JwtValidators.createDefaultWithIssuer(issuerUri);
|
||||
OAuth2TokenValidator<Jwt> audienceValidator = jwt -> {
|
||||
List<String> audience = jwt.getAudience();
|
||||
String authorizedParty = jwt.getClaimAsString("azp");
|
||||
if ((audience != null && audience.contains(clientId)) || clientId.equals(authorizedParty)) {
|
||||
return OAuth2TokenValidatorResult.success();
|
||||
}
|
||||
return OAuth2TokenValidatorResult.failure(new OAuth2Error(
|
||||
"invalid_token", "Токен выдан не для клиента " + clientId, null));
|
||||
};
|
||||
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(defaultValidators, audienceValidator));
|
||||
JwtDecoder jwtDecoder(JwkKeys jwkKeys, AuthProperties properties) {
|
||||
NimbusJwtDecoder decoder = NimbusJwtDecoder
|
||||
.withJwkSource(new ImmutableJWKSet<>(new JWKSet(jwkKeys.getKey())))
|
||||
.build();
|
||||
OAuth2TokenValidator<Jwt> issuerAndExpiry = JwtValidators.createDefaultWithIssuer(properties.issuer());
|
||||
OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>("aud",
|
||||
aud -> aud != null && aud.contains(TokenService.AUDIENCE));
|
||||
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(issuerAndExpiry, audience));
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,11 +18,11 @@ spring:
|
||||
liquibase:
|
||||
change-log: classpath:db/changelog/db.changelog-master.yaml
|
||||
|
||||
security:
|
||||
oauth2:
|
||||
resourceserver:
|
||||
jwt:
|
||||
issuer-uri: ${GORODAR_KEYCLOAK_ISSUER:http://localhost:8081/realms/gorodar}
|
||||
mail:
|
||||
host: ${GORODAR_MAIL_HOST:}
|
||||
port: ${GORODAR_MAIL_PORT:587}
|
||||
username: ${GORODAR_MAIL_USERNAME:}
|
||||
password: ${GORODAR_MAIL_PASSWORD:}
|
||||
|
||||
servlet:
|
||||
multipart:
|
||||
@@ -30,8 +30,16 @@ spring:
|
||||
max-request-size: 22MB
|
||||
|
||||
gorodar:
|
||||
keycloak:
|
||||
auth:
|
||||
client-id: gorodar
|
||||
issuer: ${GORODAR_AUTH_ISSUER:http://localhost:8080}
|
||||
access-token-ttl: 24h
|
||||
refresh-token-ttl: 30d
|
||||
code-ttl: 10m
|
||||
resend-interval: 60s
|
||||
keys-dir: ${GORODAR_AUTH_KEYS_DIR:./keys}
|
||||
mail-log-only: ${GORODAR_AUTH_MAIL_LOG_ONLY:false}
|
||||
mail-from: ${GORODAR_MAIL_FROM:}
|
||||
opencv:
|
||||
base-url: ${GORODAR_OPENCV_URL:http://localhost:8000}
|
||||
api-key: ${GORODAR_OPENCV_API_KEY:dev-key}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
--liquibase formatted sql
|
||||
|
||||
--changeset gorodar:001-areas
|
||||
create table areas (
|
||||
id uuid primary key,
|
||||
parent_id uuid references areas (id),
|
||||
name varchar(255) not null,
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
updated_at timestamp not null default (now() at time zone 'utc')
|
||||
);
|
||||
|
||||
--changeset gorodar:001-areas-index-parent
|
||||
create index idx_areas_parent_id on areas (parent_id);
|
||||
@@ -0,0 +1,47 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: 001-areas
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: areas
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: parent_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_areas_parent_id
|
||||
references: areas(id)
|
||||
- column:
|
||||
name: name
|
||||
type: varchar(255)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: created_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: updated_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- changeSet:
|
||||
id: 001-areas-index-parent
|
||||
author: gorodar
|
||||
changes:
|
||||
- createIndex:
|
||||
indexName: idx_areas_parent_id
|
||||
tableName: areas
|
||||
columns:
|
||||
- column:
|
||||
name: parent_id
|
||||
@@ -1,37 +0,0 @@
|
||||
--liquibase formatted sql
|
||||
|
||||
--changeset gorodar:002-attractions
|
||||
create table attractions (
|
||||
id uuid primary key,
|
||||
area_id uuid not null references areas (id),
|
||||
name varchar(255) not null,
|
||||
icon_key varchar(512),
|
||||
about text,
|
||||
latitude numeric(9, 6),
|
||||
longitude numeric(9, 6),
|
||||
address varchar(512),
|
||||
facts jsonb,
|
||||
cv_profile varchar(32) not null,
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
updated_at timestamp not null default (now() at time zone 'utc')
|
||||
);
|
||||
|
||||
--changeset gorodar:002-attractions-index-area
|
||||
create index idx_attractions_area_id on attractions (area_id);
|
||||
|
||||
--changeset gorodar:002-attraction-photos
|
||||
create table attraction_photos (
|
||||
id uuid primary key,
|
||||
attraction_id uuid not null references attractions (id),
|
||||
s3_photo_key varchar(512) not null,
|
||||
s3_features_key varchar(512) not null,
|
||||
feature_format_version integer not null,
|
||||
algo_id varchar(64) not null,
|
||||
keypoints_count integer not null,
|
||||
sort_order integer not null,
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
constraint uq_attraction_photos_sort_order unique (attraction_id, sort_order)
|
||||
);
|
||||
|
||||
--changeset gorodar:002-attraction-photos-index-attraction
|
||||
create index idx_attraction_photos_attraction_id on attraction_photos (attraction_id);
|
||||
@@ -0,0 +1,141 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: 002-attractions
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: attractions
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: area_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_attractions_area_id
|
||||
references: areas(id)
|
||||
nullable: false
|
||||
- column:
|
||||
name: name
|
||||
type: varchar(255)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: icon_key
|
||||
type: varchar(512)
|
||||
- column:
|
||||
name: about
|
||||
type: text
|
||||
- column:
|
||||
name: latitude
|
||||
type: numeric(9,6)
|
||||
- column:
|
||||
name: longitude
|
||||
type: numeric(9,6)
|
||||
- column:
|
||||
name: address
|
||||
type: varchar(512)
|
||||
- column:
|
||||
name: facts
|
||||
type: jsonb
|
||||
- column:
|
||||
name: cv_profile
|
||||
type: varchar(32)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: created_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: updated_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- changeSet:
|
||||
id: 002-attractions-index-area
|
||||
author: gorodar
|
||||
changes:
|
||||
- createIndex:
|
||||
indexName: idx_attractions_area_id
|
||||
tableName: attractions
|
||||
columns:
|
||||
- column:
|
||||
name: area_id
|
||||
- changeSet:
|
||||
id: 002-attraction-photos
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: attraction_photos
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: attraction_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_attraction_photos_attraction_id
|
||||
references: attractions(id)
|
||||
nullable: false
|
||||
- column:
|
||||
name: s3_photo_key
|
||||
type: varchar(512)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: s3_features_key
|
||||
type: varchar(512)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: feature_format_version
|
||||
type: integer
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: algo_id
|
||||
type: varchar(64)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: keypoints_count
|
||||
type: integer
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: sort_order
|
||||
type: integer
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: created_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- addUniqueConstraint:
|
||||
tableName: attraction_photos
|
||||
columnNames: attraction_id, sort_order
|
||||
constraintName: uq_attraction_photos_sort_order
|
||||
- changeSet:
|
||||
id: 002-attraction-photos-index-attraction
|
||||
author: gorodar
|
||||
changes:
|
||||
- createIndex:
|
||||
indexName: idx_attraction_photos_attraction_id
|
||||
tableName: attraction_photos
|
||||
columns:
|
||||
- column:
|
||||
name: attraction_id
|
||||
@@ -1,31 +0,0 @@
|
||||
--liquibase formatted sql
|
||||
|
||||
--changeset gorodar:003-attraction-sets
|
||||
create table attraction_sets (
|
||||
id uuid primary key,
|
||||
area_id uuid not null references areas (id),
|
||||
name varchar(255) not null,
|
||||
status varchar(16) not null,
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
updated_at timestamp not null default (now() at time zone 'utc'),
|
||||
constraint ck_attraction_sets_status check (status in ('DRAFT', 'ACTIVE', 'ARCHIVED'))
|
||||
);
|
||||
|
||||
--changeset gorodar:003-attraction-sets-unique-active
|
||||
create unique index uq_attraction_sets_active_area on attraction_sets (area_id) where status = 'ACTIVE';
|
||||
|
||||
--changeset gorodar:003-attraction-sets-index-area
|
||||
create index idx_attraction_sets_area_id on attraction_sets (area_id);
|
||||
|
||||
--changeset gorodar:003-attraction-set-items
|
||||
create table attraction_set_items (
|
||||
id uuid primary key,
|
||||
set_id uuid not null references attraction_sets (id),
|
||||
attraction_id uuid not null references attractions (id),
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
constraint uq_attraction_set_items unique (set_id, attraction_id)
|
||||
);
|
||||
|
||||
--changeset gorodar:003-attraction-set-items-indexes
|
||||
create index idx_attraction_set_items_set_id on attraction_set_items (set_id);
|
||||
create index idx_attraction_set_items_attraction_id on attraction_set_items (attraction_id);
|
||||
@@ -0,0 +1,130 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: 003-attraction-sets
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: attraction_sets
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: area_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_attraction_sets_area_id
|
||||
references: areas(id)
|
||||
nullable: false
|
||||
- column:
|
||||
name: name
|
||||
type: varchar(255)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: status
|
||||
type: varchar(16)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: created_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: updated_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- changeSet:
|
||||
id: 003-attraction-sets-check-status
|
||||
author: gorodar
|
||||
comment: CHECK-констрейнт нельзя выразить нативным change-типом Liquibase (addCheckConstraint — платный) — осознанное sql-исключение
|
||||
changes:
|
||||
- sql:
|
||||
dbms: postgresql
|
||||
sql: alter table attraction_sets add constraint ck_attraction_sets_status check (status in ('DRAFT', 'ACTIVE', 'ARCHIVED'))
|
||||
rollback:
|
||||
- sql:
|
||||
dbms: postgresql
|
||||
sql: alter table attraction_sets drop constraint ck_attraction_sets_status
|
||||
- changeSet:
|
||||
id: 003-attraction-sets-unique-active
|
||||
author: gorodar
|
||||
comment: Partial unique index (WHERE) не поддержан createIndex — осознанное sql-исключение
|
||||
changes:
|
||||
- sql:
|
||||
dbms: postgresql
|
||||
sql: create unique index uq_attraction_sets_active_area on attraction_sets (area_id) where status = 'ACTIVE'
|
||||
rollback:
|
||||
- sql:
|
||||
dbms: postgresql
|
||||
sql: drop index uq_attraction_sets_active_area
|
||||
- changeSet:
|
||||
id: 003-attraction-sets-index-area
|
||||
author: gorodar
|
||||
changes:
|
||||
- createIndex:
|
||||
indexName: idx_attraction_sets_area_id
|
||||
tableName: attraction_sets
|
||||
columns:
|
||||
- column:
|
||||
name: area_id
|
||||
- changeSet:
|
||||
id: 003-attraction-set-items
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: attraction_set_items
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: set_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_attraction_set_items_set_id
|
||||
references: attraction_sets(id)
|
||||
nullable: false
|
||||
- column:
|
||||
name: attraction_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_attraction_set_items_attraction_id
|
||||
references: attractions(id)
|
||||
nullable: false
|
||||
- column:
|
||||
name: created_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- addUniqueConstraint:
|
||||
tableName: attraction_set_items
|
||||
columnNames: set_id, attraction_id
|
||||
constraintName: uq_attraction_set_items
|
||||
- changeSet:
|
||||
id: 003-attraction-set-items-indexes
|
||||
author: gorodar
|
||||
changes:
|
||||
- createIndex:
|
||||
indexName: idx_attraction_set_items_set_id
|
||||
tableName: attraction_set_items
|
||||
columns:
|
||||
- column:
|
||||
name: set_id
|
||||
- createIndex:
|
||||
indexName: idx_attraction_set_items_attraction_id
|
||||
tableName: attraction_set_items
|
||||
columns:
|
||||
- column:
|
||||
name: attraction_id
|
||||
@@ -1,17 +0,0 @@
|
||||
--liquibase formatted sql
|
||||
|
||||
--changeset gorodar:004-attraction-users-visits
|
||||
create table attraction_users_visits (
|
||||
id uuid primary key,
|
||||
user_id varchar(64) not null,
|
||||
attraction_id uuid not null references attractions (id),
|
||||
visited_at timestamp not null default (now() at time zone 'utc'),
|
||||
verdict varchar(16) not null,
|
||||
confidence numeric(5, 4),
|
||||
probe_sha256 varchar(64),
|
||||
constraint uq_visits_user_attraction unique (user_id, attraction_id)
|
||||
);
|
||||
|
||||
--changeset gorodar:004-visits-indexes
|
||||
create index idx_visits_user_id on attraction_users_visits (user_id);
|
||||
create index idx_visits_attraction_id on attraction_users_visits (attraction_id);
|
||||
@@ -0,0 +1,63 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: 004-attraction-users-visits
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: attraction_users_visits
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: user_id
|
||||
type: varchar(64)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: attraction_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_attraction_users_visits_attraction_id
|
||||
references: attractions(id)
|
||||
nullable: false
|
||||
- column:
|
||||
name: visited_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: verdict
|
||||
type: varchar(16)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: confidence
|
||||
type: numeric(5,4)
|
||||
- column:
|
||||
name: probe_sha256
|
||||
type: varchar(64)
|
||||
- addUniqueConstraint:
|
||||
tableName: attraction_users_visits
|
||||
columnNames: user_id, attraction_id
|
||||
constraintName: uq_visits_user_attraction
|
||||
- changeSet:
|
||||
id: 004-visits-indexes
|
||||
author: gorodar
|
||||
changes:
|
||||
- createIndex:
|
||||
indexName: idx_visits_user_id
|
||||
tableName: attraction_users_visits
|
||||
columns:
|
||||
- column:
|
||||
name: user_id
|
||||
- createIndex:
|
||||
indexName: idx_visits_attraction_id
|
||||
tableName: attraction_users_visits
|
||||
columns:
|
||||
- column:
|
||||
name: attraction_id
|
||||
@@ -0,0 +1,176 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: 005-users
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: users
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: email
|
||||
type: varchar(255)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: created_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: updated_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- addUniqueConstraint:
|
||||
tableName: users
|
||||
columnNames: email
|
||||
constraintName: uq_users_email
|
||||
- changeSet:
|
||||
id: 005-user-roles
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: user_roles
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: user_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_user_roles_user_id
|
||||
references: users(id)
|
||||
nullable: false
|
||||
- column:
|
||||
name: role
|
||||
type: varchar(64)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: created_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- addUniqueConstraint:
|
||||
tableName: user_roles
|
||||
columnNames: user_id, role
|
||||
constraintName: uq_user_roles
|
||||
- createIndex:
|
||||
indexName: idx_user_roles_user_id
|
||||
tableName: user_roles
|
||||
columns:
|
||||
- column:
|
||||
name: user_id
|
||||
- changeSet:
|
||||
id: 005-auth-codes
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: auth_codes
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: user_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_auth_codes_user_id
|
||||
references: users(id)
|
||||
nullable: false
|
||||
- column:
|
||||
name: code_hash
|
||||
type: varchar(64)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: expires_at
|
||||
type: timestamp
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: attempts
|
||||
type: integer
|
||||
defaultValueNumeric: 0
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: used_at
|
||||
type: timestamp
|
||||
- column:
|
||||
name: created_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- createIndex:
|
||||
indexName: idx_auth_codes_user_id
|
||||
tableName: auth_codes
|
||||
columns:
|
||||
- column:
|
||||
name: user_id
|
||||
- changeSet:
|
||||
id: 005-refresh-tokens
|
||||
author: gorodar
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: refresh_tokens
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: uuid
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
- column:
|
||||
name: user_id
|
||||
type: uuid
|
||||
constraints:
|
||||
foreignKeyName: fk_refresh_tokens_user_id
|
||||
references: users(id)
|
||||
nullable: false
|
||||
- column:
|
||||
name: token_hash
|
||||
type: varchar(64)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: expires_at
|
||||
type: timestamp
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: revoked_at
|
||||
type: timestamp
|
||||
- column:
|
||||
name: created_at
|
||||
type: timestamp
|
||||
defaultValueComputed: "(now() at time zone 'utc')"
|
||||
constraints:
|
||||
nullable: false
|
||||
- addUniqueConstraint:
|
||||
tableName: refresh_tokens
|
||||
columnNames: token_hash
|
||||
constraintName: uq_refresh_tokens_hash
|
||||
- createIndex:
|
||||
indexName: idx_refresh_tokens_user_id
|
||||
tableName: refresh_tokens
|
||||
columns:
|
||||
- column:
|
||||
name: user_id
|
||||
@@ -1,9 +1,11 @@
|
||||
databaseChangeLog:
|
||||
- include:
|
||||
file: db/changelog/changelogs/001-create-areas.sql
|
||||
file: db/changelog/changelogs/001-create-areas.yaml
|
||||
- include:
|
||||
file: db/changelog/changelogs/002-create-attractions.sql
|
||||
file: db/changelog/changelogs/002-create-attractions.yaml
|
||||
- include:
|
||||
file: db/changelog/changelogs/003-create-attraction-sets.sql
|
||||
file: db/changelog/changelogs/003-create-attraction-sets.yaml
|
||||
- include:
|
||||
file: db/changelog/changelogs/004-create-attraction-users-visits.sql
|
||||
file: db/changelog/changelogs/004-create-attraction-users-visits.yaml
|
||||
- include:
|
||||
file: db/changelog/changelogs/005-create-auth.yaml
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
package ru.gorodar.auth;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import ru.gorodar.auth.TokenService.IssuedAccessToken;
|
||||
import ru.gorodar.config.AuthProperties;
|
||||
import ru.gorodar.dao.AuthCodeRepository;
|
||||
import ru.gorodar.dao.RefreshTokenRepository;
|
||||
import ru.gorodar.dao.UserRepository;
|
||||
import ru.gorodar.dao.UserRoleRepository;
|
||||
import ru.gorodar.dao.entity.AuthCode;
|
||||
import ru.gorodar.dao.entity.RefreshToken;
|
||||
import ru.gorodar.dao.entity.User;
|
||||
import ru.gorodar.dao.entity.UserRole;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AuthServiceTest {
|
||||
|
||||
private static final String EMAIL = "user@example.com";
|
||||
private static final String CODE = "123456";
|
||||
|
||||
private final UUID userId = UUID.randomUUID();
|
||||
|
||||
@Mock
|
||||
private UserRepository userRepository;
|
||||
@Mock
|
||||
private UserRoleRepository userRoleRepository;
|
||||
@Mock
|
||||
private AuthCodeRepository authCodeRepository;
|
||||
@Mock
|
||||
private RefreshTokenRepository refreshTokenRepository;
|
||||
@Mock
|
||||
private TokenService tokenService;
|
||||
@Mock
|
||||
private MailCodeSender mailCodeSender;
|
||||
|
||||
private AuthProperties properties;
|
||||
|
||||
@InjectMocks
|
||||
private AuthService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
properties = new AuthProperties("http://localhost:8080", Duration.ofHours(24), Duration.ofDays(30),
|
||||
Duration.ofMinutes(10), Duration.ofSeconds(60), Path.of("keys"), false, "noreply");
|
||||
service = new AuthService(userRepository, userRoleRepository, authCodeRepository,
|
||||
refreshTokenRepository, tokenService, mailCodeSender, properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestCodeCreatesMissingUserAndStoresHashedCode() {
|
||||
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.empty());
|
||||
User created = user();
|
||||
when(userRepository.save(any(User.class))).thenReturn(created);
|
||||
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.empty());
|
||||
|
||||
service.requestCode(EMAIL);
|
||||
|
||||
verify(userRepository).save(any(User.class));
|
||||
verify(mailCodeSender).sendCode(eq(EMAIL), anyString());
|
||||
ArgumentCaptor<AuthCode> codeCaptor = ArgumentCaptor.forClass(AuthCode.class);
|
||||
verify(authCodeRepository).save(codeCaptor.capture());
|
||||
assertThat(codeCaptor.getValue().getCodeHash()).hasSize(64);
|
||||
assertThat(codeCaptor.getValue().getExpiresAt())
|
||||
.isAfter(LocalDateTime.now(ZoneOffset.UTC).plus(Duration.ofMinutes(9)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestCodeThrottledWithinResendInterval() {
|
||||
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.of(user()));
|
||||
AuthCode recent = new AuthCode();
|
||||
recent.setCreatedAt(LocalDateTime.now(ZoneOffset.UTC).minusSeconds(10));
|
||||
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.of(recent));
|
||||
|
||||
ApiException error = assertThrows(ApiException.class, () -> service.requestCode(EMAIL));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.AUTH_CODE_RATE_LIMITED);
|
||||
verify(authCodeRepository, never()).save(any(AuthCode.class));
|
||||
verify(mailCodeSender, never()).sendCode(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenByEmailCodeIssuesTokensAndMarksCodeUsed() {
|
||||
User user = user();
|
||||
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.of(user));
|
||||
AuthCode authCode = activeCode();
|
||||
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.of(authCode));
|
||||
stubIssueTokens(user);
|
||||
|
||||
AuthService.IssuedTokens tokens = service.tokenByEmailCode(EMAIL, CODE);
|
||||
|
||||
assertThat(tokens.accessToken()).isEqualTo("jwt");
|
||||
assertThat(tokens.refreshToken()).isNotBlank();
|
||||
assertThat(authCode.getUsedAt()).isNotNull();
|
||||
verify(refreshTokenRepository).save(any(RefreshToken.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrongCodeCountsAttemptAndFails() {
|
||||
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.of(user()));
|
||||
AuthCode authCode = activeCode();
|
||||
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.of(authCode));
|
||||
|
||||
ApiException error = assertThrows(ApiException.class,
|
||||
() -> service.tokenByEmailCode(EMAIL, "000000"));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.INVALID_GRANT);
|
||||
assertThat(authCode.getAttempts()).isEqualTo(1);
|
||||
assertThat(authCode.getUsedAt()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredCodeRejected() {
|
||||
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.of(user()));
|
||||
AuthCode expired = activeCode();
|
||||
expired.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).minusMinutes(1));
|
||||
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.of(expired));
|
||||
|
||||
ApiException error = assertThrows(ApiException.class,
|
||||
() -> service.tokenByEmailCode(EMAIL, CODE));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.INVALID_GRANT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenByRefreshRotatesOldToken() {
|
||||
User user = user();
|
||||
RefreshToken refresh = new RefreshToken();
|
||||
refresh.setId(UUID.randomUUID());
|
||||
refresh.setUser(user);
|
||||
refresh.setTokenHash(sha256Hex("refresh-value"));
|
||||
refresh.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).plusDays(1));
|
||||
when(refreshTokenRepository.findByTokenHash(sha256Hex("refresh-value"))).thenReturn(Optional.of(refresh));
|
||||
stubIssueTokens(user);
|
||||
|
||||
AuthService.IssuedTokens tokens = service.tokenByRefresh("refresh-value");
|
||||
|
||||
assertThat(tokens.accessToken()).isEqualTo("jwt");
|
||||
assertThat(refresh.getRevokedAt()).isNotNull();
|
||||
// два сохранения: отзыв старого refresh-токена и запись нового
|
||||
verify(refreshTokenRepository, times(2)).save(any(RefreshToken.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void revokedRefreshRejected() {
|
||||
RefreshToken refresh = new RefreshToken();
|
||||
refresh.setUser(user());
|
||||
refresh.setTokenHash(sha256Hex("refresh-value"));
|
||||
refresh.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).plusDays(1));
|
||||
refresh.setRevokedAt(LocalDateTime.now(ZoneOffset.UTC).minusMinutes(1));
|
||||
when(refreshTokenRepository.findByTokenHash(sha256Hex("refresh-value"))).thenReturn(Optional.of(refresh));
|
||||
|
||||
ApiException error = assertThrows(ApiException.class, () -> service.tokenByRefresh("refresh-value"));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.INVALID_GRANT);
|
||||
}
|
||||
|
||||
private void stubIssueTokens(User user) {
|
||||
when(userRoleRepository.findByUserId(userId)).thenReturn(List.of());
|
||||
when(tokenService.issueAccessToken(eq(user), any()))
|
||||
.thenReturn(new IssuedAccessToken("jwt", 86400));
|
||||
}
|
||||
|
||||
private User user() {
|
||||
User user = new User();
|
||||
user.setId(userId);
|
||||
user.setEmail(EMAIL);
|
||||
return user;
|
||||
}
|
||||
|
||||
private AuthCode activeCode() {
|
||||
AuthCode authCode = new AuthCode();
|
||||
authCode.setId(UUID.randomUUID());
|
||||
authCode.setUser(user());
|
||||
authCode.setCodeHash(sha256Hex(CODE));
|
||||
authCode.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).plusMinutes(10));
|
||||
authCode.setAttempts(0);
|
||||
return authCode;
|
||||
}
|
||||
|
||||
private String sha256Hex(String value) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package ru.gorodar.auth;
|
||||
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import ru.gorodar.config.AuthProperties;
|
||||
import ru.gorodar.dao.entity.User;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.text.ParseException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class TokenServiceTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void accessTokenCarriesOidcShapedClaims() throws ParseException {
|
||||
AuthProperties properties = new AuthProperties("http://localhost:8080", Duration.ofHours(24),
|
||||
Duration.ofDays(30), Duration.ofMinutes(10), Duration.ofSeconds(60), tempDir, false, "noreply");
|
||||
TokenService tokenService = new TokenService(new JwkKeys(properties), properties);
|
||||
User user = new User();
|
||||
user.setId(UUID.randomUUID());
|
||||
user.setEmail("user@example.com");
|
||||
|
||||
TokenService.IssuedAccessToken issued = tokenService.issueAccessToken(user, List.of("manage_area"));
|
||||
|
||||
assertThat(issued.expiresInSeconds()).isEqualTo(Duration.ofHours(24).toSeconds());
|
||||
SignedJWT jwt = SignedJWT.parse(issued.token());
|
||||
var claims = jwt.getJWTClaimsSet();
|
||||
assertThat(claims.getIssuer()).isEqualTo("http://localhost:8080");
|
||||
assertThat(claims.getSubject()).isEqualTo(user.getId().toString());
|
||||
assertThat(claims.getAudience()).containsExactly("gorodar");
|
||||
assertThat(claims.getClaim("email")).isEqualTo("user@example.com");
|
||||
Map<String, Object> resourceAccess = (Map<String, Object>) claims.getClaim("resource_access");
|
||||
assertThat(resourceAccess).isNotNull();
|
||||
Map<String, Object> clientAccess = (Map<String, Object>) resourceAccess.get("gorodar");
|
||||
assertThat((List<String>) clientAccess.get("roles")).containsExactly("manage_area");
|
||||
assertThat(claims.getExpirationTime().getTime() - claims.getIssueTime().getTime())
|
||||
.isEqualTo(Duration.ofHours(24).toMillis());
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -10,10 +10,10 @@ import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class KeycloakJwtAuthenticationConverterTest {
|
||||
class ClientRolesJwtAuthenticationConverterTest {
|
||||
|
||||
private final KeycloakJwtAuthenticationConverter converter =
|
||||
new KeycloakJwtAuthenticationConverter("gorodar");
|
||||
private final ClientRolesJwtAuthenticationConverter converter =
|
||||
new ClientRolesJwtAuthenticationConverter("gorodar");
|
||||
|
||||
@Test
|
||||
void convertsClientRolesToAuthorities() {
|
||||
Reference in New Issue
Block a user