Files
cms-server/service/auth/exchange.go
2026-01-21 13:48:37 +08:00

113 lines
2.9 KiB
Go

package auth
import (
"fmt"
"net/url"
"nixcn-cms/data"
"nixcn-cms/internal/exception"
"nixcn-cms/pkgs/authcode"
"nixcn-cms/utils"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
const ()
func Exchange(c *gin.Context) {
var exchangeReq struct {
ClientId string `json:"client_id"`
RedirectUri string `json:"redirect_uri"`
State string `json:"state"`
}
err := c.ShouldBindJSON(&exchangeReq)
if err != nil {
fmt.Println(err)
errorCode := new(exception.Builder).
SetStatus(exception.ErrorStatusClient).
SetService(exception.AuthService).
SetEndpoint(exception.AuthExchangeEndpoint).
SetType(exception.ErrorTypeCommon).
SetOriginal(exception.CommonErrorInvalidInput).
Build()
utils.HttpResponse(c, 400, errorCode)
return
}
userIdOrig, ok := c.Get("user_id")
if !ok {
errorCode := new(exception.Builder).
SetStatus(exception.ErrorStatusClient).
SetService(exception.AuthService).
SetEndpoint(exception.AuthExchangeEndpoint).
SetType(exception.ErrorTypeCommon).
SetOriginal(exception.CommonErrorUnauthorized).
Build()
utils.HttpResponse(c, 401, errorCode)
return
}
userId, err := uuid.Parse(userIdOrig.(string))
if err != nil {
errorCode := new(exception.Builder).
SetStatus(exception.ErrorStatusServer).
SetService(exception.AuthService).
SetEndpoint(exception.AuthExchangeEndpoint).
SetType(exception.ErrorTypeCommon).
SetOriginal(exception.CommonErrorUuidParseFailed).
Build()
utils.HttpResponse(c, 500, errorCode)
return
}
userData := new(data.User)
user, err := userData.GetByUserId(userId)
if err != nil {
errorCode := new(exception.Builder).
SetStatus(exception.ErrorStatusServer).
SetService(exception.AuthService).
SetEndpoint(exception.AuthExchangeEndpoint).
SetType(exception.ErrorTypeSpecific).
SetOriginal(exception.AuthExchangeGetUserIdFailed).
Build()
utils.HttpResponse(c, 500, errorCode)
return
}
code, err := authcode.NewAuthCode(exchangeReq.ClientId, user.Email)
if err != nil {
errorCode := new(exception.Builder).
SetStatus(exception.ErrorStatusServer).
SetService(exception.AuthService).
SetEndpoint(exception.AuthExchangeEndpoint).
SetType(exception.ErrorTypeSpecific).
SetOriginal(exception.AuthExchangeCodeGenFailed).
Build()
utils.HttpResponse(c, 500, errorCode)
return
}
url, err := url.Parse(exchangeReq.RedirectUri)
if err != nil {
errorCode := new(exception.Builder).
SetStatus(exception.ErrorStatusClient).
SetService(exception.AuthService).
SetEndpoint(exception.AuthExchangeEndpoint).
SetType(exception.ErrorTypeSpecific).
SetOriginal(exception.AuthExchangeInvalidRedirectUri).
Build()
utils.HttpResponse(c, 400, errorCode)
return
}
query := url.Query()
query.Set("code", code)
url.RawQuery = query.Encode()
exchangeResp := struct {
RedirectUri string `json:"redirect_uri"`
}{url.String()}
utils.HttpResponse(c, 200, "", "success", exchangeResp)
}