Files
geo/server/internal/ops/transport/auth_handler.go
T

65 lines
1.6 KiB
Go
Raw Normal View History

package transport
import (
"github.com/gin-gonic/gin"
"github.com/geo-platform/tenant-api/internal/ops/app"
"github.com/geo-platform/tenant-api/internal/shared/middleware"
"github.com/geo-platform/tenant-api/internal/shared/response"
)
type loginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
type loginResponse struct {
AccessToken string `json:"access_token"`
ExpiresAt int64 `json:"expires_at"`
Operator app.OperatorView `json:"operator"`
}
func loginHandler(svc *app.AuthService) gin.HandlerFunc {
return func(c *gin.Context) {
var body loginRequest
if err := c.ShouldBindJSON(&body); err != nil {
response.Error(c, response.ErrBadRequest(40000, "invalid_payload", err.Error()))
return
}
result, err := svc.Login(c.Request.Context(), app.LoginInput{
Username: body.Username,
Password: body.Password,
IP: c.ClientIP(),
UserAgent: c.Request.UserAgent(),
RequestID: middleware.RequestIDFromGin(c),
})
if err != nil {
response.Error(c, err)
return
}
response.Success(c, loginResponse{
AccessToken: result.AccessToken,
ExpiresAt: result.ExpiresAt,
Operator: result.Operator,
})
}
}
func meHandler(accounts *app.AccountService) gin.HandlerFunc {
return func(c *gin.Context) {
actor := actorFromGin(c)
if actor == nil {
response.Error(c, response.ErrUnauthorized(40101, "missing_actor", "未登录"))
return
}
detail, err := accounts.Get(c.Request.Context(), actor.OperatorID)
if err != nil {
response.Error(c, err)
return
}
response.Success(c, detail)
}
}