| 1 | package calendar |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | "time" |
| 7 | |
| 8 | access "amadan.net/oficina/agent-access.git" |
| 9 | "amadan.net/oficina/home/roster" |
| 10 | "amadan.net/oficina/home/teammode" |
| 11 | "gorm.io/gorm" |
| 12 | ) |
| 13 | |
| 14 | // Only the outer identity check may acquire standing. Writer and response |
| 15 | // checks use the original lease and never perform roster I/O under SQLite. |
| 16 | func (a *App) agentStanding(ctx context.Context, subject string, acquire bool) error { |
| 17 | if a.cfg.Team == nil { |
| 18 | return nil |
| 19 | } |
| 20 | s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState) |
| 21 | if !ok || s == nil || a.team == nil || a.team.Bindings().Team != a.agentTeam { |
| 22 | return access.Fail("unavailable", "Team authority is unavailable.") |
| 23 | } |
| 24 | if s.standing == nil && acquire { |
| 25 | s.standing = a.team.Access(ctx, subject) |
| 26 | } |
| 27 | if s.standing == nil || s.standing.Subject() != subject { |
| 28 | return access.Fail("unavailable", "Team authority is unavailable.") |
| 29 | } |
| 30 | switch s.standing.State() { |
| 31 | case roster.Member: |
| 32 | return nil |
| 33 | case roster.NotMember: |
| 34 | return access.Fail("forbidden", "This account is not a team member.") |
| 35 | default: |
| 36 | return access.Fail("unavailable", "Team membership cannot be verified now.") |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | func (a *App) agentContext(ctx context.Context) context.Context { |
| 41 | if a.cfg.Team != nil { |
| 42 | if s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok { |
| 43 | return teammode.WithAccess(ctx, s.standing) |
| 44 | } |
| 45 | } |
| 46 | return ctx |
| 47 | } |
| 48 | |
| 49 | func (a *App) agentStore(tx *gorm.DB) *Store { |
| 50 | s := NewStore(tx, a.store.seal, a.logger) |
| 51 | s.team = a.store.team |
| 52 | return s |
| 53 | } |
| 54 | |
| 55 | type agentLeaseWriter struct { |
| 56 | http.ResponseWriter |
| 57 | state *agentResponseState |
| 58 | team bool |
| 59 | } |
| 60 | |
| 61 | func (w *agentLeaseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| 62 | func (w *agentLeaseWriter) SetWriteDeadline(deadline time.Time) error { |
| 63 | if w.team && !deadline.IsZero() { |
| 64 | if w.state == nil || w.state.standing == nil { |
| 65 | return access.Fail("unavailable", "Team authority is unavailable.") |
| 66 | } |
| 67 | now := time.Now() |
| 68 | remaining := w.state.standing.Remaining() |
| 69 | if remaining <= 0 { |
| 70 | return access.Fail("unavailable", "Team membership cannot be verified now.") |
| 71 | } |
| 72 | if lease := now.Add(remaining); lease.Before(deadline) { |
| 73 | deadline = lease |
| 74 | } |
| 75 | } |
| 76 | return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(deadline) |
| 77 | } |
| 78 | |