diff --git a/backend/controller/api.go b/backend/controller/api.go index 12fc652..db9001c 100644 --- a/backend/controller/api.go +++ b/backend/controller/api.go @@ -86,6 +86,15 @@ const ( var ErrAccountBanned = errors.New("账户已被封禁") +func (ar *APIRouter) GetBearerToken(c *gin.Context) (string, error) { + bearer := c.GetHeader("Authorization") + if bearer == "" { + return "", errors.New("no bearer token") + } + + return bearer[7:], nil +} + // 鉴权 // 如果是服务鉴权,则拿Authorization头对比service.token // 其他的都是用户鉴权,直接尝试从GetUin取uin diff --git a/backend/controller/oauthapi.go b/backend/controller/oauthapi.go index 5f10673..ee99a55 100644 --- a/backend/controller/oauthapi.go +++ b/backend/controller/oauthapi.go @@ -21,6 +21,7 @@ func NewOAuth2Router(rg *gin.RouterGroup, oas service.OAuth2Service) *OAuth2Rout group.GET("/get-app-info", oar.GetOAuth2AppInfo) group.GET("/authorize", oar.Authorize) group.POST("/get-access-token", oar.GetAccessToken) + group.GET("/get-user-info", oar.GetUserInfo) return oar } @@ -108,3 +109,30 @@ func (oar *OAuth2Router) GetAccessToken(c *gin.Context) { "access_token": ak, }) } + +func (oar *OAuth2Router) GetUserInfo(c *gin.Context) { + ak, err := oar.GetBearerToken(c) + + if err != nil { + oar.StatusCode(c, 401, err.Error()) + return + } + + account, err := oar.OAuth2Service.GetUserInfo(ak) + + if err != nil { + if err == service.ErrInvalidOAuth2AccessToken { + oar.StatusCode(c, 401, err.Error()) + return + } else { + oar.Fail(c, 1, err.Error()) + return + } + } + + oar.Success(c, gin.H{ + "uin": account.Uin, + "user_group": account.UserGroup, + "created_at": account.CreatedAt, + }) +} diff --git a/backend/service/errors.go b/backend/service/errors.go index 5232843..0b4a163 100644 --- a/backend/service/errors.go +++ b/backend/service/errors.go @@ -19,3 +19,6 @@ var ErrOAuth2AppAlreadyExist = errors.New("OAuth2应用名称已存在") // OAuth2认证 Secret 不匹配 var ErrOAuth2SecretNotMatch = errors.New("OAuth2 认证 Secret 不匹配") + +// 无效的 OAuth2 Access Token +var ErrInvalidOAuth2AccessToken = errors.New("无效的 OAuth2 Access Token") diff --git a/backend/service/oauth.go b/backend/service/oauth.go index e494aa5..481a89a 100644 --- a/backend/service/oauth.go +++ b/backend/service/oauth.go @@ -65,3 +65,13 @@ func (oas *OAuth2Service) GetAccessToken(clientID, clientSecret, code string) (s return accessToken, err } + +func (oas *OAuth2Service) GetUserInfo(accessToken string) (*database.AccountPO, error) { + uin, _, err := util.ParseOAuth2AccessTokenJWTToken(accessToken) + + if err != nil { + return &database.AccountPO{}, ErrInvalidOAuth2AccessToken + } + + return oas.DB.GetAccountByUIN(uin) +}