BlueGit

timfa bluegit

Files

bluegit / internal / auth / auth.go

auth.go

auth.go 6.2 KiB Download Raw
1// Package auth praat met de gekozen identity provider.
2// Standaard is dat auth.timfalken.com (authorization-code-flow); optioneel
3// Microsoft Entra ID (OIDC). E-mail komt nooit in het BlueGit-usermodel.
4// Er is geen lokaal wachtwoord.
5package auth
6
7import (
8 "context"
9 "encoding/json"
10 "fmt"
11 "io"
12 "net/http"
13 "net/url"
14 "strings"
15 "time"
16)
17
18// Identity is het account dat een verbonden site mag zien.
19type Identity struct {
20 AuthID int64
21 Username string
22 AvatarURL string
23 IsAdmin bool
24 EmailVerified bool
25 AccessToken string
26 ExpiresIn int
27}
28
29// Provider is de auth-server, of een testvervanger.
30// nonce is verplicht voor OIDC (Entra); TimFalken en Dev negeren hem.
31type Provider interface {
32 AuthorizeURL(state, nonce, redirectURI string) string
33 Exchange(ctx context.Context, code, redirectURI, nonce string) (Identity, error)
34 Extend(ctx context.Context, accessToken string) (expiresIn int, err error)
35 Logout(ctx context.Context, accessToken string) error
36}
37
38// TimFalken is de client voor https://auth.timfalken.com.
39type TimFalken struct {
40 BaseURL string
41 ClientID string
42 Secret string
43 UserAgent string
44 HTTP *http.Client
45}
46
47// NewTimFalken maakt een client. baseURL is zonder slash aan het eind.
48func NewTimFalken(baseURL, clientID, secret, userAgent string) *TimFalken {
49 return &TimFalken{
50 BaseURL: strings.TrimRight(baseURL, "/"),
51 ClientID: clientID,
52 Secret: secret,
53 UserAgent: userAgent,
54 HTTP: &http.Client{Timeout: 15 * time.Second},
55 }
56}
57
58// AuthorizeURL stuurt de browser naar de toestemmingspagina.
59func (t *TimFalken) AuthorizeURL(state, nonce, redirectURI string) string {
60 q := url.Values{}
61 q.Set("client_id", t.ClientID)
62 q.Set("redirect_uri", redirectURI)
63 q.Set("response_type", "code")
64 q.Set("state", state)
65 _ = nonce
66 return t.BaseURL + "/oauth/authorize?" + q.Encode()
67}
68
69// Exchange wisselt de eenmalige code om voor een bearer-token.
70func (t *TimFalken) Exchange(ctx context.Context, code, redirectURI, nonce string) (Identity, error) {
71 _ = nonce
72 form := url.Values{}
73 form.Set("grant_type", "authorization_code")
74 form.Set("code", code)
75 form.Set("redirect_uri", redirectURI)
76 form.Set("client_id", t.ClientID)
77 form.Set("client_secret", t.Secret)
78 req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.BaseURL+"/oauth/token", strings.NewReader(form.Encode()))
79 if err != nil {
80 return Identity{}, err
81 }
82 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
83 req.Header.Set("Accept", "application/json")
84 req.Header.Set("User-Agent", t.UserAgent)
85 var body struct {
86 AccessToken string `json:"access_token"`
87 TokenType string `json:"token_type"`
88 ExpiresIn int `json:"expires_in"`
89 Error string `json:"error"`
90 User struct {
91 ID int64 `json:"id"`
92 Username string `json:"username"`
93 AvatarURL string `json:"avatar_url"`
94 } `json:"user"`
95 }
96 if err := t.do(req, &body); err != nil {
97 return Identity{}, err
98 }
99 if body.Error != "" || body.AccessToken == "" || body.User.ID == 0 {
100 msg := body.Error
101 if msg == "" {
102 msg = "lege tokenrespons"
103 }
104 return Identity{}, fmt.Errorf("auth: %s", msg)
105 }
106 id := Identity{
107 AuthID: body.User.ID,
108 Username: strings.ToLower(body.User.Username),
109 AvatarURL: body.User.AvatarURL,
110 AccessToken: body.AccessToken,
111 ExpiresIn: body.ExpiresIn,
112 }
113 // /api/me vult is_admin en email_verified aan. Dat is admin van de
114 // auth-server, niet van BlueGit.
115 me, err := t.me(ctx, body.AccessToken)
116 if err != nil {
117 return id, nil
118 }
119 id.IsAdmin = me.IsAdmin
120 id.EmailVerified = me.EmailVerified
121 if me.Username != "" {
122 id.Username = strings.ToLower(me.Username)
123 }
124 if me.AvatarURL != "" {
125 id.AvatarURL = me.AvatarURL
126 }
127 return id, nil
128}
129
130type meUser struct {
131 ID int64 `json:"id"`
132 Username string `json:"username"`
133 IsAdmin bool `json:"is_admin"`
134 EmailVerified bool `json:"email_verified"`
135 AvatarURL string `json:"avatar_url"`
136}
137
138func (t *TimFalken) me(ctx context.Context, token string) (meUser, error) {
139 req, err := http.NewRequestWithContext(ctx, http.MethodGet, t.BaseURL+"/api/me", nil)
140 if err != nil {
141 return meUser{}, err
142 }
143 t.bearer(req, token)
144 var body struct {
145 User meUser `json:"user"`
146 Error string `json:"error"`
147 }
148 if err := t.do(req, &body); err != nil {
149 return meUser{}, err
150 }
151 if body.Error != "" {
152 return meUser{}, fmt.Errorf("auth: %s", body.Error)
153 }
154 return body.User, nil
155}
156
157// Extend schuift de sessie een volledige dag op.
158func (t *TimFalken) Extend(ctx context.Context, accessToken string) (int, error) {
159 req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.BaseURL+"/api/session/extend", nil)
160 if err != nil {
161 return 0, err
162 }
163 t.bearer(req, accessToken)
164 var body struct {
165 ExpiresIn int `json:"expires_in"`
166 Error string `json:"error"`
167 }
168 if err := t.do(req, &body); err != nil {
169 return 0, err
170 }
171 if body.Error != "" {
172 return 0, fmt.Errorf("auth: %s", body.Error)
173 }
174 if body.ExpiresIn <= 0 {
175 body.ExpiresIn = 86400
176 }
177 return body.ExpiresIn, nil
178}
179
180// Logout trekt het bearer-token in.
181func (t *TimFalken) Logout(ctx context.Context, accessToken string) error {
182 req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.BaseURL+"/api/logout", nil)
183 if err != nil {
184 return err
185 }
186 t.bearer(req, accessToken)
187 var body struct {
188 Error string `json:"error"`
189 }
190 if err := t.do(req, &body); err != nil {
191 return err
192 }
193 if body.Error != "" {
194 return fmt.Errorf("auth: %s", body.Error)
195 }
196 return nil
197}
198
199func (t *TimFalken) bearer(req *http.Request, token string) {
200 req.Header.Set("Authorization", "Bearer "+token)
201 req.Header.Set("Accept", "application/json")
202 req.Header.Set("User-Agent", t.UserAgent)
203}
204
205func (t *TimFalken) do(req *http.Request, dest any) error {
206 res, err := t.HTTP.Do(req)
207 if err != nil {
208 return fmt.Errorf("auth: %w", err)
209 }
210 defer res.Body.Close()
211 raw, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
212 if err != nil {
213 return err
214 }
215 if res.StatusCode >= 400 {
216 var env struct {
217 Error string `json:"error"`
218 }
219 _ = json.Unmarshal(raw, &env)
220 if env.Error == "" {
221 env.Error = res.Status
222 }
223 return fmt.Errorf("auth: %s", env.Error)
224 }
225 if dest == nil {
226 return nil
227 }
228 if err := json.Unmarshal(raw, dest); err != nil {
229 return fmt.Errorf("auth-antwoord: %w", err)
230 }
231 return nil
232}