From 1995fa1f8f23fe8325490c29ce54c0bc86c5e109 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 6 Jun 2021 17:24:36 +0800 Subject: [PATCH 1/8] Add sso.Group, context.Auth, context.APIAuth to allow auth special routes --- modules/auth/sso/basic.go | 8 +++- modules/auth/sso/group.go | 82 ++++++++++++++++++++++++++++++++ modules/auth/sso/interface.go | 2 + modules/auth/sso/oauth2.go | 5 ++ modules/auth/sso/reverseproxy.go | 5 ++ modules/auth/sso/session.go | 5 ++ modules/auth/sso/sspi_windows.go | 5 ++ modules/auth/sso/user.go | 33 ------------- modules/context/api.go | 37 ++++++++------ modules/context/context.go | 44 ++++++++++------- routers/api/v1/api.go | 4 ++ routers/web/web.go | 4 ++ 12 files changed, 167 insertions(+), 67 deletions(-) create mode 100644 modules/auth/sso/group.go delete mode 100644 modules/auth/sso/user.go diff --git a/modules/auth/sso/basic.go b/modules/auth/sso/basic.go index 555128812851..5de006113e97 100644 --- a/modules/auth/sso/basic.go +++ b/modules/auth/sso/basic.go @@ -28,6 +28,11 @@ var ( type Basic struct { } +// Name represents the name of auth method +func (b *Basic) Name() string { + return "basic" +} + // Init does nothing as the Basic implementation does not need to allocate any resources func (b *Basic) Init() error { return nil @@ -49,9 +54,8 @@ func (b *Basic) IsEnabled() bool { // name/token on successful validation. // Returns nil if header is empty or validation fails. func (b *Basic) VerifyAuthData(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { - // Basic authentication should only fire on API, Download or on Git or LFSPaths - if middleware.IsInternalPath(req) || !middleware.IsAPIPath(req) && !isAttachmentDownload(req) && !isGitRawOrLFSPath(req) { + if !middleware.IsAPIPath(req) && !isAttachmentDownload(req) && !isGitRawOrLFSPath(req) { return nil } diff --git a/modules/auth/sso/group.go b/modules/auth/sso/group.go new file mode 100644 index 000000000000..c1821528ecf3 --- /dev/null +++ b/modules/auth/sso/group.go @@ -0,0 +1,82 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package sso + +import ( + "net/http" + + "code.gitea.io/gitea/models" +) + +// Ensure the struct implements the interface. +var ( + _ SingleSignOn = &Group{} +) + +// Group implements the SingleSignOn interface with serval SingleSignOn. +type Group struct { + methods []SingleSignOn +} + +// NewGroup creates a new auth group +func NewGroup(methods ...SingleSignOn) *Group { + return &Group{ + methods: methods, + } +} + +// Name represents the name of auth method +func (b *Group) Name() string { + return "group" +} + +// Init does nothing as the Basic implementation does not need to allocate any resources +func (b *Group) Init() error { + for _, m := range b.methods { + if err := m.Init(); err != nil { + return err + } + } + return nil +} + +// Free does nothing as the Basic implementation does not have to release any resources +func (b *Group) Free() error { + for _, m := range b.methods { + if err := m.Free(); err != nil { + return err + } + } + return nil +} + +// IsEnabled returns true as this plugin is enabled by default and its not possible to disable +// it from settings. +func (b *Group) IsEnabled() bool { + return true +} + +// VerifyAuthData extracts and validates +func (b *Group) VerifyAuthData(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { + if !models.HasEngine { + return nil + } + + // Try to sign in with each of the enabled plugins + for _, ssoMethod := range b.methods { + if !ssoMethod.IsEnabled() { + continue + } + user := ssoMethod.VerifyAuthData(req, w, store, sess) + if user != nil { + if store.GetData()["AuthedMethod"] == nil { + store.GetData()["AuthedMethod"] = ssoMethod.Name() + } + return user + } + } + + return nil +} diff --git a/modules/auth/sso/interface.go b/modules/auth/sso/interface.go index 9b1472f2b37f..5531841f9c92 100644 --- a/modules/auth/sso/interface.go +++ b/modules/auth/sso/interface.go @@ -20,6 +20,8 @@ type SessionStore session.Store // SingleSignOn represents a SSO authentication method (plugin) for HTTP requests. type SingleSignOn interface { + Name() string + // Init should be called exactly once before using any of the other methods, // in order to allow the plugin to allocate necessary resources Init() error diff --git a/modules/auth/sso/oauth2.go b/modules/auth/sso/oauth2.go index b052b5599a88..ce301fd1eff7 100644 --- a/modules/auth/sso/oauth2.go +++ b/modules/auth/sso/oauth2.go @@ -56,6 +56,11 @@ func (o *OAuth2) Init() error { return nil } +// Name represents the name of auth method +func (b *OAuth2) Name() string { + return "oauth2" +} + // Free does nothing as the OAuth2 implementation does not have to release any resources func (o *OAuth2) Free() error { return nil diff --git a/modules/auth/sso/reverseproxy.go b/modules/auth/sso/reverseproxy.go index 3fffee0320d2..3df952d1849a 100644 --- a/modules/auth/sso/reverseproxy.go +++ b/modules/auth/sso/reverseproxy.go @@ -39,6 +39,11 @@ func (r *ReverseProxy) getUserName(req *http.Request) string { return webAuthUser } +// Name represents the name of auth method +func (b *ReverseProxy) Name() string { + return "reverse_proxy" +} + // Init does nothing as the ReverseProxy implementation does not need initialization func (r *ReverseProxy) Init() error { return nil diff --git a/modules/auth/sso/session.go b/modules/auth/sso/session.go index 7a546577d86e..26ae3fb43d52 100644 --- a/modules/auth/sso/session.go +++ b/modules/auth/sso/session.go @@ -25,6 +25,11 @@ func (s *Session) Init() error { return nil } +// Name represents the name of auth method +func (b *Session) Name() string { + return "session" +} + // Free does nothing as the Session implementation does not have to release any resources func (s *Session) Free() error { return nil diff --git a/modules/auth/sso/sspi_windows.go b/modules/auth/sso/sspi_windows.go index 2092a5e28976..c0acb6efe9f2 100644 --- a/modules/auth/sso/sspi_windows.go +++ b/modules/auth/sso/sspi_windows.go @@ -62,6 +62,11 @@ func (s *SSPI) Init() error { return nil } +// Name represents the name of auth method +func (b *SSPI) Name() string { + return "sspi" +} + // Free releases resources used by the global websspi.Authenticator object func (s *SSPI) Free() error { return sspiAuth.Free() diff --git a/modules/auth/sso/user.go b/modules/auth/sso/user.go deleted file mode 100644 index 48eebb1e915f..000000000000 --- a/modules/auth/sso/user.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2020 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package sso - -import ( - "net/http" - - "code.gitea.io/gitea/models" -) - -// SignedInUser returns the user object of signed user. -// It returns a bool value to indicate whether user uses basic auth or not. -func SignedInUser(req *http.Request, w http.ResponseWriter, ds DataStore, sess SessionStore) (*models.User, bool) { - if !models.HasEngine { - return nil, false - } - - // Try to sign in with each of the enabled plugins - for _, ssoMethod := range Methods() { - if !ssoMethod.IsEnabled() { - continue - } - user := ssoMethod.VerifyAuthData(req, w, ds, sess) - if user != nil { - _, isBasic := ssoMethod.(*Basic) - return user, isBasic - } - } - - return nil, false -} diff --git a/modules/context/api.go b/modules/context/api.go index cbd90c50e4b8..e034e30b3beb 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -217,6 +217,29 @@ func (ctx *APIContext) CheckForOTP() { } } +// APIAuth converts sso.SingleSignOn as a middleware +func APIAuth(authMethod sso.SingleSignOn) func(*APIContext) { + return func(ctx *APIContext) { + if !authMethod.IsEnabled() { + return + } + // Get user from session if logged in. + ctx.User = authMethod.VerifyAuthData(ctx.Req, ctx.Resp, ctx, ctx.Session) + if ctx.User != nil { + ctx.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == new(sso.Basic).Name() + ctx.IsSigned = true + ctx.Data["IsSigned"] = ctx.IsSigned + ctx.Data["SignedUser"] = ctx.User + ctx.Data["SignedUserID"] = ctx.User.ID + ctx.Data["SignedUserName"] = ctx.User.Name + ctx.Data["IsAdmin"] = ctx.User.IsAdmin + } else { + ctx.Data["SignedUserID"] = int64(0) + ctx.Data["SignedUserName"] = "" + } + } +} + // APIContexter returns apicontext as middleware func APIContexter() func(http.Handler) http.Handler { var csrfOpts = getCsrfOpts() @@ -250,20 +273,6 @@ func APIContexter() func(http.Handler) http.Handler { } } - // Get user from session if logged in. - ctx.User, ctx.IsBasicAuth = sso.SignedInUser(ctx.Req, ctx.Resp, &ctx, ctx.Session) - if ctx.User != nil { - ctx.IsSigned = true - ctx.Data["IsSigned"] = ctx.IsSigned - ctx.Data["SignedUser"] = ctx.User - ctx.Data["SignedUserID"] = ctx.User.ID - ctx.Data["SignedUserName"] = ctx.User.Name - ctx.Data["IsAdmin"] = ctx.User.IsAdmin - } else { - ctx.Data["SignedUserID"] = int64(0) - ctx.Data["SignedUserName"] = "" - } - ctx.Resp.Header().Set(`X-Frame-Options`, `SAMEORIGIN`) ctx.Data["CsrfToken"] = html.EscapeString(ctx.csrf.GetToken()) diff --git a/modules/context/context.go b/modules/context/context.go index d45e9ff87cd8..acbb4397ea27 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -605,6 +605,32 @@ func getCsrfOpts() CsrfOptions { } } +// Auth converts sso.SingleSignOn as a middleware +func Auth(authMethod sso.SingleSignOn) func(*Context) { + return func(ctx *Context) { + if !authMethod.IsEnabled() { + return + } + + ctx.User = authMethod.VerifyAuthData(ctx.Req, ctx.Resp, ctx, ctx.Session) + if ctx.User != nil { + ctx.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == new(sso.Basic).Name() + ctx.IsSigned = true + ctx.Data["IsSigned"] = ctx.IsSigned + ctx.Data["SignedUser"] = ctx.User + ctx.Data["SignedUserID"] = ctx.User.ID + ctx.Data["SignedUserName"] = ctx.User.Name + ctx.Data["IsAdmin"] = ctx.User.IsAdmin + } else { + ctx.Data["SignedUserID"] = int64(0) + ctx.Data["SignedUserName"] = "" + + // ensure the session uid is deleted + _ = ctx.Session.Delete("uid") + } + } +} + // Contexter initializes a classic context for a request. func Contexter() func(next http.Handler) http.Handler { var rnd = templates.HTMLRenderer() @@ -690,24 +716,6 @@ func Contexter() func(next http.Handler) http.Handler { } } - // Get user from session if logged in. - ctx.User, ctx.IsBasicAuth = sso.SignedInUser(ctx.Req, ctx.Resp, &ctx, ctx.Session) - - if ctx.User != nil { - ctx.IsSigned = true - ctx.Data["IsSigned"] = ctx.IsSigned - ctx.Data["SignedUser"] = ctx.User - ctx.Data["SignedUserID"] = ctx.User.ID - ctx.Data["SignedUserName"] = ctx.User.Name - ctx.Data["IsAdmin"] = ctx.User.IsAdmin - } else { - ctx.Data["SignedUserID"] = int64(0) - ctx.Data["SignedUserName"] = "" - - // ensure the session uid is deleted - _ = ctx.Session.Delete("uid") - } - ctx.Resp.Header().Set(`X-Frame-Options`, `SAMEORIGIN`) ctx.Data["CsrfToken"] = html.EscapeString(ctx.csrf.GetToken()) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index f3efd67bb3e1..c4c39f9c5bda 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -70,6 +70,7 @@ import ( "strings" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/auth/sso" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -573,6 +574,9 @@ func Routes() *web.Route { } m.Use(context.APIContexter()) + // Get user from session if logged in. + m.Use(context.APIAuth(sso.NewGroup(sso.Methods()...))) + m.Use(context.ToggleAPI(&context.ToggleOptions{ SignInRequired: setting.Service.RequireSignInView, })) diff --git a/routers/web/web.go b/routers/web/web.go index 6c0141eef30a..f8c345019fae 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -11,6 +11,7 @@ import ( "path" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/auth/sso" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/httpcache" "code.gitea.io/gitea/modules/log" @@ -149,6 +150,9 @@ func Routes() *web.Route { // Removed: toolbox.Toolboxer middleware will provide debug informations which seems unnecessary common = append(common, context.Contexter()) + // Get user from session if logged in. + common = append(common, context.Auth(sso.NewGroup(sso.Methods()...))) + // GetHead allows a HEAD request redirect to GET if HEAD method is not defined for that route common = append(common, middleware.GetHead) From 2f54bcd8be276bc6dab314fe56ebcd9729281371 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 6 Jun 2021 17:26:56 +0800 Subject: [PATCH 2/8] Remove unnecessary check --- modules/auth/sso/oauth2.go | 2 +- modules/auth/sso/sspi_windows.go | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/modules/auth/sso/oauth2.go b/modules/auth/sso/oauth2.go index ce301fd1eff7..2501f5f99963 100644 --- a/modules/auth/sso/oauth2.go +++ b/modules/auth/sso/oauth2.go @@ -127,7 +127,7 @@ func (o *OAuth2) VerifyAuthData(req *http.Request, w http.ResponseWriter, store return nil } - if middleware.IsInternalPath(req) || !middleware.IsAPIPath(req) && !isAttachmentDownload(req) { + if !middleware.IsAPIPath(req) && !isAttachmentDownload(req) { return nil } diff --git a/modules/auth/sso/sspi_windows.go b/modules/auth/sso/sspi_windows.go index c0acb6efe9f2..a0aef3792bab 100644 --- a/modules/auth/sso/sspi_windows.go +++ b/modules/auth/sso/sspi_windows.go @@ -174,8 +174,6 @@ func (s *SSPI) shouldAuthenticate(req *http.Request) (shouldAuth bool) { } else if req.FormValue("auth_with_sspi") == "1" { shouldAuth = true } - } else if middleware.IsInternalPath(req) { - shouldAuth = false } else if middleware.IsAPIPath(req) || isAttachmentDownload(req) { shouldAuth = true } From 491c8dd521c174ef466d15a17a4d17ce773513dc Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 7 Jun 2021 16:45:03 +0800 Subject: [PATCH 3/8] Fix lint --- modules/auth/sso/oauth2.go | 2 +- modules/auth/sso/reverseproxy.go | 2 +- modules/auth/sso/session.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/auth/sso/oauth2.go b/modules/auth/sso/oauth2.go index 2501f5f99963..bd280bd1b410 100644 --- a/modules/auth/sso/oauth2.go +++ b/modules/auth/sso/oauth2.go @@ -57,7 +57,7 @@ func (o *OAuth2) Init() error { } // Name represents the name of auth method -func (b *OAuth2) Name() string { +func (o *OAuth2) Name() string { return "oauth2" } diff --git a/modules/auth/sso/reverseproxy.go b/modules/auth/sso/reverseproxy.go index 3df952d1849a..622cf0073f0a 100644 --- a/modules/auth/sso/reverseproxy.go +++ b/modules/auth/sso/reverseproxy.go @@ -40,7 +40,7 @@ func (r *ReverseProxy) getUserName(req *http.Request) string { } // Name represents the name of auth method -func (b *ReverseProxy) Name() string { +func (r *ReverseProxy) Name() string { return "reverse_proxy" } diff --git a/modules/auth/sso/session.go b/modules/auth/sso/session.go index 26ae3fb43d52..2f5ed4e3dcad 100644 --- a/modules/auth/sso/session.go +++ b/modules/auth/sso/session.go @@ -26,7 +26,7 @@ func (s *Session) Init() error { } // Name represents the name of auth method -func (b *Session) Name() string { +func (s *Session) Name() string { return "session" } From 558b2fc5ac324e643f0f52fa17a8b17258c73fe2 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 7 Jun 2021 17:01:20 +0800 Subject: [PATCH 4/8] Fix lint for windows --- modules/auth/sso/sspi_windows.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/auth/sso/sspi_windows.go b/modules/auth/sso/sspi_windows.go index a0aef3792bab..fc4e4de812cc 100644 --- a/modules/auth/sso/sspi_windows.go +++ b/modules/auth/sso/sspi_windows.go @@ -63,7 +63,7 @@ func (s *SSPI) Init() error { } // Name represents the name of auth method -func (b *SSPI) Name() string { +func (s *SSPI) Name() string { return "sspi" } From 3b141e145c24a705afeb1337e22ad10cf5be2f55 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 8 Jun 2021 11:13:13 +0800 Subject: [PATCH 5/8] Rename sso -> auth --- modules/context/api.go | 8 +++--- modules/context/context.go | 8 +++--- routers/api/v1/api.go | 4 +-- routers/init.go | 4 +-- routers/web/base.go | 4 +-- routers/web/user/oauth.go | 4 +-- routers/web/web.go | 4 +-- .../auth/sso/sso.go => services/auth/auth.go | 26 +++++++++---------- .../sso_test.go => services/auth/auth_test.go | 2 +- {modules/auth/sso => services/auth}/basic.go | 6 ++--- {modules/auth/sso => services/auth}/group.go | 10 +++---- .../auth/sso => services/auth}/interface.go | 10 +++---- {modules/auth/sso => services/auth}/oauth2.go | 6 ++--- .../sso => services/auth}/reverseproxy.go | 6 ++--- .../auth/sso => services/auth}/session.go | 4 +-- .../sso => services/auth}/sspi_windows.go | 6 ++--- 16 files changed, 56 insertions(+), 56 deletions(-) rename modules/auth/sso/sso.go => services/auth/auth.go (87%) rename modules/auth/sso/sso_test.go => services/auth/auth_test.go (99%) rename {modules/auth/sso => services/auth}/basic.go (96%) rename {modules/auth/sso => services/auth}/group.go (89%) rename {modules/auth/sso => services/auth}/interface.go (80%) rename {modules/auth/sso => services/auth}/oauth2.go (97%) rename {modules/auth/sso => services/auth}/reverseproxy.go (97%) rename {modules/auth/sso => services/auth}/session.go (97%) rename {modules/auth/sso => services/auth}/sspi_windows.go (98%) diff --git a/modules/context/api.go b/modules/context/api.go index e034e30b3beb..dbfee57d1013 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -14,11 +14,11 @@ import ( "strings" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/auth/sso" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/web/middleware" + "code.gitea.io/gitea/services/auth" "gitea.com/go-chi/session" ) @@ -217,8 +217,8 @@ func (ctx *APIContext) CheckForOTP() { } } -// APIAuth converts sso.SingleSignOn as a middleware -func APIAuth(authMethod sso.SingleSignOn) func(*APIContext) { +// APIAuth converts auth.Auth as a middleware +func APIAuth(authMethod auth.Auth) func(*APIContext) { return func(ctx *APIContext) { if !authMethod.IsEnabled() { return @@ -226,7 +226,7 @@ func APIAuth(authMethod sso.SingleSignOn) func(*APIContext) { // Get user from session if logged in. ctx.User = authMethod.VerifyAuthData(ctx.Req, ctx.Resp, ctx, ctx.Session) if ctx.User != nil { - ctx.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == new(sso.Basic).Name() + ctx.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == new(auth.Basic).Name() ctx.IsSigned = true ctx.Data["IsSigned"] = ctx.IsSigned ctx.Data["SignedUser"] = ctx.User diff --git a/modules/context/context.go b/modules/context/context.go index acbb4397ea27..d2ee36660093 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -21,7 +21,6 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/auth/sso" "code.gitea.io/gitea/modules/base" mc "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/log" @@ -29,6 +28,7 @@ import ( "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/web/middleware" + "code.gitea.io/gitea/services/auth" "gitea.com/go-chi/cache" "gitea.com/go-chi/session" @@ -605,8 +605,8 @@ func getCsrfOpts() CsrfOptions { } } -// Auth converts sso.SingleSignOn as a middleware -func Auth(authMethod sso.SingleSignOn) func(*Context) { +// Auth converts auth.Auth as a middleware +func Auth(authMethod auth.Auth) func(*Context) { return func(ctx *Context) { if !authMethod.IsEnabled() { return @@ -614,7 +614,7 @@ func Auth(authMethod sso.SingleSignOn) func(*Context) { ctx.User = authMethod.VerifyAuthData(ctx.Req, ctx.Resp, ctx, ctx.Session) if ctx.User != nil { - ctx.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == new(sso.Basic).Name() + ctx.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == new(auth.Basic).Name() ctx.IsSigned = true ctx.Data["IsSigned"] = ctx.IsSigned ctx.Data["SignedUser"] = ctx.User diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index c4c39f9c5bda..acee6329afd0 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -70,7 +70,6 @@ import ( "strings" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/auth/sso" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -84,6 +83,7 @@ import ( "code.gitea.io/gitea/routers/api/v1/settings" _ "code.gitea.io/gitea/routers/api/v1/swagger" // for swagger generation "code.gitea.io/gitea/routers/api/v1/user" + "code.gitea.io/gitea/services/auth" "code.gitea.io/gitea/services/forms" "gitea.com/go-chi/binding" @@ -575,7 +575,7 @@ func Routes() *web.Route { m.Use(context.APIContexter()) // Get user from session if logged in. - m.Use(context.APIAuth(sso.NewGroup(sso.Methods()...))) + m.Use(context.APIAuth(auth.NewGroup(auth.Methods()...))) m.Use(context.ToggleAPI(&context.ToggleOptions{ SignInRequired: setting.Service.RequireSignInView, diff --git a/routers/init.go b/routers/init.go index 5e2eca439eb6..4c28a953955b 100644 --- a/routers/init.go +++ b/routers/init.go @@ -9,7 +9,6 @@ import ( "strings" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/auth/sso" "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/cron" "code.gitea.io/gitea/modules/eventsource" @@ -34,6 +33,7 @@ import ( "code.gitea.io/gitea/routers/common" "code.gitea.io/gitea/routers/private" web_routers "code.gitea.io/gitea/routers/web" + "code.gitea.io/gitea/services/auth" "code.gitea.io/gitea/services/mailer" mirror_service "code.gitea.io/gitea/services/mirror" pull_service "code.gitea.io/gitea/services/pull" @@ -134,7 +134,7 @@ func GlobalInit(ctx context.Context) { } else { ssh.Unused() } - sso.Init() + auth.Init() svg.Init() } diff --git a/routers/web/base.go b/routers/web/base.go index 8a44736434bd..f079be51f046 100644 --- a/routers/web/base.go +++ b/routers/web/base.go @@ -15,7 +15,6 @@ import ( "strings" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/auth/sso" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/httpcache" "code.gitea.io/gitea/modules/log" @@ -23,6 +22,7 @@ import ( "code.gitea.io/gitea/modules/storage" "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/web/middleware" + "code.gitea.io/gitea/services/auth" "gitea.com/go-chi/session" ) @@ -158,7 +158,7 @@ func Recovery() func(next http.Handler) http.Handler { } if user == nil { // Get user from session if logged in - do not attempt to sign-in - user = sso.SessionUser(sessionStore) + user = auth.SessionUser(sessionStore) } if user != nil { store["IsSigned"] = true diff --git a/routers/web/user/oauth.go b/routers/web/user/oauth.go index 3ef5a56c0173..3359c75020a2 100644 --- a/routers/web/user/oauth.go +++ b/routers/web/user/oauth.go @@ -13,13 +13,13 @@ import ( "strings" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/auth/sso" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/services/auth" "code.gitea.io/gitea/services/forms" "gitea.com/go-chi/binding" @@ -228,7 +228,7 @@ func InfoOAuth(ctx *context.Context) { ctx.HandleText(http.StatusUnauthorized, "no valid auth token authorization") return } - uid := sso.CheckOAuthAccessToken(auths[1]) + uid := auth.CheckOAuthAccessToken(auths[1]) if uid == 0 { handleBearerTokenError(ctx, BearerTokenError{ ErrorCode: BearerTokenErrorCodeInvalidToken, diff --git a/routers/web/web.go b/routers/web/web.go index f8c345019fae..df9efe25d6c5 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -11,7 +11,6 @@ import ( "path" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/auth/sso" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/httpcache" "code.gitea.io/gitea/modules/log" @@ -32,6 +31,7 @@ import ( "code.gitea.io/gitea/routers/web/repo" "code.gitea.io/gitea/routers/web/user" userSetting "code.gitea.io/gitea/routers/web/user/setting" + "code.gitea.io/gitea/services/auth" "code.gitea.io/gitea/services/forms" "code.gitea.io/gitea/services/lfs" "code.gitea.io/gitea/services/mailer" @@ -151,7 +151,7 @@ func Routes() *web.Route { common = append(common, context.Contexter()) // Get user from session if logged in. - common = append(common, context.Auth(sso.NewGroup(sso.Methods()...))) + common = append(common, context.Auth(auth.NewGroup(auth.Methods()...))) // GetHead allows a HEAD request redirect to GET if HEAD method is not defined for that route common = append(common, middleware.GetHead) diff --git a/modules/auth/sso/sso.go b/services/auth/auth.go similarity index 87% rename from modules/auth/sso/sso.go rename to services/auth/auth.go index 8543ceb2ffc0..7a6cdb751b31 100644 --- a/modules/auth/sso/sso.go +++ b/services/auth/auth.go @@ -3,7 +3,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package sso +package auth import ( "fmt" @@ -18,7 +18,7 @@ import ( "code.gitea.io/gitea/modules/web/middleware" ) -// ssoMethods contains the list of SSO authentication plugins in the order they are expected to be +// authMethods contains the list of authentication plugins in the order they are expected to be // executed. // // The OAuth2 plugin is expected to be executed first, as it must ignore the user id stored @@ -27,7 +27,7 @@ import ( // // The Session plugin is expected to be executed second, in order to skip authentication // for users that have already signed in. -var ssoMethods = []SingleSignOn{ +var authMethods = []Auth{ &OAuth2{}, &Basic{}, &Session{}, @@ -40,34 +40,34 @@ var ( _ = handleSignIn ) -// Methods returns the instances of all registered SSO methods -func Methods() []SingleSignOn { - return ssoMethods +// Methods returns the instances of all registered methods +func Methods() []Auth { + return authMethods } -// Register adds the specified instance to the list of available SSO methods -func Register(method SingleSignOn) { - ssoMethods = append(ssoMethods, method) +// Register adds the specified instance to the list of available methods +func Register(method Auth) { + authMethods = append(authMethods, method) } -// Init should be called exactly once when the application starts to allow SSO plugins +// Init should be called exactly once when the application starts to allow plugins // to allocate necessary resources func Init() { for _, method := range Methods() { err := method.Init() if err != nil { - log.Error("Could not initialize '%s' SSO method, error: %s", reflect.TypeOf(method).String(), err) + log.Error("Could not initialize '%s' auth method, error: %s", reflect.TypeOf(method).String(), err) } } } -// Free should be called exactly once when the application is terminating to allow SSO plugins +// Free should be called exactly once when the application is terminating to allow Auth plugins // to release necessary resources func Free() { for _, method := range Methods() { err := method.Free() if err != nil { - log.Error("Could not free '%s' SSO method, error: %s", reflect.TypeOf(method).String(), err) + log.Error("Could not free '%s' auth method, error: %s", reflect.TypeOf(method).String(), err) } } } diff --git a/modules/auth/sso/sso_test.go b/services/auth/auth_test.go similarity index 99% rename from modules/auth/sso/sso_test.go rename to services/auth/auth_test.go index e57788f35aec..f6b43835f45f 100644 --- a/modules/auth/sso/sso_test.go +++ b/services/auth/auth_test.go @@ -3,7 +3,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package sso +package auth import ( "net/http" diff --git a/modules/auth/sso/basic.go b/services/auth/basic.go similarity index 96% rename from modules/auth/sso/basic.go rename to services/auth/basic.go index 5de006113e97..acbeff43f092 100644 --- a/modules/auth/sso/basic.go +++ b/services/auth/basic.go @@ -3,7 +3,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package sso +package auth import ( "net/http" @@ -19,10 +19,10 @@ import ( // Ensure the struct implements the interface. var ( - _ SingleSignOn = &Basic{} + _ Auth = &Basic{} ) -// Basic implements the SingleSignOn interface and authenticates requests (API requests +// Basic implements the Auth interface and authenticates requests (API requests // only) by looking for Basic authentication data or "x-oauth-basic" token in the "Authorization" // header. type Basic struct { diff --git a/modules/auth/sso/group.go b/services/auth/group.go similarity index 89% rename from modules/auth/sso/group.go rename to services/auth/group.go index c1821528ecf3..cc09abfb10c3 100644 --- a/modules/auth/sso/group.go +++ b/services/auth/group.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package sso +package auth import ( "net/http" @@ -12,16 +12,16 @@ import ( // Ensure the struct implements the interface. var ( - _ SingleSignOn = &Group{} + _ Auth = &Group{} ) -// Group implements the SingleSignOn interface with serval SingleSignOn. +// Group implements the Auth interface with serval Auth. type Group struct { - methods []SingleSignOn + methods []Auth } // NewGroup creates a new auth group -func NewGroup(methods ...SingleSignOn) *Group { +func NewGroup(methods ...Auth) *Group { return &Group{ methods: methods, } diff --git a/modules/auth/sso/interface.go b/services/auth/interface.go similarity index 80% rename from modules/auth/sso/interface.go rename to services/auth/interface.go index 5531841f9c92..f77787040c39 100644 --- a/modules/auth/sso/interface.go +++ b/services/auth/interface.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package sso +package auth import ( "net/http" @@ -18,8 +18,8 @@ type DataStore middleware.DataStore // SessionStore represents a session store type SessionStore session.Store -// SingleSignOn represents a SSO authentication method (plugin) for HTTP requests. -type SingleSignOn interface { +// Auth represents an authentication method (plugin) for HTTP requests. +type Auth interface { Name() string // Init should be called exactly once before using any of the other methods, @@ -30,10 +30,10 @@ type SingleSignOn interface { // give chance to the plugin to free any allocated resources Free() error - // IsEnabled checks if the current SSO method has been enabled in settings. + // IsEnabled checks if the current auth method has been enabled in settings. IsEnabled() bool - // VerifyAuthData tries to verify the SSO authentication data contained in the request. + // VerifyAuthData tries to verify the authentication data contained in the request. // If verification is successful returns either an existing user object (with id > 0) // or a new user object (with id = 0) populated with the information that was found // in the authentication data (username or email). diff --git a/modules/auth/sso/oauth2.go b/services/auth/oauth2.go similarity index 97% rename from modules/auth/sso/oauth2.go rename to services/auth/oauth2.go index bd280bd1b410..a7590360201a 100644 --- a/modules/auth/sso/oauth2.go +++ b/services/auth/oauth2.go @@ -3,7 +3,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package sso +package auth import ( "net/http" @@ -18,7 +18,7 @@ import ( // Ensure the struct implements the interface. var ( - _ SingleSignOn = &OAuth2{} + _ Auth = &OAuth2{} ) // CheckOAuthAccessToken returns uid of user from oauth token @@ -45,7 +45,7 @@ func CheckOAuthAccessToken(accessToken string) int64 { return grant.UserID } -// OAuth2 implements the SingleSignOn interface and authenticates requests +// OAuth2 implements the Auth interface and authenticates requests // (API requests only) by looking for an OAuth token in query parameters or the // "Authorization" header. type OAuth2 struct { diff --git a/modules/auth/sso/reverseproxy.go b/services/auth/reverseproxy.go similarity index 97% rename from modules/auth/sso/reverseproxy.go rename to services/auth/reverseproxy.go index 622cf0073f0a..1386cb5f3049 100644 --- a/modules/auth/sso/reverseproxy.go +++ b/services/auth/reverseproxy.go @@ -3,7 +3,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package sso +package auth import ( "net/http" @@ -19,10 +19,10 @@ import ( // Ensure the struct implements the interface. var ( - _ SingleSignOn = &ReverseProxy{} + _ Auth = &ReverseProxy{} ) -// ReverseProxy implements the SingleSignOn interface, but actually relies on +// ReverseProxy implements the Auth interface, but actually relies on // a reverse proxy for authentication of users. // On successful authentication the proxy is expected to populate the username in the // "setting.ReverseProxyAuthUser" header. Optionally it can also populate the email of the diff --git a/modules/auth/sso/session.go b/services/auth/session.go similarity index 97% rename from modules/auth/sso/session.go rename to services/auth/session.go index 2f5ed4e3dcad..f6c15e8a20c6 100644 --- a/modules/auth/sso/session.go +++ b/services/auth/session.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package sso +package auth import ( "net/http" @@ -12,7 +12,7 @@ import ( // Ensure the struct implements the interface. var ( - _ SingleSignOn = &Session{} + _ Auth = &Session{} ) // Session checks if there is a user uid stored in the session and returns the user diff --git a/modules/auth/sso/sspi_windows.go b/services/auth/sspi_windows.go similarity index 98% rename from modules/auth/sso/sspi_windows.go rename to services/auth/sspi_windows.go index fc4e4de812cc..4920f9bb5d81 100644 --- a/modules/auth/sso/sspi_windows.go +++ b/services/auth/sspi_windows.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package sso +package auth import ( "errors" @@ -32,10 +32,10 @@ var ( sspiAuth *websspi.Authenticator // Ensure the struct implements the interface. - _ SingleSignOn = &SSPI{} + _ Auth = &SSPI{} ) -// SSPI implements the SingleSignOn interface and authenticates requests +// SSPI implements the Auth interface and authenticates requests // via the built-in SSPI module in Windows for SPNEGO authentication. // On successful authentication returns a valid user object. // Returns nil if authentication fails. From ef4c9006dd7e49ec9952fb95d6936fd90cb2e3c2 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 8 Jun 2021 17:26:06 +0800 Subject: [PATCH 6/8] remove unused method of Auth interface --- modules/context/api.go | 5 +---- modules/context/context.go | 6 +----- services/auth/auth.go | 31 +++------------------------- services/auth/basic.go | 10 ++------- services/auth/group.go | 15 +++----------- services/auth/interface.go | 7 ++----- services/auth/oauth2.go | 10 ++------- services/auth/reverseproxy.go | 9 ++------- services/auth/session.go | 38 +++++++++++++++++++++++++++-------- 9 files changed, 46 insertions(+), 85 deletions(-) diff --git a/modules/context/api.go b/modules/context/api.go index dbfee57d1013..506824674522 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -220,11 +220,8 @@ func (ctx *APIContext) CheckForOTP() { // APIAuth converts auth.Auth as a middleware func APIAuth(authMethod auth.Auth) func(*APIContext) { return func(ctx *APIContext) { - if !authMethod.IsEnabled() { - return - } // Get user from session if logged in. - ctx.User = authMethod.VerifyAuthData(ctx.Req, ctx.Resp, ctx, ctx.Session) + ctx.User = authMethod.Verify(ctx.Req, ctx.Resp, ctx, ctx.Session) if ctx.User != nil { ctx.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == new(auth.Basic).Name() ctx.IsSigned = true diff --git a/modules/context/context.go b/modules/context/context.go index d2ee36660093..492b3f80ded6 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -608,11 +608,7 @@ func getCsrfOpts() CsrfOptions { // Auth converts auth.Auth as a middleware func Auth(authMethod auth.Auth) func(*Context) { return func(ctx *Context) { - if !authMethod.IsEnabled() { - return - } - - ctx.User = authMethod.VerifyAuthData(ctx.Req, ctx.Resp, ctx, ctx.Session) + ctx.User = authMethod.Verify(ctx.Req, ctx.Resp, ctx, ctx.Session) if ctx.User != nil { ctx.IsBasicAuth = ctx.Data["AuthedMethod"].(string) == new(auth.Basic).Name() ctx.IsSigned = true diff --git a/services/auth/auth.go b/services/auth/auth.go index 7a6cdb751b31..477159c2cc72 100644 --- a/services/auth/auth.go +++ b/services/auth/auth.go @@ -31,7 +31,6 @@ var authMethods = []Auth{ &OAuth2{}, &Basic{}, &Session{}, - &ReverseProxy{}, } // The purpose of the following three function variables is to let the linter know that @@ -53,6 +52,9 @@ func Register(method Auth) { // Init should be called exactly once when the application starts to allow plugins // to allocate necessary resources func Init() { + if setting.Service.EnableReverseProxyAuth { + Register(&ReverseProxy{}) + } for _, method := range Methods() { err := method.Init() if err != nil { @@ -72,33 +74,6 @@ func Free() { } } -// SessionUser returns the user object corresponding to the "uid" session variable. -func SessionUser(sess SessionStore) *models.User { - // Get user ID - uid := sess.Get("uid") - if uid == nil { - return nil - } - log.Trace("Session Authorization: Found user[%d]", uid) - - id, ok := uid.(int64) - if !ok { - return nil - } - - // Get user object - user, err := models.GetUserByID(id) - if err != nil { - if !models.IsErrUserNotExist(err) { - log.Error("GetUserById: %v", err) - } - return nil - } - - log.Trace("Session Authorization: Logged in user %-v", user) - return user -} - // isAttachmentDownload check if request is a file download (GET) with URL to an attachment func isAttachmentDownload(req *http.Request) bool { return strings.HasPrefix(req.URL.Path, "/attachments/") && req.Method == "GET" diff --git a/services/auth/basic.go b/services/auth/basic.go index acbeff43f092..0bce4f1d067a 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -43,17 +43,11 @@ func (b *Basic) Free() error { return nil } -// IsEnabled returns true as this plugin is enabled by default and its not possible to disable -// it from settings. -func (b *Basic) IsEnabled() bool { - return true -} - -// VerifyAuthData extracts and validates Basic data (username and password/token) from the +// Verify extracts and validates Basic data (username and password/token) from the // "Authorization" header of the request and returns the corresponding user object for that // name/token on successful validation. // Returns nil if header is empty or validation fails. -func (b *Basic) VerifyAuthData(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { +func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { // Basic authentication should only fire on API, Download or on Git or LFSPaths if !middleware.IsAPIPath(req) && !isAttachmentDownload(req) && !isGitRawOrLFSPath(req) { return nil diff --git a/services/auth/group.go b/services/auth/group.go index cc09abfb10c3..b61949de7dea 100644 --- a/services/auth/group.go +++ b/services/auth/group.go @@ -52,24 +52,15 @@ func (b *Group) Free() error { return nil } -// IsEnabled returns true as this plugin is enabled by default and its not possible to disable -// it from settings. -func (b *Group) IsEnabled() bool { - return true -} - -// VerifyAuthData extracts and validates -func (b *Group) VerifyAuthData(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { +// Verify extracts and validates +func (b *Group) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { if !models.HasEngine { return nil } // Try to sign in with each of the enabled plugins for _, ssoMethod := range b.methods { - if !ssoMethod.IsEnabled() { - continue - } - user := ssoMethod.VerifyAuthData(req, w, store, sess) + user := ssoMethod.Verify(req, w, store, sess) if user != nil { if store.GetData()["AuthedMethod"] == nil { store.GetData()["AuthedMethod"] = ssoMethod.Name() diff --git a/services/auth/interface.go b/services/auth/interface.go index f77787040c39..a305bdfc226c 100644 --- a/services/auth/interface.go +++ b/services/auth/interface.go @@ -30,13 +30,10 @@ type Auth interface { // give chance to the plugin to free any allocated resources Free() error - // IsEnabled checks if the current auth method has been enabled in settings. - IsEnabled() bool - - // VerifyAuthData tries to verify the authentication data contained in the request. + // Verify tries to verify the authentication data contained in the request. // If verification is successful returns either an existing user object (with id > 0) // or a new user object (with id = 0) populated with the information that was found // in the authentication data (username or email). // Returns nil if verification fails. - VerifyAuthData(http *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User + Verify(http *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User } diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index a7590360201a..c6b98c144f0e 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -112,17 +112,11 @@ func (o *OAuth2) userIDFromToken(req *http.Request, store DataStore) int64 { return t.UID } -// IsEnabled returns true as this plugin is enabled by default and its not possible -// to disable it from settings. -func (o *OAuth2) IsEnabled() bool { - return true -} - -// VerifyAuthData extracts the user ID from the OAuth token in the query parameters +// Verify extracts the user ID from the OAuth token in the query parameters // or the "Authorization" header and returns the corresponding user object for that ID. // If verification is successful returns an existing user object. // Returns nil if verification fails. -func (o *OAuth2) VerifyAuthData(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { +func (o *OAuth2) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { if !models.HasEngine { return nil } diff --git a/services/auth/reverseproxy.go b/services/auth/reverseproxy.go index 1386cb5f3049..f958d28c9a66 100644 --- a/services/auth/reverseproxy.go +++ b/services/auth/reverseproxy.go @@ -54,19 +54,14 @@ func (r *ReverseProxy) Free() error { return nil } -// IsEnabled checks if EnableReverseProxyAuth setting is true -func (r *ReverseProxy) IsEnabled() bool { - return setting.Service.EnableReverseProxyAuth -} - -// VerifyAuthData extracts the username from the "setting.ReverseProxyAuthUser" header +// Verify extracts the username from the "setting.ReverseProxyAuthUser" header // of the request and returns the corresponding user object for that name. // Verification of header data is not performed as it should have already been done by // the revese proxy. // If a username is available in the "setting.ReverseProxyAuthUser" header an existing // user object is returned (populated with username or email found in header). // Returns nil if header is empty. -func (r *ReverseProxy) VerifyAuthData(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { +func (r *ReverseProxy) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { username := r.getUserName(req) if len(username) == 0 { return nil diff --git a/services/auth/session.go b/services/auth/session.go index f6c15e8a20c6..9f08f4336300 100644 --- a/services/auth/session.go +++ b/services/auth/session.go @@ -8,6 +8,7 @@ import ( "net/http" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/log" ) // Ensure the struct implements the interface. @@ -35,19 +36,40 @@ func (s *Session) Free() error { return nil } -// IsEnabled returns true as this plugin is enabled by default and its not possible to disable -// it from settings. -func (s *Session) IsEnabled() bool { - return true -} - -// VerifyAuthData checks if there is a user uid stored in the session and returns the user +// Verify checks if there is a user uid stored in the session and returns the user // object for that uid. // Returns nil if there is no user uid stored in the session. -func (s *Session) VerifyAuthData(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { +func (s *Session) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { user := SessionUser(sess) if user != nil { return user } return nil } + +// SessionUser returns the user object corresponding to the "uid" session variable. +func SessionUser(sess SessionStore) *models.User { + // Get user ID + uid := sess.Get("uid") + if uid == nil { + return nil + } + log.Trace("Session Authorization: Found user[%d]", uid) + + id, ok := uid.(int64) + if !ok { + return nil + } + + // Get user object + user, err := models.GetUserByID(id) + if err != nil { + if !models.IsErrUserNotExist(err) { + log.Error("GetUserById: %v", err) + } + return nil + } + + log.Trace("Session Authorization: Logged in user %-v", user) + return user +} From a79e7f2bb3b87885c9506fc6f031b1d7db9961af Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 8 Jun 2021 21:15:43 +0800 Subject: [PATCH 7/8] Fix lint for windows --- services/auth/auth.go | 1 + services/auth/placeholder.go | 9 +++++++++ services/auth/sspi_windows.go | 21 +++++++++------------ 3 files changed, 19 insertions(+), 12 deletions(-) create mode 100644 services/auth/placeholder.go diff --git a/services/auth/auth.go b/services/auth/auth.go index 477159c2cc72..5492a8b74ede 100644 --- a/services/auth/auth.go +++ b/services/auth/auth.go @@ -55,6 +55,7 @@ func Init() { if setting.Service.EnableReverseProxyAuth { Register(&ReverseProxy{}) } + specialInit() for _, method := range Methods() { err := method.Init() if err != nil { diff --git a/services/auth/placeholder.go b/services/auth/placeholder.go new file mode 100644 index 000000000000..50e3061885f8 --- /dev/null +++ b/services/auth/placeholder.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +// +build !windows + +package auth + +func specialInit() {} diff --git a/services/auth/sspi_windows.go b/services/auth/sspi_windows.go index 4920f9bb5d81..018221b999c3 100644 --- a/services/auth/sspi_windows.go +++ b/services/auth/sspi_windows.go @@ -32,10 +32,10 @@ var ( sspiAuth *websspi.Authenticator // Ensure the struct implements the interface. - _ Auth = &SSPI{} + _ SingleSignOn = &SSPI{} ) -// SSPI implements the Auth interface and authenticates requests +// SSPI implements the SingleSignOn interface and authenticates requests // via the built-in SSPI module in Windows for SPNEGO authentication. // On successful authentication returns a valid user object. // Returns nil if authentication fails. @@ -72,16 +72,11 @@ func (s *SSPI) Free() error { return sspiAuth.Free() } -// IsEnabled checks if there is an active SSPI authentication source -func (s *SSPI) IsEnabled() bool { - return models.IsSSPIEnabled() -} - -// VerifyAuthData uses SSPI (Windows implementation of SPNEGO) to authenticate the request. +// Verify uses SSPI (Windows implementation of SPNEGO) to authenticate the request. // If authentication is successful, returs the corresponding user object. // If negotiation should continue or authentication fails, immediately returns a 401 HTTP // response code, as required by the SPNEGO protocol. -func (s *SSPI) VerifyAuthData(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { +func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { if !s.shouldAuthenticate(req) { return nil } @@ -240,10 +235,12 @@ func sanitizeUsername(username string, cfg *models.SSPIConfig) string { return username } -// init registers the SSPI auth method as the last method in the list. +// specialInit registers the SSPI auth method as the last method in the list. // The SSPI plugin is expected to be executed last, as it returns 401 status code if negotiation // fails (or if negotiation should continue), which would prevent other authentication methods // to execute at all. -func init() { - Register(&SSPI{}) +func specialInit() { + if models.IsSSPIEnabled() { + Register(&SSPI{}) + } } From 660b6e720b1077e2c1116dcbf604140b54cc1199 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 9 Jun 2021 09:15:49 +0800 Subject: [PATCH 8/8] Fix lint --- services/auth/sspi_windows.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/auth/sspi_windows.go b/services/auth/sspi_windows.go index 018221b999c3..d1289a76174b 100644 --- a/services/auth/sspi_windows.go +++ b/services/auth/sspi_windows.go @@ -32,7 +32,7 @@ var ( sspiAuth *websspi.Authenticator // Ensure the struct implements the interface. - _ SingleSignOn = &SSPI{} + _ Auth = &SSPI{} ) // SSPI implements the SingleSignOn interface and authenticates requests