-
Notifications
You must be signed in to change notification settings - Fork 641
/
userparam.go
83 lines (73 loc) · 2.33 KB
/
userparam.go
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
82
83
package httpmw
import (
"context"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/httpapi"
)
type userParamContextKey struct{}
const (
// userErrorMessage is a constant so that no information about the state
// of the queried user can be gained. We return the same error if the user
// does not exist, or if the input is just garbage.
userErrorMessage = "\"user\" must be an existing uuid or username."
)
// UserParam returns the user from the ExtractUserParam handler.
func UserParam(r *http.Request) database.User {
user, ok := r.Context().Value(userParamContextKey{}).(database.User)
if !ok {
panic("developer error: user parameter middleware not provided")
}
return user
}
// ExtractUserParam extracts a user from an ID/username in the {user} URL parameter.
func ExtractUserParam(db database.Store) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
var user database.User
var err error
// userQuery is either a uuid, a username, or 'me'
userQuery := chi.URLParam(r, "user")
if userQuery == "" {
httpapi.Write(rw, http.StatusBadRequest, httpapi.Response{
Message: "\"user\" must be provided.",
})
return
}
if userQuery == "me" {
user, err = db.GetUserByID(r.Context(), APIKey(r).UserID)
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: "Internal error fetching user.",
Detail: err.Error(),
})
return
}
} else if userID, err := uuid.Parse(userQuery); err == nil {
// If the userQuery is a valid uuid
user, err = db.GetUserByID(r.Context(), userID)
if err != nil {
httpapi.Write(rw, http.StatusBadRequest, httpapi.Response{
Message: userErrorMessage,
})
return
}
} else {
// Try as a username last
user, err = db.GetUserByEmailOrUsername(r.Context(), database.GetUserByEmailOrUsernameParams{
Username: userQuery,
})
if err != nil {
httpapi.Write(rw, http.StatusBadRequest, httpapi.Response{
Message: userErrorMessage,
})
return
}
}
ctx := context.WithValue(r.Context(), userParamContextKey{}, user)
next.ServeHTTP(rw, r.WithContext(ctx))
})
}
}