You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

init.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package oauth2
  5. import (
  6. "encoding/gob"
  7. "net/http"
  8. "sync"
  9. "code.gitea.io/gitea/models/auth"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "github.com/google/uuid"
  13. "github.com/gorilla/sessions"
  14. "github.com/markbates/goth/gothic"
  15. )
  16. var gothRWMutex = sync.RWMutex{}
  17. // UsersStoreKey is the key for the store
  18. const UsersStoreKey = "gitea-oauth2-sessions"
  19. // ProviderHeaderKey is the HTTP header key
  20. const ProviderHeaderKey = "gitea-oauth2-provider"
  21. // Init initializes the oauth source
  22. func Init() error {
  23. if err := InitSigningKey(); err != nil {
  24. return err
  25. }
  26. // Lock our mutex
  27. gothRWMutex.Lock()
  28. gob.Register(&sessions.Session{})
  29. gothic.Store = &SessionsStore{
  30. maxLength: int64(setting.OAuth2.MaxTokenLength),
  31. }
  32. gothic.SetState = func(req *http.Request) string {
  33. return uuid.New().String()
  34. }
  35. gothic.GetProviderName = func(req *http.Request) (string, error) {
  36. return req.Header.Get(ProviderHeaderKey), nil
  37. }
  38. // Unlock our mutex
  39. gothRWMutex.Unlock()
  40. return initOAuth2Sources()
  41. }
  42. // ResetOAuth2 clears existing OAuth2 providers and loads them from DB
  43. func ResetOAuth2() error {
  44. ClearProviders()
  45. return initOAuth2Sources()
  46. }
  47. // initOAuth2Sources is used to load and register all active OAuth2 providers
  48. func initOAuth2Sources() error {
  49. authSources, _ := auth.GetActiveOAuth2ProviderSources()
  50. for _, source := range authSources {
  51. oauth2Source, ok := source.Cfg.(*Source)
  52. if !ok {
  53. continue
  54. }
  55. err := oauth2Source.RegisterSource()
  56. if err != nil {
  57. log.Critical("Unable to register source: %s due to Error: %v.", source.Name, err)
  58. }
  59. }
  60. return nil
  61. }