-
Notifications
You must be signed in to change notification settings - Fork 9
/
user.go
226 lines (195 loc) · 6.18 KB
/
user.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
package controllers
import (
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/go-sql-driver/mysql"
"github.com/steffen25/golang.zone/app"
"github.com/steffen25/golang.zone/models"
"github.com/steffen25/golang.zone/repositories"
"github.com/steffen25/golang.zone/services"
"github.com/steffen25/golang.zone/util"
)
// Embed a UserDAO/Repository thingy
type UserController struct {
*app.App
repositories.UserRepository
repositories.PostRepository
}
func NewUserController(a *app.App, ur repositories.UserRepository, pr repositories.PostRepository) *UserController {
return &UserController{a, ur, pr}
}
func (uc *UserController) HelloWorld(w http.ResponseWriter, r *http.Request) {
log.Println(r.Context().Value("userId"))
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, "Hello gopher!")
}
func (uc *UserController) Profile(w http.ResponseWriter, r *http.Request) {
uid, err := services.UserIdFromContext(r.Context())
if err != nil {
NewAPIError(&APIError{false, "Something went wrong", http.StatusInternalServerError}, w)
return
}
NewAPIResponse(&APIResponse{Data: uid}, w, http.StatusOK)
}
func (uc *UserController) Create(w http.ResponseWriter, r *http.Request) {
// Validate the length of the body since some users could send a big payload
/*required := []string{"name", "email", "password"}
if len(params) != len(required) {
err := NewAPIError(false, "Invalid request")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(err)
return
}*/
j, err := GetJSON(r.Body)
if err != nil {
NewAPIError(&APIError{false, "Invalid request", http.StatusBadRequest}, w)
return
}
name, err := j.GetString("name")
if err != nil {
NewAPIError(&APIError{false, "Name is required", http.StatusBadRequest}, w)
return
}
// TODO: Implement something like this and embed in a basecontroller https://stackoverflow.com/a/23960293/2554631
if len(name) < 2 || len(name) > 32 {
NewAPIError(&APIError{false, "Name must be between 2 and 32 characters", http.StatusBadRequest}, w)
return
}
email, err := j.GetString("email")
if err != nil {
NewAPIError(&APIError{false, "Email is required", http.StatusBadRequest}, w)
return
}
if ok := util.IsEmail(email); !ok {
NewAPIError(&APIError{false, "You must provide a valid email address", http.StatusBadRequest}, w)
return
}
exists := uc.UserRepository.Exists(email)
if exists {
NewAPIError(&APIError{false, "The email address is already in use", http.StatusBadRequest}, w)
return
}
pw, err := j.GetString("password")
if err != nil {
NewAPIError(&APIError{false, "Password is required", http.StatusBadRequest}, w)
return
}
if len(pw) < 6 {
NewAPIError(&APIError{false, "Password must not be less than 6 characters", http.StatusBadRequest}, w)
return
}
u := &models.User{
Name: name,
Email: email,
Admin: false,
CreatedAt: time.Now(),
}
u.SetPassword(pw)
err = uc.UserRepository.Create(u)
if err != nil {
NewAPIError(&APIError{false, "Could not create user", http.StatusBadRequest}, w)
return
}
defer r.Body.Close()
NewAPIResponse(&APIResponse{Success: true, Message: "User created"}, w, http.StatusOK)
}
func (uc *UserController) GetAll(w http.ResponseWriter, r *http.Request) {
users, err := uc.UserRepository.GetAll()
if err != nil {
// something went wrong
NewAPIError(&APIError{false, "Could not fetch users", http.StatusBadRequest}, w)
return
}
NewAPIResponse(&APIResponse{Success: true, Data: users}, w, http.StatusOK)
}
func (uc *UserController) GetById(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
NewAPIError(&APIError{false, "Invalid request", http.StatusBadRequest}, w)
return
}
user, err := uc.UserRepository.FindById(id)
if err != nil {
// user was not found
NewAPIError(&APIError{false, "Could not find user", http.StatusNotFound}, w)
return
}
NewAPIResponse(&APIResponse{Success: true, Data: user}, w, http.StatusOK)
}
func (uc *UserController) Update(w http.ResponseWriter, r *http.Request) {
uid, err := services.UserIdFromContext(r.Context())
if err != nil {
NewAPIError(&APIError{false, "Something went wrong", http.StatusInternalServerError}, w)
return
}
user, err := uc.UserRepository.FindById(uid)
if err != nil {
NewAPIError(&APIError{false, "Could not find user", http.StatusBadRequest}, w)
return
}
j, err := GetJSON(r.Body)
if err != nil {
NewAPIError(&APIError{false, "Invalid request", http.StatusBadRequest}, w)
return
}
name, err := j.GetString("name")
if name != "" && err == nil {
user.Name = name
}
newpw, err := j.GetString("newpassword")
if newpw != "" && err == nil {
// confirm password
oldpw, err := j.GetString("oldpassword")
if err != nil {
NewAPIError(&APIError{false, "Old password is required", http.StatusBadRequest}, w)
return
}
ok := user.CheckPassword(oldpw)
if !ok {
NewAPIError(&APIError{false, "Old password do not match", http.StatusBadRequest}, w)
return
}
if len(newpw) < 6 {
NewAPIError(&APIError{false, "Password must not be less than 6 characters", http.StatusBadRequest}, w)
return
}
user.SetPassword(newpw)
}
user.UpdatedAt = mysql.NullTime{Time: time.Now(), Valid: true}
err = uc.UserRepository.Update(user)
if err != nil {
NewAPIError(&APIError{false, "Could not update user", http.StatusBadRequest}, w)
return
}
authUser := &models.AuthUser{
User: user,
Admin: user.Admin,
}
NewAPIResponse(&APIResponse{Success: true, Data: authUser}, w, http.StatusOK)
}
func (uc *UserController) FindPostsByUser(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
NewAPIError(&APIError{false, "Invalid request", http.StatusBadRequest}, w)
return
}
user, err := uc.UserRepository.FindById(id)
if err != nil {
// user was not found
NewAPIError(&APIError{false, "Could not find user", http.StatusNotFound}, w)
return
}
posts, err := uc.PostRepository.FindByUser(user)
if err != nil {
// user was not found
NewAPIError(&APIError{false, "Could not find user posts", http.StatusNotFound}, w)
return
}
NewAPIResponse(&APIResponse{Success: true, Data: posts}, w, http.StatusOK)
}