| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/setup" |
| 5 | "amadan.net/rastrillo/rastrillo/auth" |
| 6 | "amadan.net/rastrillo/rastrillo/db" |
| 7 | "amadan.net/rastrillo/rastrillo/mail" |
| 8 | "context" |
| 9 | "errors" |
| 10 | "gorm.io/gorm" |
| 11 | "log/slog" |
| 12 | "net/http" |
| 13 | ) |
| 14 | |
| 15 | func NewAuth(d *db.DB, cfg Config, mailer mail.Sender, store *Store, logger *slog.Logger) (*auth.Auth, error) { |
| 16 | if err := cfg.validate(); err != nil { |
| 17 | return nil, err |
| 18 | } |
| 19 | if d == nil || store == nil || store.db != d { |
| 20 | return nil, ErrUnavailable |
| 21 | } |
| 22 | store.invitationKey, store.personOrigin = cfg.InstanceKey, cfg.Origin |
| 23 | return setup.NewAuth(d, setup.AuthOptions{Origin: cfg.Origin, Key: cfg.InstanceKey, AllowLoggedMail: cfg.AllowLoggedMail, |
| 24 | //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| 25 | MissingMailer: errors.New(copyMissingMailer), UnconfiguredMailer: errors.New(copyUnconfiguredMailer), |
| 26 | Normalize: normalizeAddress, MayVerify: store.MayVerifyInvitation, Handler: store.sessionHandler(nil)}, mailer, logger) |
| 27 | } |
| 28 | func (s *Store) sessionHandler(authentication *auth.Auth) *setup.SessionHandler { |
| 29 | return &setup.SessionHandler{Auth: authentication, Member: s.Member, NotFound: ErrNotFound, |
| 30 | Remember: func(ctx context.Context, a Actor) error { |
| 31 | return s.write(ctx, func(tx *gorm.DB) error { return s.invitationsAt(tx).RememberSignedIn(a) }) |
| 32 | }, |
| 33 | Door: signinLook.Draw, |
| 34 | Failure: func(w http.ResponseWriter, r *http.Request, status int) { ErrorPage(w, r, status, "") }, |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // RequireMember lets composed routes use the same admission as the app. |
| 39 | func (a *application) RequireMember(next http.Handler) http.Handler { return a.requireMember(next) } |
| 40 | func (a *application) requireMember(next http.Handler) http.Handler { |
| 41 | if a == nil || a.auth == nil || a.store == nil { |
| 42 | return http.HandlerFunc(privateUnavailable) |
| 43 | } |
| 44 | h := a.store.sessionHandler(a.auth) |
| 45 | if a.home != nil { |
| 46 | h.Authenticate = a.home.Authenticate |
| 47 | } |
| 48 | return h.RequireMember(next) |
| 49 | } |
| 50 | func (a *application) rememberSignIn(next http.HandlerFunc) http.HandlerFunc { |
| 51 | handler := a.store.sessionHandler(a.auth).RememberSignIn(next) |
| 52 | if a.home != nil { |
| 53 | return a.home.LocalReauth(handler) |
| 54 | } |
| 55 | return handler |
| 56 | } |
| 57 | func privateUnavailable(w http.ResponseWriter, r *http.Request) { |
| 58 | w.Header().Set("Cache-Control", "no-store") |
| 59 | ErrorPage(w, r, http.StatusServiceUnavailable, "") |
| 60 | } |
| 61 | |