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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package auth
  4. import (
  5. "context"
  6. "net/http"
  7. "reflect"
  8. "strings"
  9. user_model "code.gitea.io/gitea/models/user"
  10. )
  11. // Ensure the struct implements the interface.
  12. var (
  13. _ Method = &Group{}
  14. _ Initializable = &Group{}
  15. _ Freeable = &Group{}
  16. )
  17. // Group implements the Auth interface with serval Auth.
  18. type Group struct {
  19. methods []Method
  20. }
  21. // NewGroup creates a new auth group
  22. func NewGroup(methods ...Method) *Group {
  23. return &Group{
  24. methods: methods,
  25. }
  26. }
  27. // Add adds a new method to group
  28. func (b *Group) Add(method Method) {
  29. b.methods = append(b.methods, method)
  30. }
  31. // Name returns group's methods name
  32. func (b *Group) Name() string {
  33. names := make([]string, 0, len(b.methods))
  34. for _, m := range b.methods {
  35. if n, ok := m.(Named); ok {
  36. names = append(names, n.Name())
  37. } else {
  38. names = append(names, reflect.TypeOf(m).Elem().Name())
  39. }
  40. }
  41. return strings.Join(names, ",")
  42. }
  43. // Init does nothing as the Basic implementation does not need to allocate any resources
  44. func (b *Group) Init(ctx context.Context) error {
  45. for _, method := range b.methods {
  46. initializable, ok := method.(Initializable)
  47. if !ok {
  48. continue
  49. }
  50. if err := initializable.Init(ctx); err != nil {
  51. return err
  52. }
  53. }
  54. return nil
  55. }
  56. // Free does nothing as the Basic implementation does not have to release any resources
  57. func (b *Group) Free() error {
  58. for _, method := range b.methods {
  59. freeable, ok := method.(Freeable)
  60. if !ok {
  61. continue
  62. }
  63. if err := freeable.Free(); err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. }
  69. // Verify extracts and validates
  70. func (b *Group) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) {
  71. // Try to sign in with each of the enabled plugins
  72. for _, ssoMethod := range b.methods {
  73. user, err := ssoMethod.Verify(req, w, store, sess)
  74. if err != nil {
  75. return nil, err
  76. }
  77. if user != nil {
  78. if store.GetData()["AuthedMethod"] == nil {
  79. if named, ok := ssoMethod.(Named); ok {
  80. store.GetData()["AuthedMethod"] = named.Name()
  81. }
  82. }
  83. return user, nil
  84. }
  85. }
  86. return nil, nil
  87. }