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.

group.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package auth
  4. import (
  5. "net/http"
  6. "strings"
  7. user_model "code.gitea.io/gitea/models/user"
  8. )
  9. // Ensure the struct implements the interface.
  10. var (
  11. _ Method = &Group{}
  12. )
  13. // Group implements the Auth interface with serval Auth.
  14. type Group struct {
  15. methods []Method
  16. }
  17. // NewGroup creates a new auth group
  18. func NewGroup(methods ...Method) *Group {
  19. return &Group{
  20. methods: methods,
  21. }
  22. }
  23. // Add adds a new method to group
  24. func (b *Group) Add(method Method) {
  25. b.methods = append(b.methods, method)
  26. }
  27. // Name returns group's methods name
  28. func (b *Group) Name() string {
  29. names := make([]string, 0, len(b.methods))
  30. for _, m := range b.methods {
  31. names = append(names, m.Name())
  32. }
  33. return strings.Join(names, ",")
  34. }
  35. func (b *Group) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) {
  36. // Try to sign in with each of the enabled plugins
  37. var retErr error
  38. for _, m := range b.methods {
  39. user, err := m.Verify(req, w, store, sess)
  40. if err != nil {
  41. if retErr == nil {
  42. retErr = err
  43. }
  44. // Try other methods if this one failed.
  45. // Some methods may share the same protocol to detect if they are matched.
  46. // For example, OAuth2 and conan.Auth both read token from "Authorization: Bearer <token>" header,
  47. // If OAuth2 returns error, we should give conan.Auth a chance to try.
  48. continue
  49. }
  50. // If any method returns a user, we can stop trying.
  51. // Return the user and ignore any error returned by previous methods.
  52. if user != nil {
  53. if store.GetData()["AuthedMethod"] == nil {
  54. store.GetData()["AuthedMethod"] = m.Name()
  55. }
  56. return user, nil
  57. }
  58. }
  59. // If no method returns a user, return the error returned by the first method.
  60. return nil, retErr
  61. }