Files
cms-server/service/auth/token.go
Noa Virellia 14f50ecdb2 refactor: update exception constants to follow new naming convention
- Update old ErrorStatus, ErrorType, and Service/Endpoint constants to new naming convention
- Fix incorrect TypeSpecific usage in JWT middleware
- Add missing event specific error definitions to specific.yaml
- Regenerate exception constants

Co-authored-by: Gemini <gemini@google.com>
2026-01-21 14:34:09 +08:00

85 lines
2.1 KiB
Go

package auth
import (
"nixcn-cms/data"
"nixcn-cms/internal/exception"
"nixcn-cms/pkgs/authcode"
"nixcn-cms/pkgs/authtoken"
"nixcn-cms/utils"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
type TokenRequest struct {
Code string `json:"code"`
}
func Token(c *gin.Context) {
var req TokenRequest
err := c.ShouldBindJSON(&req)
if err != nil {
errorCode := new(exception.Builder).
SetStatus(exception.StatusClient).
SetService(exception.ServiceAuth).
SetEndpoint(exception.EndpointAuthServiceToken).
SetType(exception.TypeCommon).
SetOriginal(exception.CommonErrorInvalidInput).
Build()
utils.HttpResponse(c, 400, errorCode)
return
}
authCode, ok := authcode.VerifyAuthCode(req.Code)
if !ok {
errorCode := new(exception.Builder).
SetStatus(exception.StatusClient).
SetService(exception.ServiceAuth).
SetEndpoint(exception.EndpointAuthServiceToken).
SetType(exception.TypeSpecific).
SetOriginal(exception.AuthTokenInvalidToken).
Build()
utils.HttpResponse(c, 403, errorCode)
return
}
userData := new(data.User)
user, err := userData.GetByEmail(authCode.Email)
if err != nil {
errorCode := new(exception.Builder).
SetStatus(exception.StatusServer).
SetService(exception.ServiceAuth).
SetEndpoint(exception.EndpointAuthServiceToken).
SetType(exception.TypeCommon).
SetOriginal(exception.CommonErrorInternal).
Build()
utils.HttpResponse(c, 500, errorCode)
return
}
// Generate jwt
JwtTool := authtoken.Token{
Application: viper.GetString("server.application"),
}
accessToken, refreshToken, err := JwtTool.IssueTokens(authCode.ClientId, user.UserId)
if err != nil {
errorCode := new(exception.Builder).
SetStatus(exception.StatusServer).
SetService(exception.ServiceAuth).
SetEndpoint(exception.EndpointAuthServiceToken).
SetType(exception.TypeSpecific).
SetOriginal(exception.AuthTokenGenFailed).
Build()
utils.HttpResponse(c, 500, errorCode)
return
}
tokenResp := struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}{accessToken, refreshToken}
utils.HttpResponse(c, 200, "", "success", tokenResp)
}