repos / pico

pico services - prose.sh, pastes.sh, imgs.sh, feeds.sh, pgs.sh
git clone https://github.com/picosh/pico.git

commit
4fe315c
parent
f3ea164
author
Eric Bower
date
2024-02-03 17:01:42 +0000 UTC
feat(auth): privileged access based on `auth` feature flag
1 files changed,  +27, -0
M auth/auth.go
+27, -0
 1@@ -21,12 +21,28 @@ type Client struct {
 2 	Logger *zap.SugaredLogger
 3 }
 4 
 5+func (client *Client) hasPrivilegedAccess(apiToken string) bool {
 6+	user, err := client.Dbpool.FindUserForToken(apiToken)
 7+	if err != nil {
 8+		return false
 9+	}
10+	return client.Dbpool.HasFeatureForUser(user.ID, "auth")
11+}
12+
13 type ctxClient struct{}
14 
15 func getClient(r *http.Request) *Client {
16 	return r.Context().Value(ctxClient{}).(*Client)
17 }
18 
19+func getApiToken(r *http.Request) string {
20+	authHeader := r.Header.Get("authorization")
21+	if authHeader == "" {
22+		return ""
23+	}
24+	return strings.TrimPrefix(authHeader, "Bearer ")
25+}
26+
27 type oauth2Server struct {
28 	Issuer                                    string   `json:"issuer"`
29 	IntrospectionEndpoint                     string   `json:"introspection_endpoint"`
30@@ -228,7 +244,18 @@ func keyHandler(w http.ResponseWriter, r *http.Request) {
31 		return
32 	}
33 
34+	if !client.hasPrivilegedAccess(getApiToken(r)) {
35+		w.WriteHeader(http.StatusOK)
36+		return
37+	}
38+
39+	w.Header().Set("Content-Type", "application/json")
40 	w.WriteHeader(http.StatusOK)
41+	err = json.NewEncoder(w).Encode(user)
42+	if err != nil {
43+		client.Logger.Error(err)
44+		http.Error(w, err.Error(), http.StatusInternalServerError)
45+	}
46 }
47 
48 func createMainRoutes() []shared.Route {