]> source.dussan.org Git - gitea.git/commitdiff
use existing oauth grant for public client (#31015) (#31042)
authorGiteabot <teabot@gitea.io>
Tue, 21 May 2024 17:32:31 +0000 (01:32 +0800)
committerGitHub <noreply@github.com>
Tue, 21 May 2024 17:32:31 +0000 (17:32 +0000)
Backport #31015 by @denyskon

Do not try to create a new authorization grant when one exists already,
thus preventing a DB-related authorization issue.

Fix https://github.com/go-gitea/gitea/pull/30790#issuecomment-2118812426

Co-authored-by: Denys Konovalov <kontakt@denyskon.de>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
routers/web/auth/oauth.go

index 84fa4730441f19716fcce8a75da10435ad34ffd4..b337b6b15695985567d87e3c02205bea987757ef 100644 (file)
@@ -556,15 +556,30 @@ func GrantApplicationOAuth(ctx *context.Context) {
                ctx.ServerError("GetOAuth2ApplicationByClientID", err)
                return
        }
-       grant, err := app.CreateGrant(ctx, ctx.Doer.ID, form.Scope)
+       grant, err := app.GetGrantByUserID(ctx, ctx.Doer.ID)
        if err != nil {
+               handleServerError(ctx, form.State, form.RedirectURI)
+               return
+       }
+       if grant == nil {
+               grant, err = app.CreateGrant(ctx, ctx.Doer.ID, form.Scope)
+               if err != nil {
+                       handleAuthorizeError(ctx, AuthorizeError{
+                               State:            form.State,
+                               ErrorDescription: "cannot create grant for user",
+                               ErrorCode:        ErrorCodeServerError,
+                       }, form.RedirectURI)
+                       return
+               }
+       } else if grant.Scope != form.Scope {
                handleAuthorizeError(ctx, AuthorizeError{
                        State:            form.State,
-                       ErrorDescription: "cannot create grant for user",
+                       ErrorDescription: "a grant exists with different scope",
                        ErrorCode:        ErrorCodeServerError,
                }, form.RedirectURI)
                return
        }
+
        if len(form.Nonce) > 0 {
                err := grant.SetNonce(ctx, form.Nonce)
                if err != nil {