1
1
mirror of https://github.com/go-gitea/gitea synced 2025-07-22 18:28:37 +00:00

Move login related structs and functions to models/login (#17093)

* Move login related structs and functions to models/login

* Fix test

* Fix lint

* Fix lint

* Fix lint of windows

* Fix lint

* Fix test

* Fix test

* Only load necessary fixtures when preparing unit tests envs

* Fix lint

* Fix test

* Fix test

* Fix error log

* Fix error log

* Fix error log

* remove unnecessary change

* fix error log

* merge main branch
This commit is contained in:
Lunny Xiao
2021-09-24 19:32:56 +08:00
committed by GitHub
parent 4a2655098f
commit 5842a55b31
142 changed files with 1050 additions and 907 deletions

View File

@@ -14,6 +14,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/login"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/eventsource"
@@ -147,7 +148,7 @@ func SignIn(ctx *context.Context) {
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
ctx.Data["PageIsSignIn"] = true
ctx.Data["PageIsLogin"] = true
ctx.Data["EnableSSPI"] = models.IsSSPIEnabled()
ctx.Data["EnableSSPI"] = login.IsSSPIEnabled()
ctx.HTML(http.StatusOK, tplSignIn)
}
@@ -167,7 +168,7 @@ func SignInPost(ctx *context.Context) {
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
ctx.Data["PageIsSignIn"] = true
ctx.Data["PageIsLogin"] = true
ctx.Data["EnableSSPI"] = models.IsSSPIEnabled()
ctx.Data["EnableSSPI"] = login.IsSSPIEnabled()
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplSignIn)
@@ -573,7 +574,7 @@ func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyR
func SignInOAuth(ctx *context.Context) {
provider := ctx.Params(":provider")
loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
loginSource, err := login.GetActiveOAuth2LoginSourceByName(provider)
if err != nil {
ctx.ServerError("SignIn", err)
return
@@ -608,7 +609,7 @@ func SignInOAuthCallback(ctx *context.Context) {
provider := ctx.Params(":provider")
// first look if the provider is still active
loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
loginSource, err := login.GetActiveOAuth2LoginSourceByName(provider)
if err != nil {
ctx.ServerError("SignIn", err)
return
@@ -653,7 +654,7 @@ func SignInOAuthCallback(ctx *context.Context) {
FullName: gothUser.Name,
Email: gothUser.Email,
IsActive: !setting.OAuth2Client.RegisterEmailConfirm,
LoginType: models.LoginOAuth2,
LoginType: login.OAuth2,
LoginSource: loginSource.ID,
LoginName: gothUser.UserID,
}
@@ -711,7 +712,7 @@ func updateAvatarIfNeed(url string, u *models.User) {
}
}
func handleOAuth2SignIn(ctx *context.Context, source *models.LoginSource, u *models.User, gothUser goth.User) {
func handleOAuth2SignIn(ctx *context.Context, source *login.Source, u *models.User, gothUser goth.User) {
updateAvatarIfNeed(gothUser.AvatarURL, u)
needs2FA := false
@@ -785,7 +786,7 @@ func handleOAuth2SignIn(ctx *context.Context, source *models.LoginSource, u *mod
// OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful
// login the user
func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Request, response http.ResponseWriter) (*models.User, goth.User, error) {
func oAuth2UserLoginCallback(loginSource *login.Source, request *http.Request, response http.ResponseWriter) (*models.User, goth.User, error) {
gothUser, err := loginSource.Cfg.(*oauth2.Source).Callback(request, response)
if err != nil {
if err.Error() == "securecookie: the value is too long" {
@@ -797,7 +798,7 @@ func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Requ
user := &models.User{
LoginName: gothUser.UserID,
LoginType: models.LoginOAuth2,
LoginType: login.OAuth2,
LoginSource: loginSource.ID,
}
@@ -1068,7 +1069,7 @@ func LinkAccountPostRegister(ctx *context.Context) {
}
}
loginSource, err := models.GetActiveOAuth2LoginSourceByName(gothUser.Provider)
loginSource, err := login.GetActiveOAuth2LoginSourceByName(gothUser.Provider)
if err != nil {
ctx.ServerError("CreateUser", err)
}
@@ -1078,7 +1079,7 @@ func LinkAccountPostRegister(ctx *context.Context) {
Email: form.Email,
Passwd: form.Password,
IsActive: !(setting.Service.RegisterEmailConfirm || setting.Service.RegisterManualConfirm),
LoginType: models.LoginOAuth2,
LoginType: login.OAuth2,
LoginSource: loginSource.ID,
LoginName: gothUser.UserID,
}

View File

@@ -15,6 +15,7 @@ import (
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
issue_indexer "code.gitea.io/gitea/modules/indexer/issues"
@@ -846,7 +847,7 @@ func repoIDMap(ctxUser *models.User, issueCountByRepo map[int64]int64, unitType
// ShowSSHKeys output all the ssh keys of user by uid
func ShowSSHKeys(ctx *context.Context, uid int64) {
keys, err := models.ListPublicKeys(uid, models.ListOptions{})
keys, err := models.ListPublicKeys(uid, db.ListOptions{})
if err != nil {
ctx.ServerError("ListPublicKeys", err)
return
@@ -862,7 +863,7 @@ func ShowSSHKeys(ctx *context.Context, uid int64) {
// ShowGPGKeys output all the public GPG keys of user by uid
func ShowGPGKeys(ctx *context.Context, uid int64) {
keys, err := models.ListGPGKeys(uid, models.ListOptions{})
keys, err := models.ListGPGKeys(uid, db.ListOptions{})
if err != nil {
ctx.ServerError("ListGPGKeys", err)
return

View File

@@ -13,6 +13,7 @@ import (
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/login"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/json"
@@ -115,7 +116,7 @@ type AccessTokenResponse struct {
IDToken string `json:"id_token,omitempty"`
}
func newAccessTokenResponse(grant *models.OAuth2Grant, serverKey, clientKey oauth2.JWTSigningKey) (*AccessTokenResponse, *AccessTokenError) {
func newAccessTokenResponse(grant *login.OAuth2Grant, serverKey, clientKey oauth2.JWTSigningKey) (*AccessTokenResponse, *AccessTokenError) {
if setting.OAuth2.InvalidateRefreshTokens {
if err := grant.IncreaseCounter(); err != nil {
return nil, &AccessTokenError{
@@ -162,7 +163,7 @@ func newAccessTokenResponse(grant *models.OAuth2Grant, serverKey, clientKey oaut
// generate OpenID Connect id_token
signedIDToken := ""
if grant.ScopeContains("openid") {
app, err := models.GetOAuth2ApplicationByID(grant.ApplicationID)
app, err := login.GetOAuth2ApplicationByID(grant.ApplicationID)
if err != nil {
return nil, &AccessTokenError{
ErrorCode: AccessTokenErrorCodeInvalidRequest,
@@ -268,9 +269,9 @@ func IntrospectOAuth(ctx *context.Context) {
token, err := oauth2.ParseToken(form.Token, oauth2.DefaultSigningKey)
if err == nil {
if token.Valid() == nil {
grant, err := models.GetOAuth2GrantByID(token.GrantID)
grant, err := login.GetOAuth2GrantByID(token.GrantID)
if err == nil && grant != nil {
app, err := models.GetOAuth2ApplicationByID(grant.ApplicationID)
app, err := login.GetOAuth2ApplicationByID(grant.ApplicationID)
if err == nil && app != nil {
response.Active = true
response.Scope = grant.Scope
@@ -299,9 +300,9 @@ func AuthorizeOAuth(ctx *context.Context) {
return
}
app, err := models.GetOAuth2ApplicationByClientID(form.ClientID)
app, err := login.GetOAuth2ApplicationByClientID(form.ClientID)
if err != nil {
if models.IsErrOauthClientIDInvalid(err) {
if login.IsErrOauthClientIDInvalid(err) {
handleAuthorizeError(ctx, AuthorizeError{
ErrorCode: ErrorCodeUnauthorizedClient,
ErrorDescription: "Client ID not registered",
@@ -312,8 +313,10 @@ func AuthorizeOAuth(ctx *context.Context) {
ctx.ServerError("GetOAuth2ApplicationByClientID", err)
return
}
if err := app.LoadUser(); err != nil {
ctx.ServerError("LoadUser", err)
user, err := models.GetUserByID(app.UID)
if err != nil {
ctx.ServerError("GetUserByID", err)
return
}
@@ -406,7 +409,7 @@ func AuthorizeOAuth(ctx *context.Context) {
ctx.Data["State"] = form.State
ctx.Data["Scope"] = form.Scope
ctx.Data["Nonce"] = form.Nonce
ctx.Data["ApplicationUserLink"] = "<a href=\"" + html.EscapeString(setting.AppURL) + html.EscapeString(url.PathEscape(app.User.LowerName)) + "\">@" + html.EscapeString(app.User.Name) + "</a>"
ctx.Data["ApplicationUserLink"] = "<a href=\"" + html.EscapeString(setting.AppURL) + html.EscapeString(url.PathEscape(user.LowerName)) + "\">@" + html.EscapeString(user.Name) + "</a>"
ctx.Data["ApplicationRedirectDomainHTML"] = "<strong>" + html.EscapeString(form.RedirectURI) + "</strong>"
// TODO document SESSION <=> FORM
err = ctx.Session.Set("client_id", app.ClientID)
@@ -443,7 +446,7 @@ func GrantApplicationOAuth(ctx *context.Context) {
ctx.Error(http.StatusBadRequest)
return
}
app, err := models.GetOAuth2ApplicationByClientID(form.ClientID)
app, err := login.GetOAuth2ApplicationByClientID(form.ClientID)
if err != nil {
ctx.ServerError("GetOAuth2ApplicationByClientID", err)
return
@@ -581,7 +584,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server
return
}
// get grant before increasing counter
grant, err := models.GetOAuth2GrantByID(token.GrantID)
grant, err := login.GetOAuth2GrantByID(token.GrantID)
if err != nil || grant == nil {
handleAccessTokenError(ctx, AccessTokenError{
ErrorCode: AccessTokenErrorCodeInvalidGrant,
@@ -608,7 +611,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server
}
func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, serverKey, clientKey oauth2.JWTSigningKey) {
app, err := models.GetOAuth2ApplicationByClientID(form.ClientID)
app, err := login.GetOAuth2ApplicationByClientID(form.ClientID)
if err != nil {
handleAccessTokenError(ctx, AccessTokenError{
ErrorCode: AccessTokenErrorCodeInvalidClient,
@@ -630,7 +633,7 @@ func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, s
})
return
}
authorizationCode, err := models.GetOAuth2AuthorizationByCode(form.Code)
authorizationCode, err := login.GetOAuth2AuthorizationByCode(form.Code)
if err != nil || authorizationCode == nil {
handleAccessTokenError(ctx, AccessTokenError{
ErrorCode: AccessTokenErrorCodeUnauthorizedClient,

View File

@@ -9,13 +9,14 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/login"
"code.gitea.io/gitea/services/auth/source/oauth2"
"github.com/golang-jwt/jwt"
"github.com/stretchr/testify/assert"
)
func createAndParseToken(t *testing.T, grant *models.OAuth2Grant) *oauth2.OIDCToken {
func createAndParseToken(t *testing.T, grant *login.OAuth2Grant) *oauth2.OIDCToken {
signingKey, err := oauth2.CreateJWTSigningKey("HS256", make([]byte, 32))
assert.NoError(t, err)
assert.NotNil(t, signingKey)
@@ -42,7 +43,7 @@ func createAndParseToken(t *testing.T, grant *models.OAuth2Grant) *oauth2.OIDCTo
func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase())
grants, err := models.GetOAuth2GrantsByUserID(3)
grants, err := login.GetOAuth2GrantsByUserID(3)
assert.NoError(t, err)
assert.Len(t, grants, 1)
@@ -58,7 +59,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
assert.False(t, oidcToken.EmailVerified)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
grants, err = models.GetOAuth2GrantsByUserID(user.ID)
grants, err = login.GetOAuth2GrantsByUserID(user.ID)
assert.NoError(t, err)
assert.Len(t, grants, 1)

View File

@@ -12,6 +12,7 @@ import (
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/markup/markdown"
@@ -192,7 +193,7 @@ func Profile(ctx *context.Context) {
ctx.Data["Keyword"] = keyword
switch tab {
case "followers":
items, err := ctxUser.GetFollowers(models.ListOptions{
items, err := ctxUser.GetFollowers(db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum,
Page: page,
})
@@ -204,7 +205,7 @@ func Profile(ctx *context.Context) {
total = ctxUser.NumFollowers
case "following":
items, err := ctxUser.GetFollowing(models.ListOptions{
items, err := ctxUser.GetFollowing(db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum,
Page: page,
})
@@ -229,7 +230,7 @@ func Profile(ctx *context.Context) {
case "stars":
ctx.Data["PageIsProfileStarList"] = true
repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
ListOptions: models.ListOptions{
ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum,
Page: page,
},
@@ -260,7 +261,7 @@ func Profile(ctx *context.Context) {
}
case "watching":
repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
ListOptions: models.ListOptions{
ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum,
Page: page,
},
@@ -281,7 +282,7 @@ func Profile(ctx *context.Context) {
total = int(count)
default:
repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
ListOptions: models.ListOptions{
ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum,
Page: page,
},

View File

@@ -9,6 +9,7 @@ import (
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/login"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
@@ -92,12 +93,12 @@ func loadApplicationsData(ctx *context.Context) {
ctx.Data["Tokens"] = tokens
ctx.Data["EnableOAuth2"] = setting.OAuth2.Enable
if setting.OAuth2.Enable {
ctx.Data["Applications"], err = models.GetOAuth2ApplicationsByUserID(ctx.User.ID)
ctx.Data["Applications"], err = login.GetOAuth2ApplicationsByUserID(ctx.User.ID)
if err != nil {
ctx.ServerError("GetOAuth2ApplicationsByUserID", err)
return
}
ctx.Data["Grants"], err = models.GetOAuth2GrantsByUserID(ctx.User.ID)
ctx.Data["Grants"], err = login.GetOAuth2GrantsByUserID(ctx.User.ID)
if err != nil {
ctx.ServerError("GetOAuth2GrantsByUserID", err)
return

View File

@@ -9,6 +9,7 @@ import (
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
@@ -233,7 +234,7 @@ func DeleteKey(ctx *context.Context) {
}
func loadKeysData(ctx *context.Context) {
keys, err := models.ListPublicKeys(ctx.User.ID, models.ListOptions{})
keys, err := models.ListPublicKeys(ctx.User.ID, db.ListOptions{})
if err != nil {
ctx.ServerError("ListPublicKeys", err)
return
@@ -247,7 +248,7 @@ func loadKeysData(ctx *context.Context) {
}
ctx.Data["ExternalKeys"] = externalKeys
gpgkeys, err := models.ListGPGKeys(ctx.User.ID, models.ListOptions{})
gpgkeys, err := models.ListGPGKeys(ctx.User.ID, db.ListOptions{})
if err != nil {
ctx.ServerError("ListGPGKeys", err)
return
@@ -258,7 +259,7 @@ func loadKeysData(ctx *context.Context) {
// generate a new aes cipher using the csrfToken
ctx.Data["TokenToSign"] = tokenToSign
principals, err := models.ListPrincipalKeys(ctx.User.ID, models.ListOptions{})
principals, err := models.ListPrincipalKeys(ctx.User.ID, db.ListOptions{})
if err != nil {
ctx.ServerError("ListPrincipalKeys", err)
return

View File

@@ -8,7 +8,7 @@ import (
"fmt"
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/login"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
@@ -34,7 +34,7 @@ func OAuthApplicationsPost(ctx *context.Context) {
return
}
// TODO validate redirect URI
app, err := models.CreateOAuth2Application(models.CreateOAuth2ApplicationOptions{
app, err := login.CreateOAuth2Application(login.CreateOAuth2ApplicationOptions{
Name: form.Name,
RedirectURIs: []string{form.RedirectURI},
UserID: ctx.User.ID,
@@ -67,7 +67,7 @@ func OAuthApplicationsEdit(ctx *context.Context) {
}
// TODO validate redirect URI
var err error
if ctx.Data["App"], err = models.UpdateOAuth2Application(models.UpdateOAuth2ApplicationOptions{
if ctx.Data["App"], err = login.UpdateOAuth2Application(login.UpdateOAuth2ApplicationOptions{
ID: ctx.ParamsInt64("id"),
Name: form.Name,
RedirectURIs: []string{form.RedirectURI},
@@ -85,9 +85,9 @@ func OAuthApplicationsRegenerateSecret(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsApplications"] = true
app, err := models.GetOAuth2ApplicationByID(ctx.ParamsInt64("id"))
app, err := login.GetOAuth2ApplicationByID(ctx.ParamsInt64("id"))
if err != nil {
if models.IsErrOAuthApplicationNotFound(err) {
if login.IsErrOAuthApplicationNotFound(err) {
ctx.NotFound("Application not found", err)
return
}
@@ -110,9 +110,9 @@ func OAuthApplicationsRegenerateSecret(ctx *context.Context) {
// OAuth2ApplicationShow displays the given application
func OAuth2ApplicationShow(ctx *context.Context) {
app, err := models.GetOAuth2ApplicationByID(ctx.ParamsInt64("id"))
app, err := login.GetOAuth2ApplicationByID(ctx.ParamsInt64("id"))
if err != nil {
if models.IsErrOAuthApplicationNotFound(err) {
if login.IsErrOAuthApplicationNotFound(err) {
ctx.NotFound("Application not found", err)
return
}
@@ -129,7 +129,7 @@ func OAuth2ApplicationShow(ctx *context.Context) {
// DeleteOAuth2Application deletes the given oauth2 application
func DeleteOAuth2Application(ctx *context.Context) {
if err := models.DeleteOAuth2Application(ctx.FormInt64("id"), ctx.User.ID); err != nil {
if err := login.DeleteOAuth2Application(ctx.FormInt64("id"), ctx.User.ID); err != nil {
ctx.ServerError("DeleteOAuth2Application", err)
return
}
@@ -147,7 +147,7 @@ func RevokeOAuth2Grant(ctx *context.Context) {
ctx.ServerError("RevokeOAuth2Grant", fmt.Errorf("user id or grant id is zero"))
return
}
if err := models.RevokeOAuth2Grant(ctx.FormInt64("id"), ctx.User.ID); err != nil {
if err := login.RevokeOAuth2Grant(ctx.FormInt64("id"), ctx.User.ID); err != nil {
ctx.ServerError("RevokeOAuth2Grant", err)
return
}

View File

@@ -15,6 +15,7 @@ import (
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
@@ -235,7 +236,7 @@ func Repos(ctx *context.Context) {
ctx.Data["allowAdopt"] = ctx.IsUserSiteAdmin() || setting.Repository.AllowAdoptionOfUnadoptedRepositories
ctx.Data["allowDelete"] = ctx.IsUserSiteAdmin() || setting.Repository.AllowDeleteOfUnadoptedRepositories
opts := models.ListOptions{
opts := db.ListOptions{
PageSize: setting.UI.Admin.UserPagingNum,
Page: ctx.FormInt("page"),
}
@@ -284,7 +285,7 @@ func Repos(ctx *context.Context) {
return
}
if err := ctxUser.GetRepositories(models.ListOptions{Page: 1, PageSize: setting.UI.Admin.UserPagingNum}, repoNames...); err != nil {
if err := ctxUser.GetRepositories(db.ListOptions{Page: 1, PageSize: setting.UI.Admin.UserPagingNum}, repoNames...); err != nil {
ctx.ServerError("GetRepositories", err)
return
}

View File

@@ -9,6 +9,7 @@ import (
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/login"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
@@ -87,9 +88,9 @@ func loadSecurityData(ctx *context.Context) {
}
// map the provider display name with the LoginSource
sources := make(map[*models.LoginSource]string)
sources := make(map[*login.Source]string)
for _, externalAccount := range accountLinks {
if loginSource, err := models.GetLoginSourceByID(externalAccount.LoginSourceID); err == nil {
if loginSource, err := login.GetSourceByID(externalAccount.LoginSourceID); err == nil {
var providerDisplayName string
type DisplayNamed interface {