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.

56 lines
1.6 KiB

  1. package types
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. )
  8. // AuthRealm represents a place where a user can authenticate themselves.
  9. // This may static (like github.com) or a specific domain (like matrix.org/jira)
  10. type AuthRealm interface {
  11. ID() string
  12. Type() string
  13. Init() error
  14. Register() error
  15. OnReceiveRedirect(w http.ResponseWriter, req *http.Request)
  16. AuthSession(id, userID, realmID string) AuthSession
  17. RequestAuthSession(userID string, config json.RawMessage) interface{}
  18. }
  19. var realmsByType = map[string]func(string, string) AuthRealm{}
  20. // RegisterAuthRealm registers a factory for creating AuthRealm instances.
  21. func RegisterAuthRealm(factory func(string, string) AuthRealm) {
  22. realmsByType[factory("", "").Type()] = factory
  23. }
  24. // CreateAuthRealm creates an AuthRealm of the given type and realm ID.
  25. // Returns an error if the realm couldn't be created or the JSON cannot be unmarshalled.
  26. func CreateAuthRealm(realmID, realmType string, realmJSON []byte) (AuthRealm, error) {
  27. f := realmsByType[realmType]
  28. if f == nil {
  29. return nil, errors.New("Unknown realm type: " + realmType)
  30. }
  31. base64RealmID := base64.RawURLEncoding.EncodeToString([]byte(realmID))
  32. redirectURL := baseURL + "realms/redirects/" + base64RealmID
  33. r := f(realmID, redirectURL)
  34. if err := json.Unmarshal(realmJSON, r); err != nil {
  35. return nil, err
  36. }
  37. if err := r.Init(); err != nil {
  38. return nil, err
  39. }
  40. return r, nil
  41. }
  42. // AuthSession represents a single authentication session between a user and
  43. // an auth realm.
  44. type AuthSession interface {
  45. ID() string
  46. UserID() string
  47. RealmID() string
  48. Authenticated() bool
  49. Info() interface{}
  50. }