78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
package controller
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"nl-pms-api/internal/commonservice"
|
|
"nl-pms-api/internal/middleware"
|
|
"nl-pms-api/internal/service"
|
|
)
|
|
|
|
// AuthController 认证相关 HTTP 绑定。
|
|
type AuthController struct {
|
|
Svc *service.AuthService
|
|
}
|
|
|
|
func (h *AuthController) Register(c *gin.Context) {
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
if !bindJSON(c, &req) {
|
|
return
|
|
}
|
|
if err := h.Svc.Register(req.Username, req.Password); err != nil {
|
|
writeErr(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
|
}
|
|
|
|
func (h *AuthController) Login(c *gin.Context) {
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
if !bindJSON(c, &req) {
|
|
return
|
|
}
|
|
out, err := h.Svc.Login(req.Username, req.Password, middleware.ClientIP(c))
|
|
if err != nil {
|
|
writeErr(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, out)
|
|
}
|
|
|
|
func (h *AuthController) Refresh(c *gin.Context) {
|
|
var req struct {
|
|
RefreshToken string `json:"refreshToken"`
|
|
}
|
|
if !bindJSON(c, &req) {
|
|
return
|
|
}
|
|
out, err := h.Svc.Refresh(req.RefreshToken, middleware.ClientIP(c))
|
|
if err != nil {
|
|
writeErr(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, out)
|
|
}
|
|
|
|
func (h *AuthController) ChangePassword(c *gin.Context) {
|
|
var req struct {
|
|
OldPassword string `json:"oldPassword"`
|
|
NewPassword string `json:"newPassword"`
|
|
}
|
|
if !bindJSON(c, &req) {
|
|
return
|
|
}
|
|
if err := h.Svc.ChangePassword(commonservice.UserID(c), req.OldPassword, req.NewPassword); err != nil {
|
|
writeErr(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
|
}
|