/
users.go
253 lines (223 loc) · 6.24 KB
/
users.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
package api
import (
"errors"
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/imdario/mergo"
"github.com/maxiepax/go-via/db"
"github.com/maxiepax/go-via/models"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
// ListUsers Get a list of all users
// @Summary Get all users
// @Tags users
// @Accept json
// @Produce json
// @Success 200 {array} models.User
// @Failure 500 {object} models.APIError
// @Router /users [get]
func ListUsers(c *gin.Context) {
var items []models.User
if res := db.DB.Find(&items); res.Error != nil {
Error(c, http.StatusInternalServerError, res.Error) // 500
return
}
c.JSON(http.StatusOK, items) // 200
}
// GetUser Get an existing user
// @Summary Get an existing user
// @Tags users
// @Accept json
// @Produce json
// @Param id path int true "User ID"
// @Success 200 {object} models.User
// @Failure 400 {object} models.APIError
// @Failure 404 {object} models.APIError
// @Failure 500 {object} models.APIError
// @Router /users/{id} [get]
func GetUser(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
Error(c, http.StatusBadRequest, err) // 400
return
}
// Load the item
var item models.User
if res := db.DB.First(&item, id); res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
Error(c, http.StatusNotFound, fmt.Errorf("not found")) // 404
} else {
Error(c, http.StatusInternalServerError, res.Error) // 500
}
return
}
c.JSON(http.StatusOK, item) // 200
}
// SearchUser Search for a user
// @Summary Search for a user
// @Tags users
// @Accept json
// @Produce json
// @Param item body models.User true "Fields to search for"
// @Success 200 {object} models.User
// @Failure 400 {object} models.APIError
// @Failure 404 {object} models.APIError
// @Failure 500 {object} models.APIError
// @Router /users/search [post]
func SearchUser(c *gin.Context) {
form := make(map[string]interface{})
if err := c.ShouldBind(&form); err != nil {
Error(c, http.StatusBadRequest, err) // 400
return
}
query := db.DB
for k, v := range form {
query = query.Where(k, v)
}
// Load the item
var item models.User
if res := query.First(&item); res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
Error(c, http.StatusNotFound, fmt.Errorf("not found")) // 404
} else {
Error(c, http.StatusInternalServerError, res.Error) // 500
}
return
}
c.JSON(http.StatusOK, item) // 200
}
// CreateUser Create a new user
// @Summary Create a new user
// @Tags users
// @Accept json
// @Produce json
// @Param item body models.UserForm true "Add an user"
// @Success 200 {object} models.User
// @Failure 400 {object} models.APIError
// @Failure 500 {object} models.APIError
// @Router /users [post]
func CreateUser(c *gin.Context) {
var form models.UserForm
if err := c.ShouldBind(&form); err != nil {
Error(c, http.StatusBadRequest, err) // 400
return
}
item := models.User{UserForm: form}
// hash and salt the plaintext password
hp := HashAndSalt([]byte(item.Password))
item.Password = hp
if res := db.DB.Create(&item); res.Error != nil {
Error(c, http.StatusInternalServerError, res.Error) // 500
return
}
c.JSON(http.StatusOK, item) // 200
}
// UpdateUser Update an existing user
// @Summary Update an existing user
// @Tags users
// @Accept json
// @Produce json
// @Param id path int true "User ID"
// @Param item body models.UserForm true "Update a user"
// @Success 200 {object} models.User
// @Failure 400 {object} models.APIError
// @Failure 404 {object} models.APIError
// @Failure 500 {object} models.APIError
// @Router /users/{id} [patch]
func UpdateUser(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
Error(c, http.StatusBadRequest, err) // 400
return
}
// Load the form data
var form models.UserForm
if err := c.ShouldBind(&form); err != nil {
Error(c, http.StatusBadRequest, err) // 400
return
}
// Load the item
var item models.User
if res := db.DB.First(&item, id); res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
Error(c, http.StatusNotFound, fmt.Errorf("not found")) // 404
} else {
Error(c, http.StatusInternalServerError, res.Error) // 500
}
return
}
// Merge the item and the form data
if err := mergo.Merge(&item, models.User{UserForm: form}, mergo.WithOverride); err != nil {
Error(c, http.StatusInternalServerError, err) // 500
}
// hash and salt the plaintext password
hp := HashAndSalt([]byte(item.Password))
item.Password = hp
// Save it
if res := db.DB.Save(&item); res.Error != nil {
Error(c, http.StatusInternalServerError, res.Error) // 500
return
}
c.JSON(http.StatusOK, item) // 200
}
// DeleteUser Remove an existing user
// @Summary Remove an existing user
// @Tags users
// @Accept json
// @Produce json
// @Param id path int true "User ID"
// @Success 204
// @Failure 404 {object} models.APIError
// @Failure 500 {object} models.APIError
// @Router /users/{id} [delete]
func DeleteUser(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
Error(c, http.StatusBadRequest, err) // 400
return
}
// Load the item
var item models.User
if res := db.DB.First(&item, id); res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
Error(c, http.StatusNotFound, fmt.Errorf("not found")) // 404
} else {
Error(c, http.StatusInternalServerError, res.Error) // 500
}
return
}
// Save it
if res := db.DB.Delete(&item); res.Error != nil {
Error(c, http.StatusInternalServerError, res.Error) // 500
return
}
c.JSON(http.StatusNoContent, gin.H{}) //204
}
// functions to hash and compare passwords
func HashAndSalt(pwd []byte) string {
// Generate hashed and salted password
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
}).Error("couldnt salt and hash password")
}
return string(hash)
}
func ComparePasswords(hashedPwd string, plainPwd []byte, username string) bool {
// compare a password to the hashed and salted value
byteHash := []byte(hashedPwd)
err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
if err != nil {
logrus.WithFields(logrus.Fields{
"username": username,
"error": err,
}).Error("invalid password supplied")
return false
}
return true
}