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; |
wuchimedes | 18addec | 2025-04-03 17:59:02 +0800 | [diff] [blame^] | 7 | import org.springframework.data.redis.core.RedisTemplate; |
wuchimedes | 079c163 | 2025-04-02 22:01:20 +0800 | [diff] [blame] | 8 | import org.springframework.http.ResponseEntity; |
| 9 | import org.springframework.security.crypto.password.PasswordEncoder; |
| 10 | import org.springframework.web.bind.annotation.*; |
| 11 | |
| 12 | import java.util.HashMap; |
| 13 | import java.util.Map; |
| 14 | |
| 15 | @RestController |
| 16 | @RequestMapping("/auth") |
| 17 | public class AuthController { |
| 18 | |
| 19 | @Autowired |
| 20 | private IUserService userService; |
| 21 | |
| 22 | @Autowired |
| 23 | private PasswordEncoder passwordEncoder; |
| 24 | |
| 25 | @Autowired |
| 26 | private JwtUtil jwtUtil; |
| 27 | |
wuchimedes | 18addec | 2025-04-03 17:59:02 +0800 | [diff] [blame^] | 28 | @Autowired |
| 29 | RedisTemplate<String, Object> redisTemplate; |
| 30 | |
wuchimedes | 079c163 | 2025-04-02 22:01:20 +0800 | [diff] [blame] | 31 | // 用户注册 |
| 32 | @PostMapping("/register") |
| 33 | public ResponseEntity<?> register(@RequestBody User user) { |
| 34 | if (userService.getUserByName(user.getUserName()) != null) { |
| 35 | return ResponseEntity.badRequest().body("用户名已存在"); |
| 36 | } |
| 37 | userService.registerUser(user); |
| 38 | return ResponseEntity.ok("注册成功"); |
| 39 | } |
| 40 | |
| 41 | // 用户登录 |
| 42 | @PostMapping("/login") |
| 43 | public ResponseEntity<?> login(@RequestBody User user) { |
| 44 | User existingUser = userService.getUserByEmail(user.getEmail()); |
| 45 | if (existingUser == null || !passwordEncoder.matches(user.getPassword(), existingUser.getPassword())) { |
| 46 | return ResponseEntity.badRequest().body("用户名或密码错误"); |
| 47 | } |
| 48 | String token = jwtUtil.generateToken(existingUser.getUserName()); |
| 49 | Map<String, String> response = new HashMap<>(); |
| 50 | response.put("token", token); |
| 51 | return ResponseEntity.ok(response); |
| 52 | } |
wuchimedes | 18addec | 2025-04-03 17:59:02 +0800 | [diff] [blame^] | 53 | |
| 54 | @GetMapping("/test_redis") |
| 55 | public ResponseEntity<?> testRedis() { |
| 56 | redisTemplate.opsForValue().get("test"); |
| 57 | return ResponseEntity.ok("test redis ok"); |
| 58 | } |
wuchimedes | 079c163 | 2025-04-02 22:01:20 +0800 | [diff] [blame] | 59 | } |