-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.go
309 lines (272 loc) · 8.51 KB
/
app.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
package rest
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
en_translations "github.com/go-playground/validator/v10/translations/en"
"github.com/gorilla/mux"
"github.com/iproduct/coursegopro/10-modules-rest-jwtauth/dao"
"github.com/iproduct/coursegopro/10-modules-rest-jwtauth/daomysql"
"github.com/iproduct/coursegopro/10-modules-rest-jwtauth/model"
"golang.org/x/crypto/bcrypt"
"log"
"net/http"
"strconv"
"time"
)
type App struct {
Router *mux.Router
Users dao.UserRepo
Validator *validator.Validate
Translator ut.Translator
}
func (a *App) Init(user, password, dbname string) {
a.Users = daomysql.NewUserRepoMysql(user, password, dbname)
// Create and configure validator and translator
a.Validator = validator.New()
eng := en.New()
var uni *ut.UniversalTranslator
uni = ut.New(eng, eng)
// this is usually know or extracted from http 'Accept-Language' header
// also see uni.FindTranslator(...)
var found bool
a.Translator, found = uni.GetTranslator("en")
if !found {
log.Fatal("translator not found")
}
if err := en_translations.RegisterDefaultTranslations(a.Validator, a.Translator); err != nil {
log.Fatal(err)
}
a.Router = mux.NewRouter()
a.initializeRoutes()
}
func (a *App) Run(addr string) {
log.Fatal(http.ListenAndServe(addr, a.Router))
}
func (a *App) initializeRoutes() {
a.Router.HandleFunc("/users", a.getUsers).Methods(http.MethodGet)
a.Router.HandleFunc("/users", a.createUser).Methods("POST")
a.Router.HandleFunc("/users/{id:[0-9]+}", a.getUser).Methods("GET")
a.Router.HandleFunc("/users/{id:[0-9]+}", a.updateUser).Methods("PUT")
a.Router.HandleFunc("/users/{id:[0-9]+}", a.deleteUser).Methods("DELETE")
a.Router.HandleFunc("/login", a.login).Methods("POST")
// Auth route
s := a.Router.PathPrefix("/auth").Subrouter()
s.Use(JwtVerify)
s.HandleFunc("/users", a.getUsers).Methods(http.MethodGet)
s.HandleFunc("/users", a.createUser).Methods("POST")
s.HandleFunc("/users/{id:[0-9]+}", a.getUser).Methods("GET")
s.HandleFunc("/users/{id:[0-9]+}", a.updateUser).Methods("PUT")
s.HandleFunc("/users/{id:[0-9]+}", a.deleteUser).Methods("DELETE")
}
func (a *App) login(w http.ResponseWriter, r *http.Request) {
userCredentials := &model.UserLogin{}
err := json.NewDecoder(r.Body).Decode(userCredentials)
if err != nil {
fmt.Printf("Error logging user %v: %v", userCredentials, err)
var resp = map[string]interface{}{"status": false, "message": "Invalid request"}
json.NewEncoder(w).Encode(resp)
return
}
resp, err := a.checkEmailPassword(w, userCredentials.Email, userCredentials.Password)
if err == nil {
json.NewEncoder(w).Encode(resp)
}
}
func (a *App) checkEmailPassword(w http.ResponseWriter, email, password string) (map[string]interface{}, error) {
user, err := a.Users.FindByEmail(email)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Email address not found")
return nil, err
}
expiresAt := time.Now().Add(time.Minute * 10).Unix()
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err != nil && err == bcrypt.ErrMismatchedHashAndPassword { //Password does not match!
respondWithError(w, http.StatusUnauthorized, "Invalid login credentials. Please try again")
return nil, err
}
claims := &model.UserToken{
UserID: string(user.ID),
Name: user.Name,
Email: user.Email,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expiresAt,
Issuer: "test",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, error := token.SignedString([]byte("secret"))
if error != nil {
fmt.Println(error)
}
var resp = map[string]interface{}{"status": false, "message": "logged in"}
resp["token"] = tokenString //Store the token in the response
// remove user password
user.Password = ""
resp["user"] = user
return resp, nil
}
// User handlers
func (a *App) getUsers(w http.ResponseWriter, r *http.Request) {
count, err := strconv.Atoi(r.FormValue("count"))
if err != nil && r.FormValue("count") != "" {
respondWithError(w, http.StatusBadRequest, "Invalid request count parameter")
return
}
start, err := strconv.Atoi(r.FormValue("start"))
if err != nil && r.FormValue("start") != "" {
respondWithError(w, http.StatusBadRequest, "Invalid request start parameter")
return
}
start--
if count > 20 || count < 1 {
count = 20
}
if start < 0 {
start = 0
}
users, err := a.Users.Find(start, count)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
// remove user passwords
for i := range users {
users[i].Password = ""
}
respondWithJSON(w, http.StatusOK, users)
}
func (a *App) createUser(w http.ResponseWriter, r *http.Request) {
user := &model.User{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(user); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
// Validate User struct
err := a.Validator.Struct(user)
if err != nil {
// translate all error at once
errs := err.(validator.ValidationErrors)
respondWithValidationError(errs.Translate(a.Translator), w)
return
}
// Hash the pasword with bcrypt
pass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err != nil {
fmt.Println(err)
respondWithError(w, http.StatusInternalServerError, "Password Encryption failed")
return
}
user.Password = string(pass)
if user, err = a.Users.Create(user); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
// remove user password
user.Password = ""
respondWithJSON(w, http.StatusCreated, user)
}
func (a *App) getUser(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid user ID")
return
}
var user *model.User
if user, err = a.Users.FindByID(id); err != nil {
switch err {
case sql.ErrNoRows:
respondWithError(w, http.StatusNotFound, "User not found")
default:
respondWithError(w, http.StatusInternalServerError, err.Error())
}
return
}
// remove user password
user.Password = ""
respondWithJSON(w, http.StatusOK, user)
}
func (a *App) updateUser(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid user ID")
return
}
user := &model.User{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(user); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid resquest payload")
return
}
// Validate User struct
err = a.Validator.Struct(user)
if err != nil {
// translate all error at once
errs := err.(validator.ValidationErrors)
respondWithValidationError(errs.Translate(a.Translator), w)
return
}
if user.ID != id {
respondWithError(w, http.StatusBadRequest, "ID in URL path is different from ID in request payload")
return
}
// Find if user exists in DB
oldUser, err := a.Users.FindByID(id);
if err != nil {
if err == sql.ErrNoRows {
respondWithError(w, http.StatusNotFound, fmt.Sprintf("user with ID='%d' does not exist", id))
} else {
respondWithError(w, http.StatusInternalServerError, err.Error())
}
return
}
// Encrypt password if sent otherwise use old password
if user.Password != "" {
// Hash the pasword with bcrypt
pass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err != nil {
fmt.Println(err)
respondWithError(w, http.StatusInternalServerError, "Password Encryption failed")
return
}
user.Password = string(pass)
} else {
user.Password = oldUser.Password
}
// Do update user
if user, err = a.Users.Update(user); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
// remove user password
user.Password = ""
respondWithJSON(w, http.StatusOK, user)
}
func (a *App) deleteUser(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid User ID")
return
}
// Do delete user in DB
user, err := a.Users.DeleteByID(id)
if err != nil {
if err == sql.ErrNoRows {
respondWithError(w, http.StatusNotFound, fmt.Sprintf("user with ID='%d' does not exist", id))
} else {
respondWithError(w, http.StatusInternalServerError, err.Error())
}
return
}
// remove user password
user.Password = ""
respondWithJSON(w, http.StatusOK, user)
}