上传到git

This commit is contained in:
2025-05-21 15:05:12 +09:00
commit 0a8e30dbd7
27 changed files with 1543 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package co.jp.springp0421.dogdemo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("co.jp.springp0421.dogdemo.repository")
public class DogDemoApplication {
public static void main(String[] args) {
SpringApplication.run(DogDemoApplication.class, args);
}
}

View File

@ -0,0 +1,44 @@
package co.jp.springp0421.dogdemo.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiResponse<T> {
//成功状况判定
private boolean success;
//状态码
private int code;
//状态信息
private String message;
//数据
private T data;
public static <T> ApiResponse<T> success(T data) {
return new ApiResponse<>(true, ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
public static <T> ApiResponse<T> success() { // 通常也会有一个不带数据的成功响应
return new ApiResponse<>(true, ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
}
public static <T> ApiResponse<T> fail(ResultCode resultCode) {
if (resultCode == ResultCode.SUCCESS) {
throw new IllegalArgumentException("Cannot use SUCCESS ResultCode for fail method. Use a specific error code.");
}
// 修正success 应为 false并从 resultCode 获取 code 和 message
return new ApiResponse<>(false, resultCode.getCode(), resultCode.getMessage(), null);
}
public static <T> ApiResponse<T> fail(ResultCode resultCode, T data) {
if (resultCode == ResultCode.SUCCESS) {
throw new IllegalArgumentException("Cannot use SUCCESS ResultCode for fail method. Use a specific error code.");
}
// 修正success 应为 false并从 resultCode 获取 code 和 message
return new ApiResponse<>(false, resultCode.getCode(), resultCode.getMessage(), data);
}
}

View File

@ -0,0 +1,82 @@
package co.jp.springp0421.dogdemo.common;
import lombok.Getter;
@Getter
public enum ResultCode {
SUCCESS(200, "Success"),
// 客户端错误段 (1000 - 1999)
BAD_REQUEST(1000, "HTTP 400 Bad Request"),
UNAUTHORIZED(1001, "HTTP 401 Unauthorized"),
FORBIDDEN(1002, "HTTP 403 Forbidden"),
NOT_FOUND(1003, "HTTP 404 Not Found"),
METHOD_NOT_ALLOWED(1004, "HTTP 405 Method Not Allowed"),
REQUEST_TIMEOUT(1005, "HTTP 408 Request Timeout"),
CONFLICT(1006, "HTTP 409 Conflict"),
UNSUPPORTED_MEDIA_TYPE(1007, "HTTP 415 Unsupported Media Type"),
TOO_MANY_REQUESTS(1008, "HTTP 429 Too Many Requests"),
VALIDATION_ERROR(1009, "Parameter validation failure"),
// 服务端错误段 (2000 - 2999)
INTERNAL_SERVER_ERROR(2000, "HTTP 500 Internal Server Error"),
SERVICE_UNAVAILABLE(2001, "HTTP 503 Service Unavailable"),
GATEWAY_TIMEOUT(2002, "HTTP 504 Gateway Timeout"),
DATABASE_ERROR(2003, "Database error"),
NETWORK_ERROR(2004, "Network error"),
THIRD_PARTY_SERVICE_ERROR(2005, "Third-party service error"),
// ================================== 用户模块状态码 (3000 - 3999) ==================================
// 注册相关
// USER_REGISTRATION_SUCCESS(3000, "用户注册成功"),
USER_EMAIL_ALREADY_EXISTS(3001, "Email already exists"),
USER_USERNAME_ALREADY_EXISTS(3002, "Username"),
USER_EMAIL_NOT_VALID(3006, "Email is not valid"),
USER_PASSWORD_TOO_SHORT(3003, "password too short"),
USER_PASSWORD_TOO_WEAK(3004, "password too weak"),
USER_REGISTRATION_FAILED(3005, "User registration failed"),
// 登录相关
// USER_LOGIN_SUCCESS(3100, "登录成功"),
USER_ACCOUNT_NOT_FOUND(3101, "User account not found"),
USER_INVALID_CREDENTIALS(3102, "User invalid credentials"),
USER_ACCOUNT_LOCKED(3103, "User account locked"),
USER_ACCOUNT_DISABLED(3104, "User account disabled"),
USER_ACCOUNT_EXPIRED(3105, "User account expired"),
USER_LOGIN_FAILED(3106, "User login failed"),
USER_SESSION_EXPIRED(3107, "User session expired"),
USER_TOKEN_INVALID(3108, "User token invalid"),
USER_TOKEN_EXPIRED(3109, "User token expired(Token"),
USER_REFRESH_TOKEN_INVALID(3110, "User refresh token invalid"),
// USER_REFRESH_TOKEN_EXPIRED(3111, "User refresh token expired(Refresh Token"),
USER_LOGOUT_SUCCESS(3112, "loignout success"),
// 用户信息相关
USER_PROFILE_NOT_FOUND(3200, "User profile not found"),
USER_UPDATE_PROFILE_SUCCESS(3201, "User profile updated"),
USER_UPDATE_PROFILE_FAILED(3202, "User profile update failed"),
USER_CHANGE_PASSWORD_SUCCESS(3203, "Change password success"),
USER_CHANGE_PASSWORD_FAILED(3204, "Change password failed"),
USER_OLD_PASSWORD_MISMATCH(3205, "Old password mismatch"),
// 权限相关 (如果你的用户模块包含复杂权限)
// USER_PERMISSION_DENIED(3300, "用户权限不足(细粒度)"), // 可用于补充 FORBIDDEN
;
private final int code;
private final String message;
ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
public String getMessage(String customDetail) {
return this.message + (customDetail == null || customDetail.isEmpty() ? "" : " (" + customDetail + ")");
}
}

View File

@ -0,0 +1,17 @@
package co.jp.springp0421.dogdemo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**") // 允许 /api/ 下的所有请求
.allowedOrigins("http://localhost:1024") // 允许来自该域的请求
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的 HTTP 方法
.allowedHeaders("*"); // 允许所有头部
}
}

View File

@ -0,0 +1,64 @@
package co.jp.springp0421.dogdemo.config.security;
import co.jp.springp0421.dogdemo.config.security.filter.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
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.core.userdetails.UserDetailsService;
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;
@Configuration
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final UserDetailsService userDetailsService;
public SecurityConfig(@Lazy JwtAuthenticationFilter jwtAuthenticationFilter, @Lazy UserDetailsService userDetailsService) {
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
this.userDetailsService = userDetailsService;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
// http config
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/user/login", "/api/user/register", "/api/inuhouse", "/api/dogs/pet").permitAll()
.anyRequest().authenticated()
)
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}

View File

@ -0,0 +1,61 @@
package co.jp.springp0421.dogdemo.config.security.filter;
import co.jp.springp0421.dogdemo.service.JwtService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final UserDetailsService userDetailsService;
public JwtAuthenticationFilter(JwtService jwtService, UserDetailsService userDetailsService) {
this.jwtService = jwtService;
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String username;
//不需要token直接返回Chain
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
//透过token读取username
jwt = authHeader.substring(7);
username = jwtService.extractUsername(jwt);
//如果username为空且认证为空
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtService.isTokenValid(jwt, userDetails)) {
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}
}

View File

@ -0,0 +1,67 @@
package co.jp.springp0421.dogdemo.controller;
import co.jp.springp0421.dogdemo.common.ApiResponse;
import co.jp.springp0421.dogdemo.dto.LoginDto;
import co.jp.springp0421.dogdemo.dto.RegistrationDto;
import co.jp.springp0421.dogdemo.dto.UserDto;
import co.jp.springp0421.dogdemo.entity.UserEntity;
import co.jp.springp0421.dogdemo.service.JwtService;
import co.jp.springp0421.dogdemo.service.UserService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class UserController {
private final UserService userService;
private final AuthenticationManager authenticationManager;
private final JwtService jwtService;
public UserController(UserService userService, AuthenticationManager authenticationManager, JwtService jwtService) {
this.userService = userService;
this.authenticationManager = authenticationManager;
this.jwtService = jwtService;
}
@PostMapping("/api/user/register")
public ResponseEntity<ApiResponse<UserDto>> registerUser(@Valid @RequestBody RegistrationDto registrationDto) {
UserEntity registeredUser = userService.registerNewUser(registrationDto);
UserDto userDto = new UserDto();
userDto.setEmail(registeredUser.getEmail());
userDto.setName(registeredUser.getName());
return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(userDto));
}
@PostMapping("/api/user/login")
public ResponseEntity<ApiResponse<Map<String, String>>> authenticateUser(@Valid @RequestBody LoginDto loginDto) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String jwtToken = jwtService.generateToken(userDetails);
Map<String, String> tokenResponse = new HashMap<>();
tokenResponse.put("token", jwtToken);
return ResponseEntity.ok(ApiResponse.success(tokenResponse));
}
}

View File

@ -0,0 +1,32 @@
package co.jp.springp0421.dogdemo.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class LoginDto {
@NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱格式不正确,请输入有效的邮箱地址")
private String email;
@NotBlank(message = "密码不能为空")
@Size(min = 6, max = 30, message = "密码长度必须在6到30位之间")
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,49 @@
package co.jp.springp0421.dogdemo.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
public class RegistrationDto {
//注username可以为空
@Size(min = 2, max = 20, message = "用户名长度必须在2到20个字符之间")
@Pattern(
regexp = "^[a-zA-Z\\p{script=Han}]+$",
message = "用户名只能包含大小写英文字母和汉字,不能使用数字和标点符号"
)
private String name;
@NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱格式不正确,请输入有效的邮箱地址")
private String email;
@NotBlank(message = "密码不能为空")
@Size(min = 6, max = 30, message = "密码长度必须在6到30位之间")
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,24 @@
package co.jp.springp0421.dogdemo.dto;
public class UserDto {
private String email;
private String name;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,30 @@
package co.jp.springp0421.dogdemo.entity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class PetEntity {
private int ID;
//犬の名前
private String name;
//犬の種類
private String type;
//犬の誕生日
private String brithday;
//犬の体重
private int weight;
//犬の身長
private int lenght;
//犬の性格
private String persionarity;
//犬の健康状態
private String status;
//犬の圖片
private String image;
}

View File

@ -0,0 +1,20 @@
package co.jp.springp0421.dogdemo.entity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class UserEntity {
private int id;
//name,null
private String name;
//login email
private String email;
private String password;
}

View File

@ -0,0 +1,38 @@
package co.jp.springp0421.dogdemo.exception;
import co.jp.springp0421.dogdemo.common.ResultCode;
public class BusinessException extends RuntimeException {
private final ResultCode resultCode;
private final String detailMessage; // 附加详细信息
public BusinessException(ResultCode resultCode) {
super(resultCode.getMessage());
this.resultCode = resultCode;
this.detailMessage = null;
}
// 有详细信息的构造函数
public BusinessException(ResultCode resultCode, String detailMessage) {
super(detailMessage != null && !detailMessage.isEmpty() ? detailMessage : resultCode.getMessage());
this.resultCode = resultCode;
this.detailMessage = detailMessage;
}
// 无详细信息的构造函数
public BusinessException(ResultCode resultCode, Throwable cause) {
super(resultCode.getMessage(), cause);
this.resultCode = resultCode;
this.detailMessage = null;
}
public ResultCode getResultCode() {
return resultCode;
}
public String getDetailMessage() {
return detailMessage;
}
}

View File

@ -0,0 +1,124 @@
package co.jp.springp0421.dogdemo.exception;
import co.jp.springp0421.dogdemo.common.ApiResponse;
import co.jp.springp0421.dogdemo.common.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.stream.Collectors;
@RestControllerAdvice
public class GlobalExceptionHandler {
// slf4j日志记录器
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
// 业务异常
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ApiResponse<Object>> handleBusinessException(BusinessException ex) {
logger.warn("业务异常: Code={}, Message={}, Detail={}", ex.getResultCode().getCode(), ex.getResultCode().getMessage(), ex.getDetailMessage(), ex);
ApiResponse<Object> body;
if (ex.getDetailMessage() != null && !ex.getDetailMessage().isEmpty()) {
body = ApiResponse.fail(ex.getResultCode(), ex.getDetailMessage());
} else {
body = ApiResponse.fail(ex.getResultCode());
}
HttpStatus httpStatus = determineHttpStatusFromResultCode(ex.getResultCode());
return new ResponseEntity<>(body, httpStatus);
}
// 参数校验异常
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
public ResponseEntity<ApiResponse<Object>> handleValidationExceptions(BindException ex) { // BindException 是 MethodArgumentNotValidException 的父类
String errorMessage = ex.getBindingResult().getFieldErrors().stream()
.map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
.collect(Collectors.joining("; "));
logger.warn("参数校验失败: {}", errorMessage, ex);
return new ResponseEntity<>(ApiResponse.fail(ResultCode.VALIDATION_ERROR, errorMessage), HttpStatus.BAD_REQUEST);
}
// 参数缺失异常
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<ApiResponse<Object>> handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) {
String message = "请求参数 '" + ex.getParameterName() + "' 不能为空";
logger.warn(message, ex);
return new ResponseEntity<>(ApiResponse.fail(ResultCode.BAD_REQUEST, message), HttpStatus.BAD_REQUEST);
}
// Spring Security 用户认证异常
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<ApiResponse<Object>> handleAuthenticationException(AuthenticationException ex) {
logger.warn("认证失败: {}", ex.getMessage(), ex);
if (ex instanceof BadCredentialsException) {
return new ResponseEntity<>(ApiResponse.fail(ResultCode.USER_INVALID_CREDENTIALS), HttpStatus.UNAUTHORIZED);
} else if (ex instanceof UsernameNotFoundException) {
return new ResponseEntity<>(ApiResponse.fail(ResultCode.USER_INVALID_CREDENTIALS, "用户名或密码错误(用户不存在)"), HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(ApiResponse.fail(ResultCode.UNAUTHORIZED, ex.getMessage()), HttpStatus.UNAUTHORIZED);
}
// Spring Security 权限异常
// @ExceptionHandler(AccessDeniedException.class)
// public ResponseEntity<ApiResponse<Object>> handleAccessDeniedException(AccessDeniedException ex) {
// logger.warn("权限不足: {}", ex.getMessage(), ex);
// return new ResponseEntity<>(ApiResponse.fail(ResultCode.FORBIDDEN), HttpStatus.FORBIDDEN);
// }
// 其他异常
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Object>> handleAllUncaughtException(Exception ex) {
logger.error("发生未捕获的服务器内部错误!", ex);
return new ResponseEntity<>(ApiResponse.fail(ResultCode.INTERNAL_SERVER_ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
private HttpStatus determineHttpStatusFromResultCode(ResultCode resultCode) {
if (resultCode == null) return HttpStatus.INTERNAL_SERVER_ERROR;
switch (resultCode) {
case SUCCESS:
return HttpStatus.OK;
case UNAUTHORIZED:
case USER_INVALID_CREDENTIALS:
case USER_TOKEN_INVALID:
case USER_TOKEN_EXPIRED:
return HttpStatus.UNAUTHORIZED;
case FORBIDDEN:
return HttpStatus.FORBIDDEN;
case NOT_FOUND:
case USER_ACCOUNT_NOT_FOUND:
case USER_PROFILE_NOT_FOUND:
return HttpStatus.NOT_FOUND;
case CONFLICT:
case USER_EMAIL_ALREADY_EXISTS:
return HttpStatus.CONFLICT;
case BAD_REQUEST:
case VALIDATION_ERROR:
case USER_PASSWORD_TOO_SHORT:
return HttpStatus.BAD_REQUEST;
default:
if (resultCode.getCode() >= 2000 && resultCode.getCode() < 3000) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.BAD_REQUEST;
}
}
}

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="co.jp.springp0421.dogdemo.repository.UserRepository">
<select id="existsByEmail" resultType="co.jp.springp0421.dogdemo.entity.UserEntity">
select u.email
from user_entity u
where u.email = #{email}
</select>
<select id="loadUserByUsername" resultType="co.jp.springp0421.dogdemo.entity.UserEntity">
select u.email
from user_entity u
where u.email = #{email}
</select>
</mapper>

View File

@ -0,0 +1,15 @@
package co.jp.springp0421.dogdemo.repository;
import co.jp.springp0421.dogdemo.entity.UserEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.Optional;
@Mapper
public interface UserRepository extends BaseMapper<UserEntity> {
boolean existsByEmail(String Email);
Optional<UserEntity> findByEmail(String Email);
}

View File

@ -0,0 +1,105 @@
package co.jp.springp0421.dogdemo.service;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Service
public class JwtService {
private static final Logger logger = LoggerFactory.getLogger(JwtService.class);
//log
@Value("${jwt.secret}")
private String secretKey;
@Value("${jwt.token-expiration-ms}")
private long tokenExpirationMs;
@org.jetbrains.annotations.NotNull
private Key getSignKey() {
byte[] keyBytes = Base64.getDecoder().decode(secretKey);
return Keys.hmacShaKeyFor(keyBytes);
}
public String extractUsername(String token) {
try {
return extractClaim(token, Claims::getSubject);
} catch (ExpiredJwtException e) {
logger.warn("JWT token is expired when extracting username: {}", e.getMessage());
return e.getClaims().getSubject();
} catch (MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
logger.error("Invalid JWT token when extracting username: {}", e.getMessage());
return null;
}
}
public <T> T extractClaim(String token, @NotNull Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts
.parserBuilder()
.setSigningKey(getSignKey())
.build()
.parseClaimsJws(token)
.getBody();
}
public String generateToken(@NotNull UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, userDetails.getUsername());
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + tokenExpirationMs)) // 使用配置的过期时间
.signWith(getSignKey(), SignatureAlgorithm.HS256)
.compact();
}
public boolean isTokenValid(String token, UserDetails userDetails) {
try {
final String username = extractUsername(token);
if (username == null) {
return false;
}
return (username.equals(userDetails.getUsername()) && !isTokenActuallyExpired(token));
} catch (ExpiredJwtException e) {
logger.warn("Token validation failed: Expired JWT - {}", e.getMessage());
return false;
} catch (MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
logger.error("Token validation failed: Invalid JWT (format, signature, etc.) - {}", e.getMessage());
return false;
}
}
private boolean isTokenActuallyExpired(String token) {
return extractExpiration(token).before(new Date());
}
private Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
}

View File

@ -0,0 +1,75 @@
package co.jp.springp0421.dogdemo.service;
import java.util.Collection;
import java.util.Collections;
import co.jp.springp0421.dogdemo.common.ResultCode;
import co.jp.springp0421.dogdemo.dto.RegistrationDto;
import co.jp.springp0421.dogdemo.entity.UserEntity;
import co.jp.springp0421.dogdemo.exception.BusinessException;
import co.jp.springp0421.dogdemo.repository.UserRepository;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService extends ServiceImpl<UserRepository, UserEntity> implements UserDetailsService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public UserEntity registerNewUser(@NotNull RegistrationDto registrationDto) throws BusinessException {
if (userRepository.existsByEmail(registrationDto.getEmail())) {
throw new BusinessException(ResultCode.USER_EMAIL_ALREADY_EXISTS,"error: Email" + registrationDto.getEmail() + " had been used");
}
UserEntity newUser = new UserEntity();
newUser.setName(registrationDto.getName());
newUser.setEmail(registrationDto.getEmail());
newUser.setPassword(passwordEncoder.encode(registrationDto.getPassword()));
boolean success = this.save(newUser);
if (success) {
return newUser;
} else {
throw new BusinessException(ResultCode.DATABASE_ERROR, "User registration failed");
}
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
UserEntity userEntity = userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException(email + " not found"));
Collection<? extends GrantedAuthority> authorities = Collections
.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
return new User(
userEntity.getEmail(),
userEntity.getPassword(),
true, // enabled
true, // accountNonExpired
true, // credentialsNonExpired
true, // accountNonLocked
authorities // role
);
}
}

View File

@ -0,0 +1,16 @@
spring.application.name=DogDemo
server.address=localhost
server.port=8085
spring.sql.init.platform=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.datasource.url=jdbc:mysql://192.168.1.192:3306/dog
spring.datasource.username=coder
spring.datasource.password=coder
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
jwt.secret=XyRmP4NvTcW9aJoE1LbGz7uKYqF6sHdC
jwt.token-expiration-ms=900000