| package com.pt.controller; |
| |
| import com.pt.constant.Constants; |
| import com.pt.entity.Admin; |
| import com.pt.repository.AdminRepository; |
| import com.pt.service.AdminService; |
| import com.pt.utils.JWTUtils; |
| import org.springframework.beans.factory.annotation.Autowired; |
| import org.springframework.web.bind.annotation.*; |
| import org.springframework.http.ResponseEntity; |
| |
| import java.util.HashMap; |
| import java.util.Map; |
| |
| @RestController |
| @RequestMapping("/api/admin") |
| @CrossOrigin(origins = "*") |
| public class AdminController { |
| |
| @Autowired |
| private AdminService adminService; |
| |
| @PostMapping("/login") |
| public ResponseEntity<?> loginAdmin(@RequestBody Map<String, String> request) { |
| String username = request.get("username"); |
| String password = request.get("password"); |
| |
| Map<String, Object> ans = new HashMap<>(); |
| Admin admin = adminService.findByUsernameAndPassword(username, password); |
| if (admin != null) { |
| ans.put("message", "Login successful"); |
| ans.put("data", Map.of( |
| "token", JWTUtils.generateToken(username, Constants.UserRole.ADMIN, Constants.DEFAULT_EXPIRE_TIME), |
| "uid", admin.getId(), |
| "username", admin.getUsername() |
| )); |
| return ResponseEntity.ok().body(ans); |
| } else { |
| ans.put("message", "Invalid username or password"); |
| return ResponseEntity.badRequest().body(ans); |
| } |
| } |
| } |