BlueGit

timfa bluegit

Files

bluegit / internal / auth / auth.go

auth.go

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