-
Notifications
You must be signed in to change notification settings - Fork 11
/
tokens.go
61 lines (49 loc) · 1.24 KB
/
tokens.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
package api
import (
"net/http"
"github.com/common-fate/iamzero/api/io"
"github.com/common-fate/iamzero/pkg/tokens"
"github.com/go-chi/chi"
)
type ListTokensResponse struct {
Tokens []tokens.Token `json:"tokens"`
}
func (h *Handlers) ListTokens(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
tokens, err := h.TokenStore.List(ctx)
if err != nil {
io.RespondError(ctx, h.Log, w, err)
return
}
res := ListTokensResponse{
Tokens: tokens,
}
io.RespondJSON(ctx, h.Log, w, res, http.StatusOK)
}
func (h *Handlers) DeleteToken(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
tokenID := chi.URLParam(r, "tokenID")
err := h.TokenStore.Delete(ctx, tokenID)
if err != nil {
io.RespondError(ctx, h.Log, w, err)
return
}
w.WriteHeader(http.StatusOK)
}
type CreateTokenRequest struct {
Name string `json:"name"`
}
func (h *Handlers) CreateToken(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var rec CreateTokenRequest
if err := io.DecodeJSONBody(w, r, &rec); err != nil {
io.RespondError(ctx, h.Log, w, err)
return
}
token, err := h.TokenStore.Create(ctx, rec.Name)
if err != nil {
io.RespondError(ctx, h.Log, w, err)
return
}
io.RespondJSON(ctx, h.Log, w, token, http.StatusOK)
}