-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
316 lines (260 loc) · 6.96 KB
/
handler.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package users
import (
"context"
"database/sql"
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
"github.com/darkjedidj/cinema-service/internal"
repo "github.com/darkjedidj/cinema-service/internal/repository/users"
user "github.com/darkjedidj/cinema-service/internal/service/user"
e "github.com/darkjedidj/cinema-service/package"
tkn "github.com/darkjedidj/cinema-service/package/jwt"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
)
type Handler struct {
s user.Service // Allows use service features
log *zap.Logger
}
func Init(db *sql.DB, l *zap.Logger) *Handler {
service := user.Init(db, l)
return &Handler{
s: *service,
log: l,
}
}
// CheckPrivileges of user
func (h *Handler) CheckPrivileges(route string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("Authorization")
if len(header) == 0 {
w.WriteHeader(http.StatusUnauthorized)
_, err := w.Write([]byte("Missing Authorization Header"))
if err != nil {
h.log.Info("Failed to write ticket response.",
zap.Error(err),
)
w.WriteHeader(http.StatusInternalServerError)
return
}
return
}
header = strings.Replace(header, "Bearer ", "", 1)
claims, err := tkn.VerifyToken(header)
if err != nil {
h.log.Info("Failed to verify token.",
zap.Error(err),
)
}
id := claims.(jwt.MapClaims)["ID"].(float64)
privileges, err := h.s.RetrievePrivileges(int64(id))
if err != nil {
h.log.Info("Failed to get privileges.",
zap.Error(err),
)
}
for _, s := range privileges {
if s == route {
next(w, r)
}
}
w.WriteHeader(http.StatusUnauthorized)
}
}
// CheckTicket to download for user
func (h *Handler) CheckTicket(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
ticket, err := strconv.Atoi(vars["id"])
if err != nil {
h.log.Info("Failed to parse ticket id.",
zap.Error(err),
)
w.WriteHeader(http.StatusBadRequest)
return
}
header := r.Header.Get("Authorization")
if len(header) == 0 {
w.WriteHeader(http.StatusUnauthorized)
_, err := w.Write([]byte("Missing Authorization Header"))
if err != nil {
h.log.Info("Failed to write ticket response.",
zap.Error(err),
)
w.WriteHeader(http.StatusInternalServerError)
return
}
return
}
header = strings.Replace(header, "Bearer ", "", 1)
claims, err := tkn.VerifyToken(header)
if err != nil {
h.log.Info("Failed to verify token.",
zap.Error(err),
)
}
id := claims.(jwt.MapClaims)["ID"].(float64)
privileges, err := h.s.RetrieveTickets(int64(ticket), int64(id))
if err != nil {
h.log.Info("Failed to get privileges.",
zap.Error(err),
)
}
if privileges {
next(w, r)
}
w.WriteHeader(http.StatusUnauthorized)
}
}
// Signup
// Signup godoc
// @Summary Signup
// @Description Signup
// @Tags Users
// @Param Body body repo.Resource true "Email and password"
// @Accept json
// @Produce json
// @Success 201
// @Failure 400
// @Failure 422
// @Failure 500
// @Router /signup [post]
func (h *Handler) Signup(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "application/json")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var user repo.Resource
err := json.NewDecoder(request.Body).Decode(&user)
if err != nil {
h.log.Info("Failed to decode user json.",
zap.Error(err),
)
return
}
user.Password = e.GetHash([]byte(user.Password))
err = h.s.Create(&user, ctx)
if err != nil {
if errors.Is(err, internal.ErrWrongEmail) {
response.WriteHeader(http.StatusUnprocessableEntity)
_, err = response.Write([]byte(`{"message":"Email format inccorect"}`))
if err != nil {
h.log.Info("Failed to write user response.",
zap.Error(err),
)
response.WriteHeader(http.StatusInternalServerError)
return
}
return
}
if errors.Is(err, internal.ErrValidationFailed) {
response.WriteHeader(http.StatusUnprocessableEntity)
_, err = response.Write([]byte(`{"message":"This email is already in use"}`))
if err != nil {
h.log.Info("Failed to write user response.",
zap.Error(err),
)
response.WriteHeader(http.StatusInternalServerError)
return
}
return
}
response.WriteHeader(http.StatusUnprocessableEntity)
return
}
response.WriteHeader(http.StatusCreated)
}
// Signin
// Signin godoc
// @Summary Signin
// @Description Signin
// @Tags Users
// @Param Body body repo.Resource true "Email and password"
// @Accept json
// @Produce json
// @Success 200 {object} string
// @Failure 400
// @Failure 422
// @Failure 500
// @Router /signin [post]
func (h *Handler) Signin(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "application/json")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var user repo.Resource
err := json.NewDecoder(request.Body).Decode(&user)
if err != nil {
h.log.Info("Failed to decode user json.",
zap.Error(err),
)
response.WriteHeader(http.StatusBadRequest)
return
}
resource, err := h.s.Retrieve(user.EMail, ctx)
if err != nil {
if errors.Is(err, internal.ErrValidationFailed) {
response.WriteHeader(http.StatusBadRequest)
_, err = response.Write([]byte(err.Error()))
if err != nil {
h.log.Info("Failed to write response.",
zap.Error(err),
)
response.WriteHeader(http.StatusInternalServerError)
return
}
return
}
response.WriteHeader(http.StatusUnprocessableEntity)
return
}
if resource == nil {
response.WriteHeader(http.StatusUnauthorized)
_, err = response.Write([]byte(`{"message":"Wrong email or password"}`))
if err != nil {
h.log.Info("Failed to write user response.",
zap.Error(err),
)
response.WriteHeader(http.StatusInternalServerError)
return
}
return
}
userDB, ok := resource.(*repo.Resource)
if !ok {
h.log.Info("Failed to assert user object.",
zap.Bool("ok", ok),
)
response.WriteHeader(http.StatusUnprocessableEntity)
return
}
err = bcrypt.CompareHashAndPassword([]byte(userDB.Password), []byte(user.Password))
if err != nil {
response.WriteHeader(http.StatusUnauthorized)
_, err = response.Write([]byte(`{"message":"Wrong email or password"}`))
if err != nil {
h.log.Info("Failed to write user response.",
zap.Error(err),
)
response.WriteHeader(http.StatusInternalServerError)
return
}
return
}
jwtToken, err := tkn.GenerateJWT(resource.GID())
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
return
}
_, err = response.Write([]byte(`{"token":"` + jwtToken + `"}`))
if err != nil {
h.log.Info("Failed to write user response.",
zap.Error(err),
)
response.WriteHeader(http.StatusInternalServerError)
return
}
}