22301102 | aa5adbc | 2025-05-18 17:51:55 +0800 | [diff] [blame] | 1 | package com.pt.controller; |
| 2 | |
| 3 | import com.pt.constant.Constants; |
| 4 | import com.pt.entity.Admin; |
| 5 | import com.pt.repository.AdminRepository; |
| 6 | import com.pt.service.AdminService; |
| 7 | import com.pt.utils.JWTUtils; |
| 8 | import org.springframework.beans.factory.annotation.Autowired; |
22301102 | f69709e | 2025-06-08 14:10:02 +0800 | [diff] [blame] | 9 | import org.springframework.web.bind.annotation.*; |
22301102 | aa5adbc | 2025-05-18 17:51:55 +0800 | [diff] [blame] | 10 | import org.springframework.http.ResponseEntity; |
| 11 | |
| 12 | import java.util.HashMap; |
| 13 | import java.util.Map; |
| 14 | |
| 15 | @RestController |
| 16 | @RequestMapping("/api/admin") |
| 17 | @CrossOrigin(origins = "*") |
| 18 | public class AdminController { |
| 19 | |
| 20 | @Autowired |
| 21 | private AdminService adminService; |
| 22 | |
| 23 | @PostMapping("/login") |
22301102 | f69709e | 2025-06-08 14:10:02 +0800 | [diff] [blame] | 24 | public ResponseEntity<?> loginAdmin(@RequestBody Map<String, String> request) { |
| 25 | String username = request.get("username"); |
| 26 | String password = request.get("password"); |
| 27 | |
22301102 | aa5adbc | 2025-05-18 17:51:55 +0800 | [diff] [blame] | 28 | Map<String, Object> ans = new HashMap<>(); |
| 29 | Admin admin = adminService.findByUsernameAndPassword(username, password); |
| 30 | if (admin != null) { |
22301102 | f69709e | 2025-06-08 14:10:02 +0800 | [diff] [blame] | 31 | ans.put("message", "Login successful"); |
22301102 | f567030 | 2025-06-08 14:10:02 +0800 | [diff] [blame^] | 32 | ans.put("data", Map.of( |
| 33 | "token", JWTUtils.generateToken(username, Constants.UserRole.ADMIN, Constants.DEFAULT_EXPIRE_TIME), |
| 34 | "uid", admin.getId(), |
| 35 | "username", admin.getUsername() |
| 36 | )); |
22301102 | aa5adbc | 2025-05-18 17:51:55 +0800 | [diff] [blame] | 37 | return ResponseEntity.ok().body(ans); |
| 38 | } else { |
22301102 | f69709e | 2025-06-08 14:10:02 +0800 | [diff] [blame] | 39 | ans.put("message", "Invalid username or password"); |
22301102 | aa5adbc | 2025-05-18 17:51:55 +0800 | [diff] [blame] | 40 | return ResponseEntity.badRequest().body(ans); |
| 41 | } |
| 42 | } |
| 43 | } |