| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- package controllers
- import (
- "ems-backend/models"
- "ems-backend/utils"
- "net/http"
- "github.com/gin-gonic/gin"
- )
- type LoginRequest struct {
- Username string `json:"username" binding:"required"`
- Password string `json:"password" binding:"required"`
- }
- type LoginResponse struct {
- Token string `json:"token"`
- User models.User `json:"user"`
- }
- func Login(c *gin.Context) {
- var req LoginRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
- return
- }
- // 1. Database User Check
- var user models.User
- // 使用 MD5 或其他加密方式比较密码(这里为了演示先用明文,实际项目请使用 bcrypt)
- if err := models.DB.Where("username = ? AND password = ?", req.Username, req.Password).First(&user).Error; err != nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
- return
- }
- token, err := utils.GenerateToken(user)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
- return
- }
- // Avoid returning sensitive data
- user.Password = ""
- c.JSON(http.StatusOK, LoginResponse{
- Token: token,
- User: user,
- })
- }
- func GetProfile(c *gin.Context) {
- userId, exists := c.Get("userId")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
- return
- }
- var user models.User
- if err := models.DB.Where("id = ?", userId).First(&user).Error; err != nil {
- c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
- return
- }
- user.Password = ""
- c.JSON(http.StatusOK, gin.H{"user": user})
- }
- type UpdatePwdRequest struct {
- OldPassword string `json:"oldPassword" binding:"required"`
- NewPassword string `json:"newPassword" binding:"required"`
- }
- func UpdateProfilePwd(c *gin.Context) {
- userId, exists := c.Get("userId")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
- return
- }
- var req UpdatePwdRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
- return
- }
- var user models.User
- if err := models.DB.Where("id = ?", userId).First(&user).Error; err != nil {
- c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
- return
- }
- // Verify old password (plaintext for now)
- if user.Password != req.OldPassword {
- c.JSON(http.StatusBadRequest, gin.H{"error": "旧密码错误"})
- return
- }
- user.Password = req.NewPassword
- if err := models.DB.Save(&user).Error; err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update password"})
- return
- }
- c.JSON(http.StatusOK, gin.H{"message": "Password updated successfully"})
- }
|