wuchimedes | 079c163 | 2025-04-02 22:01:20 +0800 | [diff] [blame] | 1 | package com.example.g8backend.controller; |
| 2 | |
| 3 | import com.example.g8backend.entity.User; |
| 4 | import com.example.g8backend.service.IUserService; |
| 5 | import com.example.g8backend.util.JwtUtil; |
| 6 | import org.springframework.beans.factory.annotation.Autowired; |
| 7 | import org.springframework.http.ResponseEntity; |
| 8 | import org.springframework.security.crypto.password.PasswordEncoder; |
| 9 | import org.springframework.web.bind.annotation.*; |
| 10 | |
| 11 | import java.util.HashMap; |
| 12 | import java.util.Map; |
| 13 | |
| 14 | @RestController |
| 15 | @RequestMapping("/auth") |
| 16 | public class AuthController { |
| 17 | |
| 18 | @Autowired |
| 19 | private IUserService userService; |
| 20 | |
| 21 | @Autowired |
| 22 | private PasswordEncoder passwordEncoder; |
| 23 | |
| 24 | @Autowired |
| 25 | private JwtUtil jwtUtil; |
| 26 | |
| 27 | // 用户注册 |
| 28 | @PostMapping("/register") |
| 29 | public ResponseEntity<?> register(@RequestBody User user) { |
| 30 | if (userService.getUserByName(user.getUserName()) != null) { |
| 31 | return ResponseEntity.badRequest().body("用户名已存在"); |
| 32 | } |
| 33 | userService.registerUser(user); |
| 34 | return ResponseEntity.ok("注册成功"); |
| 35 | } |
| 36 | |
| 37 | // 用户登录 |
| 38 | @PostMapping("/login") |
| 39 | public ResponseEntity<?> login(@RequestBody User user) { |
| 40 | User existingUser = userService.getUserByEmail(user.getEmail()); |
| 41 | if (existingUser == null || !passwordEncoder.matches(user.getPassword(), existingUser.getPassword())) { |
| 42 | return ResponseEntity.badRequest().body("用户名或密码错误"); |
| 43 | } |
| 44 | String token = jwtUtil.generateToken(existingUser.getUserName()); |
| 45 | Map<String, String> response = new HashMap<>(); |
| 46 | response.put("token", token); |
| 47 | return ResponseEntity.ok(response); |
| 48 | } |
| 49 | } |