50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type adminAuthSvc interface {
|
|
Login(ctx context.Context, username, password string) (string, error)
|
|
}
|
|
|
|
type AuthHandler struct {
|
|
authSvc adminAuthSvc
|
|
}
|
|
|
|
func NewAuthHandler(authSvc adminAuthSvc) *AuthHandler {
|
|
return &AuthHandler{authSvc: authSvc}
|
|
}
|
|
|
|
type loginRequest struct {
|
|
Username string `json:"username" binding:"required"`
|
|
Password string `json:"password" binding:"required"`
|
|
}
|
|
|
|
func (h *AuthHandler) Login(c *gin.Context) {
|
|
var req loginRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"code": "400", "message": "参数错误"})
|
|
return
|
|
}
|
|
|
|
token, err := h.authSvc.Login(c.Request.Context(), req.Username, req.Password)
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"code": "UNAUTHORIZED", "message": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"code": "0",
|
|
"message": "ok",
|
|
"data": gin.H{"token": token},
|
|
})
|
|
}
|
|
|
|
func (h *AuthHandler) Logout(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"code": "0", "message": "ok"})
|
|
}
|