initial
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
package com.aplp.backend;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
public class AplpBackendApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AplpBackendApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.aplp.backend.common.api;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record ApiError(
|
||||
Instant timestamp,
|
||||
int status,
|
||||
String error,
|
||||
String code,
|
||||
String message,
|
||||
String traceId
|
||||
) {
|
||||
|
||||
public static ApiError of(int status, String error, String code, String message, String traceId) {
|
||||
return new ApiError(Instant.now(), status, error, code, message, traceId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.aplp.backend.common.api;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public enum ErrorCode {
|
||||
|
||||
INVALID_ARGUMENT(HttpStatus.BAD_REQUEST),
|
||||
VALIDATION_FAILED(HttpStatus.BAD_REQUEST),
|
||||
MALFORMED_REQUEST(HttpStatus.BAD_REQUEST),
|
||||
UNAUTHENTICATED(HttpStatus.UNAUTHORIZED),
|
||||
INVALID_CREDENTIALS(HttpStatus.UNAUTHORIZED),
|
||||
INVALID_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED),
|
||||
ACCESS_DENIED(HttpStatus.FORBIDDEN),
|
||||
EMAIL_ALREADY_EXISTS(HttpStatus.CONFLICT),
|
||||
USER_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
LEARNER_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
INTERNAL_ERROR(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
|
||||
private final HttpStatus httpStatus;
|
||||
|
||||
ErrorCode(HttpStatus httpStatus) {
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
|
||||
public HttpStatus httpStatus() {
|
||||
return httpStatus;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.aplp.backend.common.api;
|
||||
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(DomainException.class)
|
||||
public ResponseEntity<ApiError> handleDomainException(DomainException ex) {
|
||||
HttpStatus status = ex.code().httpStatus();
|
||||
return build(status, ex.code().name(), ex.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ApiError> handleValidation(MethodArgumentNotValidException ex) {
|
||||
Map<String, String> details = new LinkedHashMap<>();
|
||||
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
|
||||
details.putIfAbsent(error.getField(), error.getDefaultMessage());
|
||||
}
|
||||
ApiError error = ApiError.of(
|
||||
HttpStatus.BAD_REQUEST.value(),
|
||||
HttpStatus.BAD_REQUEST.getReasonPhrase(),
|
||||
ErrorCode.VALIDATION_FAILED.name(),
|
||||
"Validation failed",
|
||||
requestId());
|
||||
return ResponseEntity.badRequest().body(error);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ApiError> handleUnreadable(HttpMessageNotReadableException ex) {
|
||||
return build(HttpStatus.BAD_REQUEST, ErrorCode.MALFORMED_REQUEST.name(), "Malformed request body");
|
||||
}
|
||||
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
public ResponseEntity<ApiError> handleNoResource(NoResourceFoundException ex) {
|
||||
return build(HttpStatus.NOT_FOUND, "NOT_FOUND", "Resource not found");
|
||||
}
|
||||
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
public ResponseEntity<ApiError> handleAuthentication(AuthenticationException ex) {
|
||||
return build(HttpStatus.UNAUTHORIZED, ErrorCode.UNAUTHENTICATED.name(), "Authentication required");
|
||||
}
|
||||
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ResponseEntity<ApiError> handleAccessDenied(AccessDeniedException ex) {
|
||||
return build(HttpStatus.FORBIDDEN, ErrorCode.ACCESS_DENIED.name(), "Access denied");
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiError> handleUnexpected(Exception ex, HttpServletRequest request) {
|
||||
log.error("Unhandled error on {} {}", request.getMethod(), request.getRequestURI(), ex);
|
||||
return build(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.INTERNAL_ERROR.name(), "Internal server error");
|
||||
}
|
||||
|
||||
private ResponseEntity<ApiError> build(HttpStatus status, String code, String message) {
|
||||
ApiError error = ApiError.of(
|
||||
status.value(),
|
||||
status.getReasonPhrase(),
|
||||
code,
|
||||
message,
|
||||
requestId());
|
||||
return ResponseEntity.status(status).body(error);
|
||||
}
|
||||
|
||||
private String requestId() {
|
||||
return MDC.get("requestId");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.aplp.backend.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
@Configuration
|
||||
public class CommonConfig {
|
||||
|
||||
@Bean
|
||||
Clock clock() {
|
||||
return Clock.systemUTC();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.aplp.backend.common.config;
|
||||
|
||||
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
|
||||
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
|
||||
import io.swagger.v3.oas.annotations.info.Info;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityScheme;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@OpenAPIDefinition(
|
||||
info = @Info(title = "APLP Backend API", version = "0.1.0", description = "Adaptive Personal Learning Platform (backend)"),
|
||||
security = @SecurityRequirement(name = "bearerAuth")
|
||||
)
|
||||
@SecurityScheme(
|
||||
name = "bearer",
|
||||
type = SecuritySchemeType.HTTP,
|
||||
scheme = "bearer",
|
||||
bearerFormat = "JWT"
|
||||
)
|
||||
public class OpenApiConfig {
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.aplp.backend.common.error;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
|
||||
public class DomainException extends RuntimeException {
|
||||
|
||||
private final ErrorCode code;
|
||||
|
||||
public DomainException(ErrorCode code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public ErrorCode code() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
public record AuthenticatedUser(Long userId, String email, String displayName) {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.cors")
|
||||
public record CorsProperties(
|
||||
List<String> allowedOrigins
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtTokenProvider tokenProvider;
|
||||
|
||||
public JwtAuthenticationFilter(JwtTokenProvider tokenProvider) {
|
||||
this.tokenProvider = tokenProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String token = resolveToken(request);
|
||||
if (token != null) {
|
||||
try {
|
||||
JwtClaims claims = tokenProvider.parse(token);
|
||||
Long userId = Long.valueOf(claims.subject());
|
||||
AuthenticatedUser principal = new AuthenticatedUser(userId, null, null);
|
||||
var authentication = new UsernamePasswordAuthenticationToken(
|
||||
principal,
|
||||
null,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
} catch (RuntimeException ex) {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String resolveToken(HttpServletRequest request) {
|
||||
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
if (header != null && header.startsWith("Bearer ")) {
|
||||
return header.substring(7);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record JwtClaims(String subject, Instant issuedAt, Instant expiration) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.jwt")
|
||||
public record JwtProperties(
|
||||
String secret,
|
||||
Duration accessTokenTtl,
|
||||
Duration refreshTokenTtl
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class JwtTokenProvider {
|
||||
|
||||
private final JwtProperties properties;
|
||||
private final SecretKey key;
|
||||
|
||||
public JwtTokenProvider(JwtProperties properties) {
|
||||
this.properties = properties;
|
||||
this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(properties.secret()));
|
||||
}
|
||||
|
||||
public String createAccessToken(AuthenticatedUser user) {
|
||||
Instant now = Instant.now();
|
||||
return Jwts.builder()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.subject(user.userId().toString())
|
||||
.claim("email", user.email())
|
||||
.claim("displayName", user.displayName())
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(now.plus(properties.accessTokenTtl())))
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String createRefreshToken(Long userId) {
|
||||
Instant now = Instant.now();
|
||||
return Jwts.builder()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.subject(userId.toString())
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(now.plus(properties.refreshTokenTtl())))
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public JwtClaims parse(String token) throws JwtException {
|
||||
Claims claims = Jwts.parser()
|
||||
.verifyWith(key)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
return new JwtClaims(claims.getSubject(), claims.getIssuedAt().toInstant(), claims.getExpiration().toInstant());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableMethodSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain securityFilterChain(HttpSecurity http,
|
||||
JwtAuthenticationFilter jwtAuthenticationFilter,
|
||||
SecurityErrorHandlers errorHandlers) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.cors(Customizer.withDefaults())
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(HttpMethod.POST,
|
||||
"/api/v1/auth/register",
|
||||
"/api/v1/auth/login",
|
||||
"/api/v1/auth/refresh").permitAll()
|
||||
.requestMatchers("/actuator/health/**", "/actuator/info").permitAll()
|
||||
.requestMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll()
|
||||
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.exceptionHandling(exceptions -> exceptions
|
||||
.authenticationEntryPoint(errorHandlers.authenticationEntryPoint())
|
||||
.accessDeniedHandler(errorHandlers.accessDeniedHandler()))
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
CorsConfigurationSource corsConfigurationSource(CorsProperties corsProperties) {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOrigins(corsProperties.allowedOrigins());
|
||||
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(List.of("*"));
|
||||
configuration.setAllowCredentials(true);
|
||||
configuration.setMaxAge(3600L);
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import com.aplp.backend.common.api.ApiError;
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class SecurityErrorHandlers {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public SecurityErrorHandlers(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public AuthenticationEntryPoint authenticationEntryPoint() {
|
||||
return (request, response, authException) ->
|
||||
write(response, HttpStatus.UNAUTHORIZED, ErrorCode.UNAUTHENTICATED.name(), "Authentication required");
|
||||
}
|
||||
|
||||
public AccessDeniedHandler accessDeniedHandler() {
|
||||
return (request, response, accessDeniedException) ->
|
||||
write(response, HttpStatus.FORBIDDEN, ErrorCode.ACCESS_DENIED.name(), "Access denied");
|
||||
}
|
||||
|
||||
private void write(HttpServletResponse response, HttpStatus status, String code, String message)
|
||||
throws IOException {
|
||||
ApiError body = ApiError.of(
|
||||
status.value(),
|
||||
status.getReasonPhrase(),
|
||||
code,
|
||||
message,
|
||||
MDC.get("requestId"));
|
||||
response.setStatus(status.value());
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.getWriter().write(objectMapper.writeValueAsString(body));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public final class SecurityUtils {
|
||||
|
||||
private SecurityUtils() {
|
||||
}
|
||||
|
||||
public static AuthenticatedUser currentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null || !(authentication.getPrincipal() instanceof AuthenticatedUser user)) {
|
||||
throw new DomainException(ErrorCode.UNAUTHENTICATED, "Authentication required");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
public static Long currentUserId() {
|
||||
return currentUser().userId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.aplp.backend.common.web;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class RequestIdFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String REQUEST_ID_HEADER = "X-Request-Id";
|
||||
public static final String REQUEST_ID_MDC_KEY = "requestId";
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String requestId = request.getHeader(REQUEST_ID_HEADER);
|
||||
if (requestId == null || requestId.isBlank()) {
|
||||
requestId = UUID.randomUUID().toString();
|
||||
}
|
||||
MDC.put(REQUEST_ID_MDC_KEY, requestId);
|
||||
response.setHeader(REQUEST_ID_HEADER, requestId);
|
||||
try {
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
MDC.remove(REQUEST_ID_MDC_KEY);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import com.aplp.backend.identity.application.AuthService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
public AuthController(AuthService authService) {
|
||||
this.authService = authService;
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public AuthResponse register(@Valid @RequestBody RegisterRequest request) {
|
||||
return AuthResponse.from(authService.register(request.email(), request.password(), request.displayName()));
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public AuthResponse login(@Valid @RequestBody LoginRequest request) {
|
||||
return AuthResponse.from(authService.login(request.email(), request.password()));
|
||||
}
|
||||
|
||||
@PostMapping("/refresh")
|
||||
public AuthResponse refresh(@Valid @RequestBody RefreshTokenRequest request) {
|
||||
return AuthResponse.from(authService.refresh(request.refreshToken()));
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void logout(@Valid @RequestBody RefreshTokenRequest request) {
|
||||
authService.logout(request.refreshToken());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import com.aplp.backend.identity.application.AuthResult;
|
||||
|
||||
public record AuthResponse(
|
||||
String accessToken,
|
||||
String refreshToken,
|
||||
String tokenType,
|
||||
long expiresIn,
|
||||
UserDto user
|
||||
) {
|
||||
|
||||
public static AuthResponse from(AuthResult result) {
|
||||
return new AuthResponse(
|
||||
result.accessToken(),
|
||||
result.refreshToken(),
|
||||
"Bearer",
|
||||
result.expiresInSeconds(),
|
||||
new UserDto(
|
||||
result.user().userId(),
|
||||
result.user().email(),
|
||||
result.user().displayName()));
|
||||
}
|
||||
|
||||
public record UserDto(Long id, String email, String displayName) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record LoginRequest(
|
||||
@NotBlank @Email(message = "must be a valid email") String email,
|
||||
@NotBlank String password
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record RefreshTokenRequest(
|
||||
@NotBlank String refreshToken
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record RegisterRequest(
|
||||
@NotBlank @Email(message = "must be a valid email") @Size(max = 320) String email,
|
||||
@NotBlank @Size(min = 8, max = 128, message = "must be between 8 and 128 characters") String password,
|
||||
@NotBlank @Size(max = 100) String displayName
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
import com.aplp.backend.common.security.AuthenticatedUser;
|
||||
|
||||
public record AuthResult(
|
||||
String accessToken,
|
||||
String refreshToken,
|
||||
long expiresInSeconds,
|
||||
AuthenticatedUser user
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
import com.aplp.backend.common.security.AuthenticatedUser;
|
||||
import com.aplp.backend.common.security.JwtClaims;
|
||||
import com.aplp.backend.common.security.JwtProperties;
|
||||
import com.aplp.backend.common.security.JwtTokenProvider;
|
||||
import com.aplp.backend.identity.domain.EmailAlreadyExistsException;
|
||||
import com.aplp.backend.identity.domain.InvalidCredentialsException;
|
||||
import com.aplp.backend.identity.domain.RefreshToken;
|
||||
import com.aplp.backend.identity.domain.RefreshTokenInvalidException;
|
||||
import com.aplp.backend.identity.domain.RefreshTokenRepository;
|
||||
import com.aplp.backend.identity.domain.User;
|
||||
import com.aplp.backend.identity.domain.UserRepository;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
|
||||
@Service
|
||||
public class AuthService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtTokenProvider tokenProvider;
|
||||
private final JwtProperties jwtProperties;
|
||||
private final LearnerProvisioner learnerProvisioner;
|
||||
private final Clock clock;
|
||||
|
||||
public AuthService(UserRepository userRepository,
|
||||
RefreshTokenRepository refreshTokenRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
JwtTokenProvider tokenProvider,
|
||||
JwtProperties jwtProperties,
|
||||
LearnerProvisioner learnerProvisioner,
|
||||
Clock clock) {
|
||||
this.userRepository = userRepository;
|
||||
this.refreshTokenRepository = refreshTokenRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.tokenProvider = tokenProvider;
|
||||
this.jwtProperties = jwtProperties;
|
||||
this.learnerProvisioner = learnerProvisioner;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthResult register(String email, String rawPassword, String displayName) {
|
||||
Instant now = clock.instant();
|
||||
String normalizedEmail = email.trim().toLowerCase();
|
||||
if (userRepository.existsByEmail(normalizedEmail)) {
|
||||
throw new EmailAlreadyExistsException(normalizedEmail);
|
||||
}
|
||||
User user = User.register(normalizedEmail, passwordEncoder.encode(rawPassword), displayName, now);
|
||||
User saved = userRepository.save(user);
|
||||
learnerProvisioner.provision(saved.id(), displayName);
|
||||
return issueTokens(saved);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthResult login(String email, String rawPassword) {
|
||||
String normalizedEmail = email.trim().toLowerCase();
|
||||
User user = userRepository.findByEmail(normalizedEmail).orElseThrow(InvalidCredentialsException::new);
|
||||
if (!passwordEncoder.matches(rawPassword, user.passwordHash())) {
|
||||
throw new InvalidCredentialsException();
|
||||
}
|
||||
return issueTokens(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthResult refresh(String rawRefreshToken) {
|
||||
Instant now = clock.instant();
|
||||
RefreshToken stored = refreshTokenRepository.findByTokenHash(TokenHasher.sha256Hex(rawRefreshToken))
|
||||
.orElseThrow(RefreshTokenInvalidException::new);
|
||||
if (stored.isExpired(now) || stored.isRevoked()) {
|
||||
throw new RefreshTokenInvalidException();
|
||||
}
|
||||
JwtClaims claims;
|
||||
try {
|
||||
claims = tokenProvider.parse(rawRefreshToken);
|
||||
} catch (RuntimeException ex) {
|
||||
throw new RefreshTokenInvalidException();
|
||||
}
|
||||
User user = userRepository.findById(stored.userId())
|
||||
.filter(u -> u.id().toString().equals(claims.subject()))
|
||||
.orElseThrow(RefreshTokenInvalidException::new);
|
||||
|
||||
stored.revoke(now);
|
||||
refreshTokenRepository.save(stored);
|
||||
return issueTokens(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void logout(String rawRefreshToken) {
|
||||
Instant now = clock.instant();
|
||||
refreshTokenRepository.findByTokenHash(TokenHasher.sha256Hex(rawRefreshToken))
|
||||
.ifPresent(token -> {
|
||||
token.revoke(now);
|
||||
refreshTokenRepository.save(token);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void logoutAll(Long userId) {
|
||||
Instant now = clock.instant();
|
||||
for (RefreshToken token : refreshTokenRepository.findAllByUserId(userId)) {
|
||||
if (!token.isRevoked()) {
|
||||
token.revoke(now);
|
||||
refreshTokenRepository.save(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private AuthResult issueTokens(User user) {
|
||||
Instant now = clock.instant();
|
||||
AuthenticatedUser principal = new AuthenticatedUser(user.id(), user.email(), user.displayName());
|
||||
String accessToken = tokenProvider.createAccessToken(principal);
|
||||
String rawRefreshToken = tokenProvider.createRefreshToken(user.id());
|
||||
RefreshToken refresh = RefreshToken.issue(
|
||||
user.id(),
|
||||
TokenHasher.sha256Hex(rawRefreshToken),
|
||||
now.plus(jwtProperties.refreshTokenTtl()),
|
||||
now);
|
||||
refreshTokenRepository.save(refresh);
|
||||
return new AuthResult(accessToken, rawRefreshToken, jwtProperties.accessTokenTtl().toSeconds(), principal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
public interface LearnerProvisioner {
|
||||
|
||||
void provision(Long userId, String displayName);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
final class TokenHasher {
|
||||
|
||||
private TokenHasher() {
|
||||
}
|
||||
|
||||
static String sha256Hex(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 not available", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
|
||||
public class EmailAlreadyExistsException extends DomainException {
|
||||
|
||||
public EmailAlreadyExistsException(String email) {
|
||||
super(ErrorCode.EMAIL_ALREADY_EXISTS, "Email is already registered: " + email);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
|
||||
public class InvalidCredentialsException extends DomainException {
|
||||
|
||||
public InvalidCredentialsException() {
|
||||
super(ErrorCode.INVALID_CREDENTIALS, "Invalid email or password");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class RefreshToken {
|
||||
|
||||
private Long id;
|
||||
private final Long userId;
|
||||
private final String tokenHash;
|
||||
private final Instant expiresAt;
|
||||
private Instant revokedAt;
|
||||
private final Instant createdAt;
|
||||
|
||||
private RefreshToken(Long id, Long userId, String tokenHash, Instant expiresAt, Instant revokedAt, Instant createdAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.tokenHash = tokenHash;
|
||||
this.expiresAt = expiresAt;
|
||||
this.revokedAt = revokedAt;
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public static RefreshToken issue(Long userId, String tokenHash, Instant expiresAt, Instant now) {
|
||||
return new RefreshToken(null, userId, tokenHash, expiresAt, null, now);
|
||||
}
|
||||
|
||||
public static RefreshToken reconstruct(Long id, Long userId, String tokenHash, Instant expiresAt,
|
||||
Instant revokedAt, Instant createdAt) {
|
||||
return new RefreshToken(id, userId, tokenHash, expiresAt, revokedAt, createdAt);
|
||||
}
|
||||
|
||||
public boolean isExpired(Instant now) {
|
||||
return now.isAfter(expiresAt);
|
||||
}
|
||||
|
||||
public boolean isRevoked() {
|
||||
return revokedAt != null;
|
||||
}
|
||||
|
||||
public void revoke(Instant now) {
|
||||
this.revokedAt = now;
|
||||
}
|
||||
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Long userId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public String tokenHash() {
|
||||
return tokenHash;
|
||||
}
|
||||
|
||||
public Instant expiresAt() {
|
||||
return expiresAt;
|
||||
}
|
||||
|
||||
public Instant revokedAt() {
|
||||
return revokedAt;
|
||||
}
|
||||
|
||||
public Instant createdAt() {
|
||||
return createdAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
|
||||
public class RefreshTokenInvalidException extends DomainException {
|
||||
|
||||
public RefreshTokenInvalidException() {
|
||||
super(ErrorCode.INVALID_REFRESH_TOKEN, "Refresh token is invalid or expired");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface RefreshTokenRepository {
|
||||
|
||||
Optional<RefreshToken> findByTokenHash(String tokenHash);
|
||||
|
||||
List<RefreshToken> findAllByUserId(Long userId);
|
||||
|
||||
RefreshToken save(RefreshToken token);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class User {
|
||||
|
||||
private Long id;
|
||||
private final String email;
|
||||
private String passwordHash;
|
||||
private String displayName;
|
||||
private UserStatus status;
|
||||
private final Instant createdAt;
|
||||
private Instant updatedAt;
|
||||
|
||||
private User(Long id, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.email = email;
|
||||
this.passwordHash = passwordHash;
|
||||
this.displayName = displayName;
|
||||
this.status = status;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public static User register(String email, String passwordHash, String displayName, Instant now) {
|
||||
return new User(null, normalizeEmail(email), passwordHash, displayName, UserStatus.ACTIVE, now, now);
|
||||
}
|
||||
|
||||
public static User reconstruct(Long id, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
return new User(id, email, passwordHash, displayName, status, createdAt, updatedAt);
|
||||
}
|
||||
|
||||
public void updatePasswordHash(String newHash, Instant now) {
|
||||
this.passwordHash = newHash;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
public void updateDisplayName(String newDisplayName, Instant now) {
|
||||
this.displayName = newDisplayName;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
private static String normalizeEmail(String email) {
|
||||
return email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String email() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public String passwordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public UserStatus status() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public Instant createdAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public Instant updatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository {
|
||||
|
||||
Optional<User> findByEmail(String email);
|
||||
|
||||
Optional<User> findById(Long id);
|
||||
|
||||
boolean existsByEmail(String email);
|
||||
|
||||
User save(User user);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
public enum UserStatus {
|
||||
ACTIVE,
|
||||
DISABLED
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Table(name = "refresh_token")
|
||||
public class RefreshTokenJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "token_hash", nullable = false, unique = true, length = 64)
|
||||
private String tokenHash;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private Instant expiresAt;
|
||||
|
||||
@Column(name = "revoked_at")
|
||||
private Instant revokedAt;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
protected RefreshTokenJpaEntity() {
|
||||
}
|
||||
|
||||
public RefreshTokenJpaEntity(Long id, Long userId, String tokenHash, Instant expiresAt,
|
||||
Instant revokedAt, Instant createdAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.tokenHash = tokenHash;
|
||||
this.expiresAt = expiresAt;
|
||||
this.revokedAt = revokedAt;
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getTokenHash() {
|
||||
return tokenHash;
|
||||
}
|
||||
|
||||
public void setTokenHash(String tokenHash) {
|
||||
this.tokenHash = tokenHash;
|
||||
}
|
||||
|
||||
public Instant getExpiresAt() {
|
||||
return expiresAt;
|
||||
}
|
||||
|
||||
public void setExpiresAt(Instant expiresAt) {
|
||||
this.expiresAt = expiresAt;
|
||||
}
|
||||
|
||||
public Instant getRevokedAt() {
|
||||
return revokedAt;
|
||||
}
|
||||
|
||||
public void setRevokedAt(Instant revokedAt) {
|
||||
this.revokedAt = revokedAt;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface RefreshTokenJpaRepository extends JpaRepository<RefreshTokenJpaEntity, Long> {
|
||||
|
||||
Optional<RefreshTokenJpaEntity> findByTokenHash(String tokenHash);
|
||||
|
||||
List<RefreshTokenJpaEntity> findAllByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import com.aplp.backend.identity.domain.RefreshToken;
|
||||
import com.aplp.backend.identity.domain.RefreshTokenRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class RefreshTokenRepositoryImpl implements RefreshTokenRepository {
|
||||
|
||||
private final RefreshTokenJpaRepository jpaRepository;
|
||||
|
||||
public RefreshTokenRepositoryImpl(RefreshTokenJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RefreshToken> findByTokenHash(String tokenHash) {
|
||||
return jpaRepository.findByTokenHash(tokenHash).map(RefreshTokenRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RefreshToken> findAllByUserId(Long userId) {
|
||||
return jpaRepository.findAllByUserId(userId).stream()
|
||||
.map(RefreshTokenRepositoryImpl::toDomain)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RefreshToken save(RefreshToken token) {
|
||||
RefreshTokenJpaEntity entity = toEntity(token);
|
||||
RefreshTokenJpaEntity saved = jpaRepository.save(entity);
|
||||
return toDomain(saved);
|
||||
}
|
||||
|
||||
private static RefreshTokenJpaEntity toEntity(RefreshToken token) {
|
||||
return new RefreshTokenJpaEntity(
|
||||
token.id(),
|
||||
token.userId(),
|
||||
token.tokenHash(),
|
||||
token.expiresAt(),
|
||||
token.revokedAt(),
|
||||
token.createdAt());
|
||||
}
|
||||
|
||||
private static RefreshToken toDomain(RefreshTokenJpaEntity entity) {
|
||||
return RefreshToken.reconstruct(
|
||||
entity.getId(),
|
||||
entity.getUserId(),
|
||||
entity.getTokenHash(),
|
||||
entity.getExpiresAt(),
|
||||
entity.getRevokedAt(),
|
||||
entity.getCreatedAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import com.aplp.backend.identity.domain.UserStatus;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 320)
|
||||
private String email;
|
||||
|
||||
@Column(name = "password_hash", nullable = false)
|
||||
private String passwordHash;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 20)
|
||||
private UserStatus status;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
protected UserJpaEntity() {
|
||||
}
|
||||
|
||||
public UserJpaEntity(Long id, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.email = email;
|
||||
this.passwordHash = passwordHash;
|
||||
this.displayName = displayName;
|
||||
this.status = status;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPasswordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public void setPasswordHash(String passwordHash) {
|
||||
this.passwordHash = passwordHash;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public UserStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(UserStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Instant getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public void setUpdatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserJpaRepository extends JpaRepository<UserJpaEntity, Long> {
|
||||
|
||||
boolean existsByEmail(String email);
|
||||
|
||||
java.util.Optional<UserJpaEntity> findByEmail(String email);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import com.aplp.backend.identity.domain.User;
|
||||
import com.aplp.backend.identity.domain.UserRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class UserRepositoryImpl implements UserRepository {
|
||||
|
||||
private final UserJpaRepository jpaRepository;
|
||||
|
||||
public UserRepositoryImpl(UserJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByEmail(String email) {
|
||||
return jpaRepository.findByEmail(email).map(UserRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findById(Long id) {
|
||||
return jpaRepository.findById(id).map(UserRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsByEmail(String email) {
|
||||
return jpaRepository.existsByEmail(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User save(User user) {
|
||||
UserJpaEntity entity = toEntity(user);
|
||||
UserJpaEntity saved = jpaRepository.save(entity);
|
||||
return toDomain(saved);
|
||||
}
|
||||
|
||||
private static UserJpaEntity toEntity(User user) {
|
||||
return new UserJpaEntity(
|
||||
user.id(),
|
||||
user.email(),
|
||||
user.passwordHash(),
|
||||
user.displayName(),
|
||||
user.status(),
|
||||
user.createdAt(),
|
||||
user.updatedAt());
|
||||
}
|
||||
|
||||
private static User toDomain(UserJpaEntity entity) {
|
||||
return User.reconstruct(
|
||||
entity.getId(),
|
||||
entity.getEmail(),
|
||||
entity.getPasswordHash(),
|
||||
entity.getDisplayName(),
|
||||
entity.getStatus(),
|
||||
entity.getCreatedAt(),
|
||||
entity.getUpdatedAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.aplp.backend.learner.api;
|
||||
|
||||
import com.aplp.backend.common.security.SecurityUtils;
|
||||
import com.aplp.backend.learner.application.LearnerService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/learners/me")
|
||||
public class LearnerController {
|
||||
|
||||
private final LearnerService learnerService;
|
||||
|
||||
public LearnerController(LearnerService learnerService) {
|
||||
this.learnerService = learnerService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public LearnerProfileResponse getMyProfile() {
|
||||
return LearnerProfileResponse.from(learnerService.getProfile(SecurityUtils.currentUserId()));
|
||||
}
|
||||
|
||||
@PatchMapping
|
||||
public LearnerProfileResponse updateMyProfile(@Valid @RequestBody UpdateLearnerProfileRequest request) {
|
||||
return LearnerProfileResponse.from(
|
||||
learnerService.updateDisplayName(SecurityUtils.currentUserId(), request.displayName()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.aplp.backend.learner.api;
|
||||
|
||||
import com.aplp.backend.learner.application.LearnerProfile;
|
||||
|
||||
public record LearnerProfileResponse(
|
||||
Long id,
|
||||
Long userId,
|
||||
String displayName
|
||||
) {
|
||||
|
||||
public static LearnerProfileResponse from(LearnerProfile profile) {
|
||||
return new LearnerProfileResponse(profile.id(), profile.userId(), profile.displayName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.aplp.backend.learner.api;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record UpdateLearnerProfileRequest(
|
||||
@NotBlank @Size(max = 100) String displayName
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.aplp.backend.learner.application;
|
||||
|
||||
public record LearnerProfile(
|
||||
Long id,
|
||||
Long userId,
|
||||
String displayName
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.aplp.backend.learner.application;
|
||||
|
||||
import com.aplp.backend.identity.application.LearnerProvisioner;
|
||||
import com.aplp.backend.learner.domain.Learner;
|
||||
import com.aplp.backend.learner.domain.LearnerRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
@Service
|
||||
public class LearnerProvisionerImpl implements LearnerProvisioner {
|
||||
|
||||
private final LearnerRepository learnerRepository;
|
||||
private final Clock clock;
|
||||
|
||||
public LearnerProvisionerImpl(LearnerRepository learnerRepository, Clock clock) {
|
||||
this.learnerRepository = learnerRepository;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void provision(Long userId, String displayName) {
|
||||
learnerRepository.save(Learner.create(userId, displayName, clock.instant()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.aplp.backend.learner.application;
|
||||
|
||||
import com.aplp.backend.learner.domain.Learner;
|
||||
import com.aplp.backend.learner.domain.LearnerNotFoundException;
|
||||
import com.aplp.backend.learner.domain.LearnerRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
@Service
|
||||
public class LearnerService {
|
||||
|
||||
private final LearnerRepository learnerRepository;
|
||||
private final Clock clock;
|
||||
|
||||
public LearnerService(LearnerRepository learnerRepository, Clock clock) {
|
||||
this.learnerRepository = learnerRepository;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public LearnerProfile getProfile(Long userId) {
|
||||
return learnerRepository.findByUserId(userId)
|
||||
.map(LearnerService::toProfile)
|
||||
.orElseThrow(LearnerNotFoundException::new);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LearnerProfile updateDisplayName(Long userId, String displayName) {
|
||||
Learner learner = learnerRepository.findByUserId(userId).orElseThrow(LearnerNotFoundException::new);
|
||||
learner.updateDisplayName(displayName, clock.instant());
|
||||
return toProfile(learnerRepository.save(learner));
|
||||
}
|
||||
|
||||
private static LearnerProfile toProfile(Learner learner) {
|
||||
return new LearnerProfile(learner.id(), learner.userId(), learner.displayName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.aplp.backend.learner.domain;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class Learner {
|
||||
|
||||
private Long id;
|
||||
private final Long userId;
|
||||
private String displayName;
|
||||
private final Instant createdAt;
|
||||
private Instant updatedAt;
|
||||
|
||||
private Learner(Long id, Long userId, String displayName, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.displayName = displayName;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public static Learner create(Long userId, String displayName, Instant now) {
|
||||
return new Learner(null, userId, displayName, now, now);
|
||||
}
|
||||
|
||||
public static Learner reconstruct(Long id, Long userId, String displayName, Instant createdAt, Instant updatedAt) {
|
||||
return new Learner(id, userId, displayName, createdAt, updatedAt);
|
||||
}
|
||||
|
||||
public void updateDisplayName(String newDisplayName, Instant now) {
|
||||
this.displayName = newDisplayName;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Long userId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public Instant createdAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public Instant updatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.learner.domain;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
|
||||
public class LearnerNotFoundException extends DomainException {
|
||||
|
||||
public LearnerNotFoundException() {
|
||||
super(ErrorCode.LEARNER_NOT_FOUND, "Learner profile not found");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.aplp.backend.learner.domain;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface LearnerRepository {
|
||||
|
||||
Optional<Learner> findByUserId(Long userId);
|
||||
|
||||
Learner save(Learner learner);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.aplp.backend.learner.persistence;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Table(name = "learner")
|
||||
public class LearnerJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false, unique = true)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
protected LearnerJpaEntity() {
|
||||
}
|
||||
|
||||
public LearnerJpaEntity(Long id, Long userId, String displayName, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.displayName = displayName;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Instant getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public void setUpdatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.aplp.backend.learner.persistence;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface LearnerJpaRepository extends JpaRepository<LearnerJpaEntity, Long> {
|
||||
|
||||
Optional<LearnerJpaEntity> findByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.aplp.backend.learner.persistence;
|
||||
|
||||
import com.aplp.backend.learner.domain.Learner;
|
||||
import com.aplp.backend.learner.domain.LearnerRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class LearnerRepositoryImpl implements LearnerRepository {
|
||||
|
||||
private final LearnerJpaRepository jpaRepository;
|
||||
|
||||
public LearnerRepositoryImpl(LearnerJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Learner> findByUserId(Long userId) {
|
||||
return jpaRepository.findByUserId(userId).map(LearnerRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Learner save(Learner learner) {
|
||||
LearnerJpaEntity entity = toEntity(learner);
|
||||
return toDomain(jpaRepository.save(entity));
|
||||
}
|
||||
|
||||
private static LearnerJpaEntity toEntity(Learner learner) {
|
||||
return new LearnerJpaEntity(
|
||||
learner.id(),
|
||||
learner.userId(),
|
||||
learner.displayName(),
|
||||
learner.createdAt(),
|
||||
learner.updatedAt());
|
||||
}
|
||||
|
||||
private static Learner toDomain(LearnerJpaEntity entity) {
|
||||
return Learner.reconstruct(
|
||||
entity.getId(),
|
||||
entity.getUserId(),
|
||||
entity.getDisplayName(),
|
||||
entity.getCreatedAt(),
|
||||
entity.getUpdatedAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: ${DB_URL:jdbc:postgresql://localhost:5432/aplp}
|
||||
username: ${DB_USERNAME:postgres}
|
||||
password: ${DB_PASSWORD:Pa55w0rd}
|
||||
hikari:
|
||||
maximum-pool-size: ${DB_POOL_SIZE:10}
|
||||
jpa:
|
||||
properties:
|
||||
hibernate:
|
||||
format_sql: true
|
||||
show-sql: ${JPA_SHOW_SQL:false}
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.aplp.backend: DEBUG
|
||||
@@ -0,0 +1,11 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: ${DB_URL}
|
||||
username: ${DB_USERNAME}
|
||||
password: ${DB_PASSWORD}
|
||||
hikari:
|
||||
maximum-pool-size: ${DB_POOL_SIZE:20}
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.aplp.backend: INFO
|
||||
@@ -0,0 +1,54 @@
|
||||
spring:
|
||||
application:
|
||||
name: aplp-backend
|
||||
profiles:
|
||||
default: dev
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
open-in-view: false
|
||||
flyway:
|
||||
enabled: true
|
||||
locations: classpath:db/migration
|
||||
jackson:
|
||||
default-property-inclusion: non_null
|
||||
|
||||
springdoc:
|
||||
swagger-ui:
|
||||
path: /swagger-ui.html
|
||||
operations-sorter: method
|
||||
|
||||
server:
|
||||
port: ${SERVER_PORT:8080}
|
||||
shutdown: graceful
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health,info,metrics
|
||||
endpoint:
|
||||
health:
|
||||
probes:
|
||||
enabled: true
|
||||
show-details: when_authorized
|
||||
show-components: when_authorized
|
||||
health:
|
||||
livenessstate:
|
||||
enabled: true
|
||||
readinessstate:
|
||||
enabled: true
|
||||
|
||||
logging:
|
||||
pattern:
|
||||
level: "%5p [%X{requestId:-}]"
|
||||
|
||||
app:
|
||||
jwt:
|
||||
# Dev-only default. MUST be overridden via JWT_SECRET in non-dev environments.
|
||||
secret: ${JWT_SECRET:Y29tbWl0LW5vdGhpbmctZGV2LXNlY3JldC1jaGFuZ2UtbWUtaW4tcHJvZHVjdGlvbi0xMjM0NTY3ODkw}
|
||||
access-token-ttl: ${JWT_ACCESS_TTL:15m}
|
||||
refresh-token-ttl: ${JWT_REFRESH_TTL:30d}
|
||||
cors:
|
||||
allowed-origins:
|
||||
- http://localhost:5173
|
||||
@@ -0,0 +1,34 @@
|
||||
CREATE TABLE users (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
email VARCHAR(320) NOT NULL,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT uq_users_email UNIQUE (email)
|
||||
);
|
||||
|
||||
CREATE TABLE refresh_token (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
token_hash VARCHAR(64) NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
revoked_at TIMESTAMP WITH TIME ZONE,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_refresh_token_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT uq_refresh_token_hash UNIQUE (token_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE learner (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT uq_learner_user UNIQUE (user_id),
|
||||
CONSTRAINT fk_learner_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_refresh_token_user_id ON refresh_token (user_id);
|
||||
CREATE INDEX idx_users_email ON users (email);
|
||||
Reference in New Issue
Block a user