Files

80 lines
2.2 KiB
Go

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"`
EncryptedPassword string `json:"encrypted_password"`
PasswordKeyID string `json:"password_key_id"`
}
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,
EncryptedPassword: body.EncryptedPassword,
PasswordKeyID: body.PasswordKeyID,
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 passwordPublicKeyHandler(svc *app.AuthService) gin.HandlerFunc {
return func(c *gin.Context) {
key := svc.PasswordPublicKey()
if key == nil {
response.Error(c, response.ErrNotFound(40420, "password_cipher_disabled", "password cipher is disabled"))
return
}
response.Success(c, key)
}
}
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)
}
}