diff --git a/demo/src/main/java/com/example/demo/DemoApplication.java b/demo/src/main/java/com/example/demo/DemoApplication.java index 094d95b..1c07f80 100644 --- a/demo/src/main/java/com/example/demo/DemoApplication.java +++ b/demo/src/main/java/com/example/demo/DemoApplication.java @@ -1,13 +1,30 @@ package com.example.demo; +import jakarta.annotation.PostConstruct; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.beans.factory.annotation.Autowired; @SpringBootApplication public class DemoApplication { + @Autowired + private JdbcTemplate jdbcTemplate; + public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } -} + @PostConstruct + public void testConnection() { + try { + System.out.println("Testing database connection..."); + this.jdbcTemplate.queryForObject("SELECT 1", Integer.class); + System.out.println("Database connection successful."); + } catch (Exception e) { + System.err.println("Failed to connect to the database: " + e.getMessage()); + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/demo/src/main/java/com/example/demo/User.java b/demo/src/main/java/com/example/demo/User.java index 5d55b56..e785dbf 100644 --- a/demo/src/main/java/com/example/demo/User.java +++ b/demo/src/main/java/com/example/demo/User.java @@ -14,38 +14,45 @@ public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + private Long id; // 用户ID @Enumerated(EnumType.STRING) - private AccountType accountType; + private AccountType accountType; // 账户类型 + + private String nickname; // 昵称 + + private String signature; // 签名或个人简介 - private String nickname; - private String signature; @Column(name = "login_account", unique = true, nullable = false) - private String loginAccount; - private String password; - private LocalDateTime birthday; // 更改为 LocalDateTime 以便统一时间类型 - private LocalDateTime createdAt; - private LocalDateTime updatedAt; - private Boolean loginStatus; + private String loginAccount; // 登录账号(通常是用户名或邮箱) + + private String password; // 加密后的密码 + + private LocalDateTime birthday; // 生日 + + private LocalDateTime createdAt; // 创建时间 + + private LocalDateTime updatedAt; // 更新时间 + + private Boolean loginStatus; // 登录状态 @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true) @JoinColumn(name = "user_id") - private Set securityQuestions = new HashSet<>(); + private Set securityQuestions = new HashSet<>(); // 安全问题集合 @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "user_authorities", joinColumns = @JoinColumn(name = "user_id")) @Column(name = "authority") - private Set authorityStrings; // 使用 Set 来避免重复权限 + private Set authorityStrings; // 权限字符串集合 public enum AccountType { - USER, ADMIN // 英文枚举值更符合国际化标准 + USER, ADMIN // 账户类型枚举值 } - // Default constructor + // 默认构造函数 public User() {} - // Parameterized constructor for convenience + // 参数化构造函数 public User(AccountType accountType, String nickname, String signature, String loginAccount, String password, LocalDateTime birthday, LocalDateTime createdAt, LocalDateTime updatedAt, Boolean loginStatus, Set authorityStrings) { this.accountType = accountType; @@ -60,7 +67,7 @@ public class User implements UserDetails { this.authorityStrings = authorityStrings != null ? authorityStrings : Collections.emptySet(); } - // Getters and Setters + // Getters 和 Setters 方法 /** * 获取用户的唯一标识符。 @@ -218,7 +225,8 @@ public class User implements UserDetails { this.authorityStrings = authorityStrings; } - // Implementing methods of UserDetails interface + // 实现 UserDetails 接口的方法 + @Override public Collection getAuthorities() { return this.getAuthorityStrings().stream() @@ -265,7 +273,7 @@ public class User implements UserDetails { this.securityQuestions = securityQuestions; } - // Equals and HashCode methods for better entity comparison + // 重写 equals 和 hashCode 方法以更好地进行实体比较 @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/demo/src/main/java/com/example/demo/config/SecurityConfig.java b/demo/src/main/java/com/example/demo/config/SecurityConfig.java index c6d7498..c316686 100644 --- a/demo/src/main/java/com/example/demo/config/SecurityConfig.java +++ b/demo/src/main/java/com/example/demo/config/SecurityConfig.java @@ -77,4 +77,5 @@ public class SecurityConfig { public AuthenticationManager authenticationManager(AuthenticationProvider authenticationProvider) { return new ProviderManager(List.of(authenticationProvider)); } + } diff --git a/demo/src/main/java/com/example/demo/controller/UserController.java b/demo/src/main/java/com/example/demo/controller/UserController.java index d315bd6..146be6c 100644 --- a/demo/src/main/java/com/example/demo/controller/UserController.java +++ b/demo/src/main/java/com/example/demo/controller/UserController.java @@ -14,6 +14,9 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; +import java.util.Arrays; +import java.util.Map; + @RestController @CrossOrigin(origins = "http://localhost:5137/") // 允许来自前端开发服务器的请求 @@ -48,6 +51,11 @@ public class UserController { } } + // 设置默认 accountType 如果未指定或无效 + if (user.getAccountType() == null || !Arrays.asList(User.AccountType.USER, User.AccountType.ADMIN).contains(user.getAccountType())) { + user.setAccountType(User.AccountType.USER); + } + User registeredUser = userService.registerUser(user); return new ResponseEntity<>(registeredUser, HttpStatus.CREATED); } catch (IllegalArgumentException e) { diff --git a/demo/src/main/java/com/example/demo/repository/UserRepository.java b/demo/src/main/java/com/example/demo/repository/UserRepository.java index 3887ed6..cb2a40f 100644 --- a/demo/src/main/java/com/example/demo/repository/UserRepository.java +++ b/demo/src/main/java/com/example/demo/repository/UserRepository.java @@ -9,4 +9,6 @@ import java.util.Optional; @Repository public interface UserRepository extends JpaRepository { Optional findByLoginAccount(String loginAccount); + + } \ No newline at end of file diff --git a/demo/src/main/java/com/example/demo/service/UserService.java b/demo/src/main/java/com/example/demo/service/UserService.java index 6787468..eb76faa 100644 --- a/demo/src/main/java/com/example/demo/service/UserService.java +++ b/demo/src/main/java/com/example/demo/service/UserService.java @@ -8,8 +8,10 @@ import com.example.demo.repository.UserSecurityQuestionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.LocalDateTime; +import java.util.Arrays; import java.util.Collections; import java.util.Optional; import java.util.Set; @@ -22,6 +24,9 @@ public class UserService { private final UserSecurityQuestionRepository userSecurityQuestionRepository; private final PasswordEncoder passwordEncoder; + + private static final Logger logger = LoggerFactory.getLogger(UserService.class); + @Autowired public UserService(UserRepository userRepository, ArticleRepository articleRepository, @@ -31,6 +36,7 @@ public class UserService { this.articleRepository = articleRepository; this.userSecurityQuestionRepository = userSecurityQuestionRepository; this.passwordEncoder = passwordEncoder; + logger.info("UserService dependencies injected successfully."); } /** @@ -49,6 +55,11 @@ public class UserService { throw new IllegalArgumentException("Password cannot be null or empty."); } + // 设置默认 accountType 如果未指定或无效 + if (user.getAccountType() == null || !Arrays.asList(User.AccountType.USER, User.AccountType.ADMIN).contains(user.getAccountType())) { + user.setAccountType(User.AccountType.USER); + } + // 初始化 authorityStrings 和 securityQuestions 集合为空集合 if (user.getAuthorityStrings() == null) { user.setAuthorityStrings(Collections.emptySet()); @@ -68,6 +79,17 @@ public class UserService { return userRepository.save(user); } + /** + * 用户登录验证。 + * + * @param loginAccount 用户登录账号 + * @param password 用户密码 + * @return 包含用户的 Optional 对象,如果找不到或密码不匹配则为空 + */ + public Optional loginUser(String loginAccount, String password) { + return userRepository.findByLoginAccount(loginAccount) + .filter(user -> passwordEncoder.matches(password, user.getPassword())); + } /** * 根据登录账号查找用户。 @@ -136,9 +158,9 @@ public class UserService { /** * 已登录用户请求重置密码。 * - * @param loginAccount 用户登录账号 + * @param loginAccount 用户登录账号 * @param currentPassword 用户当前密码 - * @param newPassword 用户的新密码 + * @param newPassword 用户的新密码 */ public void resetPasswordForLoggedInUser(String loginAccount, String currentPassword, String newPassword) { userRepository.findByLoginAccount(loginAccount).ifPresentOrElse( @@ -167,7 +189,7 @@ public class UserService { /** * 添加安全问题到用户账户。 * - * @param loginAccount 用户登录账号 + * @param loginAccount 用户登录账号 * @param securityQuestions 安全问题集合 */ public void addSecurityQuestions(String loginAccount, Set securityQuestions) { @@ -192,7 +214,7 @@ public class UserService { /** * 更新用户的安全问题。 * - * @param loginAccount 用户登录账号 + * @param loginAccount 用户登录账号 * @param securityQuestions 新的安全问题集合 */ public void updateSecurityQuestions(String loginAccount, Set securityQuestions) { diff --git a/demo/src/main/resources/data.sql b/demo/src/main/resources/data.sql index 14afa1b..ecd7713 100644 --- a/demo/src/main/resources/data.sql +++ b/demo/src/main/resources/data.sql @@ -1,10 +1,10 @@ -- 插入测试用户 INSERT INTO Users (account_type, nickname, signature, login_account, password, birthday, created_at, updated_at, login_status) -VALUES ('USER', 'testuser', 'Just a test user', 'user@example.com', '123456', '1990-01-01 00:00:00', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, TRUE); +VALUES ('USER', 'testuser', 'Just a test user', 'user@example.com', '123456', '1990-01-01 00:00:00', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 1); -- 插入测试管理员 INSERT INTO Users (account_type, nickname, signature, login_account, password, birthday, created_at, updated_at, login_status) -VALUES ('ADMIN', 'admin', 'Administrator account', 'admin@example.com', '123456', '1985-05-05 00:00:00', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, TRUE); +VALUES ('ADMIN', 'admin', 'Administrator account', 'admin@example.com', '123456', '1985-05-05 00:00:00', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 1); -- 插入权限信息 INSERT INTO user_authorities (user_id, authority) VALUES (1, 'ROLE_USER');