Skip to content

Commit a4dd8fc

Browse files
author
Nils Hillmann
committed
Implemented BearerTokenErrorCode handling
1 parent 64e7aa6 commit a4dd8fc

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

routers/user/oauth.go

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,24 @@ func (err AccessTokenError) Error() string {
9494
return fmt.Sprintf("%s: %s", err.ErrorCode, err.ErrorDescription)
9595
}
9696

97+
// BearerTokenErrorCode represents an error code specified in RFC 6750
98+
type BearerTokenErrorCode string
99+
100+
const (
101+
// BearerTokenErrorCodeInvalidRequest represents an error code specified in RFC 6750
102+
BearerTokenErrorCodeInvalidRequest BearerTokenErrorCode = "invalid_request"
103+
// BearerTokenErrorCodeInvalidToken represents an error code specified in RFC 6750
104+
BearerTokenErrorCodeInvalidToken BearerTokenErrorCode = "invalid_token"
105+
// BearerTokenErrorCodeInsufficientScope represents an error code specified in RFC 6750
106+
BearerTokenErrorCodeInsufficientScope BearerTokenErrorCode = "insufficient_scope"
107+
)
108+
109+
// BearerTokenError represents an error response specified in RFC 6750
110+
type BearerTokenError struct {
111+
ErrorCode BearerTokenErrorCode
112+
ErrorDescription string
113+
}
114+
97115
// TokenType specifies the kind of token
98116
type TokenType string
99117

@@ -211,6 +229,13 @@ func InfoOAuth(ctx *context.Context) {
211229
return
212230
}
213231
uid := sso.CheckOAuthAccessToken(auths[1])
232+
if uid == 0 {
233+
handleBearerTokenError(ctx, BearerTokenError{
234+
ErrorCode: BearerTokenErrorCodeInvalidToken,
235+
ErrorDescription: "Access token not assigned to any user",
236+
})
237+
return
238+
}
214239
if uid != 0 {
215240
authUser, err := models.GetUserByID(uid)
216241
if err != nil {
@@ -225,8 +250,6 @@ func InfoOAuth(ctx *context.Context) {
225250
Picture: authUser.AvatarLink(),
226251
}
227252
ctx.JSON(http.StatusOK, response)
228-
} else {
229-
ctx.ServerError("InfoOAuth:", fmt.Errorf("UserID not valid"))
230253
}
231254
}
232255

@@ -608,3 +631,16 @@ func handleAuthorizeError(ctx *context.Context, authErr AuthorizeError, redirect
608631
redirect.RawQuery = q.Encode()
609632
ctx.Redirect(redirect.String(), 302)
610633
}
634+
635+
func handleBearerTokenError(ctx *context.Context, beErr BearerTokenError) {
636+
ctx.Resp.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"\", error=\"%s\", error_description=\"%s\"", beErr.ErrorCode, beErr.ErrorDescription))
637+
if beErr.ErrorCode == BearerTokenErrorCodeInvalidRequest {
638+
ctx.Error(http.StatusBadRequest)
639+
}
640+
if beErr.ErrorCode == BearerTokenErrorCodeInvalidToken {
641+
ctx.Error(http.StatusUnauthorized)
642+
}
643+
if beErr.ErrorCode == BearerTokenErrorCodeInsufficientScope {
644+
ctx.Error(http.StatusForbidden)
645+
}
646+
}

0 commit comments

Comments
 (0)