/
http.go
80 lines (65 loc) · 1.78 KB
/
http.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
package token
import (
"encoding/json"
"net/http"
"github.com/julienschmidt/httprouter"
)
func NewHTTPHandler(repository Repository) http.Handler {
h := httpHandler{
repository: repository,
}
r := httprouter.New()
r.POST("/v1/token/activation/:userId", h.handleCreateToken)
r.GET("/v1/token/:userId", h.handleValidateToken)
return r
}
type httpHandler struct {
repository Repository
}
// create a token for a given user
func (h *httpHandler) handleCreateToken(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
activationToken, err := generateActivationToken()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
userID := ps.ByName("userId")
if userID == "" {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
info := ActivationTokenInfo{
Token: activationToken,
UserID: userID,
}
if err := h.repository.insertActivationToken(r.Context(), &info); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(map[string]string{"token": activationToken}); err != nil {
panic(err)
}
}
// Return all the activation tokens that are listed under
// the same user id
func (h *httpHandler) handleValidateToken(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
activationToken := ps.ByName("token")
if activationToken == "" {
http.Error(w, "token required", http.StatusBadRequest)
return
}
userID, err := h.repository.getUserID(r.Context(), activationToken)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := json.NewEncoder(w).Encode(struct {
UserID string `json:"userId"`
}{
UserID: userID,
}); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}