Skip to content

Commit

Permalink
feat: access-token 获取用户信息
Browse files Browse the repository at this point in the history
  • Loading branch information
RockChinQ committed Jul 27, 2024
1 parent 7c0c8e8 commit a7882a9
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 0 deletions.
9 changes: 9 additions & 0 deletions backend/controller/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 28 additions & 0 deletions backend/controller/oauthapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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,
})
}
3 changes: 3 additions & 0 deletions backend/service/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
10 changes: 10 additions & 0 deletions backend/service/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit a7882a9

Please sign in to comment.