jojo/routers/common/auth.go
forgejo-backport-action 0aa1b45956 [v15.0/forgejo] refactor: change authentication to return structured data (#12462)
**Backport:** https://codeberg.org/forgejo/forgejo/pulls/12202

Currently authentication methods return information in two forms: they return who was authenticated as a `*user_model.User`, and then they insert key-values into `ctx.Data` which has critical impact on how the authenticated request is treated.  This PR changes the authentication methods to return structured data in the form of an `AuthenticationResult`, with all the key-value information in `ctx.Data` being moved into methods on the `AuthenticationResult` interface.

Authentication workflows in Forgejo are a real mess.  This is the first step in trying to clean it up and make the code predictable and reasonable, and is both follow-up work that was identified from the repo-specific access tokens (where the `"ApiTokenReducer"` key-value was added), and is pre-requisite work to future JWT enhancements that are [being discussed](https://codeberg.org/forgejo/forgejo/issues/3571#issuecomment-13268004).

Co-authored-by: Mathieu Fenniak <mathieu@fenniak.net>
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/12462
Reviewed-by: Gusted <gusted@noreply.codeberg.org>
2026-05-08 04:07:32 +02:00

44 lines
1.1 KiB
Go

// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package common
import (
"errors"
"forgejo.org/modules/web/middleware"
auth_service "forgejo.org/services/auth"
"forgejo.org/services/context"
)
func AuthShared(ctx *context.Base, sessionStore auth_service.SessionStore, authMethod auth_service.Method) (ar auth_service.AuthenticationResult, err error) {
ar, err = authMethod.Verify(ctx.Req, ctx.Resp, sessionStore)
if err != nil {
return ar, err
}
if ar == nil {
return nil, errors.New("failure to retrieve AuthenticationResult - nil value")
}
doer := ar.User()
if doer != nil {
if ctx.Locale.Language() != doer.Language {
ctx.Locale = middleware.Locale(ctx.Resp, ctx.Req)
}
ctx.Data["IsSigned"] = true
ctx.Data[middleware.ContextDataKeySignedUser] = doer
ctx.Data["SignedUserID"] = doer.ID
ctx.Data["IsAdmin"] = doer.IsAdmin
} else {
ctx.Data["IsSigned"] = false
ctx.Data["SignedUserID"] = int64(0)
}
return ar, nil
}
// VerifyOptions contains required or check options
type VerifyOptions struct {
SignInRequired bool
SignOutRequired bool
AdminRequired bool
DisableCSRF bool
}