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.

58 lines
1.7 KiB

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