-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
180 lines (147 loc) · 4.16 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package user
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi"
"github.com/pkg/errors"
"github.com/dzeban/conduit/app"
"github.com/dzeban/conduit/jwt"
"github.com/dzeban/conduit/transport"
)
type Server struct {
router *chi.Mux
service *Service
secret []byte
}
func NewHTTP(store Store, secret []byte) (*Server, error) {
s := &Server{
router: chi.NewRouter(),
service: NewService(store),
secret: secret,
}
// Unauthenticated endpoints
s.router.Post("/", transport.WithError(s.HandleUserRegister))
s.router.Post("/login", transport.WithError(s.HandleUserLogin))
// Endpoints protected by JWT auth
s.router.Group(func(r chi.Router) {
r.Use(jwt.Auth(s.secret, jwt.AuthTypeRequired))
r.Get("/", transport.WithError(s.HandleUserGet))
r.Put("/", transport.WithError(s.HandleUserUpdate))
})
return s, nil
}
// ServeHTTP implements http.handler interface and uses router ServeHTTP method
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
// Response represent a json structure used
// in user serice responses.
type Response struct {
User app.User `json:"user"`
}
func (s *Server) HandleUserLogin(w http.ResponseWriter, r *http.Request) error {
// Decode user request from JSON body
decoder := json.NewDecoder(r.Body)
var req LoginRequest
err := decoder.Decode(&req)
if err != nil {
return app.ServiceError(errorInvalidRequest)
}
// Perform login in service
user, err := s.service.Login(&req)
if err != nil {
return err
}
// Generate JWT
token, err := jwt.New(user, s.secret)
if err != nil {
return app.InternalError(errors.Wrap(err, "jwt.New"))
}
// Prepare and send reply with user data, including token
user.Token = token
jsonUser, err := json.Marshal(Response{User: *user})
if err != nil {
return app.InternalError(errors.Wrap(err, "json.Marshal"))
}
w.Write(jsonUser)
return nil
}
func (s *Server) HandleUserRegister(w http.ResponseWriter, r *http.Request) error {
// Decode user request from JSON body
decoder := json.NewDecoder(r.Body)
var req RegisterRequest
err := decoder.Decode(&req)
if err != nil {
return app.ServiceError(errorInvalidRequest)
}
// Perform register in service
user, err := s.service.Register(&req)
if err != nil {
return err
}
// Generate JWT
token, err := jwt.New(user, s.secret)
if err != nil {
return app.InternalError(errors.Wrap(err, "jwt.New"))
}
// Prepare and send reply with user data, including token
user.Token = token
jsonUser, err := json.Marshal(Response{User: *user})
if err != nil {
return app.InternalError(errors.Wrap(err, "json.Marshal"))
}
w.WriteHeader(http.StatusCreated)
w.Write(jsonUser)
return nil
}
// HandleUserGet gets the currently logged-in user. Requires authentication.
func (s *Server) HandleUserGet(w http.ResponseWriter, r *http.Request) error {
currentUser, ok := app.UserFromContext(r.Context())
if !ok {
return app.AuthError(app.ErrorUserNotInContext)
}
u, err := s.service.Get(currentUser.Email)
if err != nil {
return err
}
jsonUser, err := json.Marshal(Response{User: *u})
if err != nil {
return app.InternalError(errors.Wrap(err, "json.Marshal"))
}
w.Write(jsonUser)
return nil
}
// HandleUserUpdate changes currently logged-in user. Requires authentication.
func (s *Server) HandleUserUpdate(w http.ResponseWriter, r *http.Request) error {
currentUser, ok := app.UserFromContext(r.Context())
if !ok {
return app.AuthError(app.ErrorUserNotInContext)
}
// Decode user request from JSON body
decoder := json.NewDecoder(r.Body)
var req UpdateRequest
err := decoder.Decode(&req)
if err != nil {
return app.ServiceError(errorInvalidRequest)
}
// Check that user updates itself
if req.User.Email != "" && req.User.Email != currentUser.Email {
return app.AuthError(errorUserUpdateForbidden)
}
u, err := s.service.Update(currentUser.Id, &req)
if err != nil {
return err
}
// Regenerate JWT
token, err := jwt.New(u, s.secret)
if err != nil {
return app.InternalError(errors.Wrap(err, "jwt.New"))
}
u.Token = token
jsonUser, err := json.Marshal(Response{User: *u})
if err != nil {
return app.InternalError(errors.Wrap(err, "json.Marshal"))
}
w.Write(jsonUser)
return nil
}