Repository navigation
Expand file tree
/
Copy pathapi_users.go
More file actions
81 lines (69 loc) · 1.91 KB
/
Copy pathapi_users.go
File metadata and controls
81 lines (69 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"net/http"
"strings"
"time"
"ublproxy/internal/store"
)
func (a *apiHandler) routeUsers(w http.ResponseWriter, r *http.Request, path string, sess *store.Session) {
if !a.isAdmin(sess) {
writeJSON(w, http.StatusForbidden, errorResponse{"admin access required"})
return
}
if path == "/users" && r.Method == http.MethodGet {
a.handleListUsers(w)
return
}
// PATCH /users/:id
if r.Method == http.MethodPatch {
id := strings.TrimPrefix(path, "/users/")
if id != "" && id != path {
a.handlePatchUser(w, r, id, sess)
return
}
}
http.NotFound(w, r)
}
type userResponse struct {
ID string `json:"id"`
IsAdmin bool `json:"is_admin"`
CreatedAt string `json:"created_at"`
}
func (a *apiHandler) handleListUsers(w http.ResponseWriter) {
creds, err := a.store.ListCredentials()
if err != nil {
writeJSON(w, http.StatusInternalServerError, errorResponse{"failed to list users"})
return
}
users := make([]userResponse, len(creds))
for i, c := range creds {
users[i] = userResponse{
ID: c.ID,
IsAdmin: c.IsAdmin,
CreatedAt: c.CreatedAt.Format(time.RFC3339),
}
}
writeJSON(w, http.StatusOK, users)
}
func (a *apiHandler) handlePatchUser(w http.ResponseWriter, r *http.Request, id string, sess *store.Session) {
if id == sess.CredentialID {
writeJSON(w, http.StatusForbidden, errorResponse{"cannot modify own admin status"})
return
}
var body struct {
IsAdmin *bool `json:"is_admin"`
}
if err := readJSON(w, r, &body); err != nil {
writeJSON(w, http.StatusBadRequest, errorResponse{"invalid request body"})
return
}
if body.IsAdmin == nil {
writeJSON(w, http.StatusBadRequest, errorResponse{"is_admin is required"})
return
}
if err := a.store.SetAdmin(id, *body.IsAdmin); err != nil {
writeJSON(w, http.StatusNotFound, errorResponse{"user not found"})
return
}
writeJSON(w, http.StatusOK, map[string]bool{"is_admin": *body.IsAdmin})
}