oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "crypto/sha256"
5 "net/http"
6 "sync"
7 "time"
8
9 "amadan.net/oficina/home/dashboard"
10 "amadan.net/rastrillo/rastrillo/sessions"
11)
12
13const dashboardCookie = "__Host-oficina-dashboard"
14
15type dashboardPending struct {
16 Subject, Team, Session string
17 Expires time.Time
18 Tokens map[string]string
19}
20type dashboardResult struct {
21 Source dashboardSource
22 Response dashboard.Response
23 Status string
24}
25type dashboardCache struct {
26 Results []dashboardResult
27 At time.Time
28}
29type dashboardState struct {
30 mu sync.Mutex
31 pending map[string]dashboardPending
32 cache map[string]dashboardCache
33 slots chan struct{}
34 client *http.Client
35}
36
37func newDashboardState() *dashboardState {
38 return &dashboardState{pending: map[string]dashboardPending{}, cache: map[string]dashboardCache{}, slots: make(chan struct{}, 16), client: &http.Client{Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
39}
40
41// Sweep every access; hard expiry is independent of whether a source recovers.
42func (d *dashboardState) sweep(now time.Time) {
43 for k, v := range d.pending {
44 if !now.Before(v.Expires) {
45 delete(d.pending, k)
46 }
47 }
48 for k, v := range d.cache {
49 if now.Sub(v.At) >= 120*time.Second {
50 delete(d.cache, k)
51 }
52 }
53}
54func (a *App) dashboardSession(r *http.Request) (string, string, bool) {
55 s, ok := sessions.Current(r)
56 if !ok || !ValidPersonRef(s.Subject) {
57 return "", "", false
58 }
59 count := 0
60 value := ""
61 for _, c := range r.Cookies() {
62 if c.Name == a.sessions.CookieName() {
63 count++
64 value = c.Value
65 }
66 }
67 if count != 1 || value == "" {
68 return "", "", false
69 }
70 h := sha256.Sum256([]byte(value))
71 return s.Subject, string(h[:]), true
72}
73func dashboardCacheKey(subject, session, team string) string {
74 return subject + "\x00" + session + "\x00" + team
75}
76func dashboardNonce(r *http.Request) string {
77 count := 0
78 v := ""
79 for _, c := range r.Cookies() {
80 if c.Name == dashboardCookie {
81 count++
82 v = c.Value
83 }
84 }
85 if count != 1 || !dashboard.ValidID(v) {
86 return ""
87 }
88 return v
89}
90