forked from
tangled.org/core
Monorepo for Tangled — https://tangled.org
1package oauth
2
3import (
4 "encoding/json"
5 "log"
6 "net/http"
7
8 "github.com/go-chi/chi/v5"
9 "github.com/lestrrat-go/jwx/v2/jwk"
10)
11
12func (o *OAuth) Router() http.Handler {
13 r := chi.NewRouter()
14
15 r.Get("/oauth/client-metadata.json", o.clientMetadata)
16 r.Get("/oauth/jwks.json", o.jwks)
17 r.Get("/oauth/callback", o.callback)
18 return r
19}
20
21func (o *OAuth) clientMetadata(w http.ResponseWriter, r *http.Request) {
22 doc := o.ClientApp.Config.ClientMetadata()
23 doc.JWKSURI = &o.JwksUri
24
25 w.Header().Set("Content-Type", "application/json")
26 if err := json.NewEncoder(w).Encode(doc); err != nil {
27 http.Error(w, err.Error(), http.StatusInternalServerError)
28 return
29 }
30}
31
32func (o *OAuth) jwks(w http.ResponseWriter, r *http.Request) {
33 jwks := o.Config.OAuth.Jwks
34 pubKey, err := pubKeyFromJwk(jwks)
35 if err != nil {
36 log.Printf("error parsing public key: %v", err)
37 http.Error(w, err.Error(), http.StatusInternalServerError)
38 return
39 }
40
41 response := map[string]any{
42 "keys": []jwk.Key{pubKey},
43 }
44
45 w.Header().Set("Content-Type", "application/json")
46 w.WriteHeader(http.StatusOK)
47 json.NewEncoder(w).Encode(response)
48}
49
50func (o *OAuth) callback(w http.ResponseWriter, r *http.Request) {
51 ctx := r.Context()
52
53 sessData, err := o.ClientApp.ProcessCallback(ctx, r.URL.Query())
54 if err != nil {
55 http.Error(w, err.Error(), http.StatusInternalServerError)
56 return
57 }
58
59 if err := o.SaveSession(w, r, sessData); err != nil {
60 http.Error(w, err.Error(), http.StatusInternalServerError)
61 return
62 }
63
64 http.Redirect(w, r, "/", http.StatusFound)
65}