2024-09-02 18:07:30 +00:00

60 lines
1.8 KiB
Go

package middleware
import (
"net/http"
"github.com/Timothylock/go-signin-with-apple/apple"
"github.com/nose7en/ToyBoomServer/common"
"github.com/nose7en/ToyBoomServer/config"
"github.com/nose7en/ToyBoomServer/defs"
"github.com/nose7en/ToyBoomServer/rpc"
"github.com/spf13/cast"
"github.com/gin-gonic/gin"
)
func ValidateAppleAppToken() func(c *gin.Context) {
return func(c *gin.Context) {
code := c.GetHeader(common.TokenKey)
resp, err := rpc.GetManager().AppleCli().VerifyAppToken(c, code)
if err != nil || len(resp.Error) > 0 {
common.Logger(c).WithError(err).Errorf("failed to verify apple token, response error: %s", resp.Error)
c.AbortWithStatusJSON(http.StatusOK, common.UnAuth("failed to verify apple token"))
return
}
// Get the unique user ID
unique, err := apple.GetUniqueID(resp.IDToken)
if err != nil {
common.Logger(c).WithError(err).Error("failed to get apple unique id")
c.AbortWithStatusJSON(http.StatusOK, common.UnAuth("failed to verify apple token"))
return
}
// Get detail user info
claim, err := apple.GetClaims(resp.IDToken)
if err != nil || claim == nil {
common.Logger(c).WithError(err).Error("failed to get apple user info or claim is nil")
c.AbortWithStatusJSON(http.StatusOK, common.UnAuth("failed to verify apple token"))
return
}
if config.IsDebug() {
common.Logger(c).Debugf("apple auth success, user info: %+v", claim)
}
email := cast.ToString((*claim)["email"])
emailVerified := cast.ToBool((*claim)["email_verified"])
isPrivateEmail := cast.ToBool((*claim)["is_private_email"])
userInfo := &defs.User{
UserID: unique,
Email: email,
IsPrivateEmail: isPrivateEmail,
EmailVerified: emailVerified,
}
common.Logger(c).Infof("apple auth success, user info: %+v", userInfo)
c.Set(common.UserInfoKey, userInfo)
}
}