-
Notifications
You must be signed in to change notification settings - Fork 2
/
user.go
104 lines (85 loc) · 2.08 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
package controllers
import (
"net/http"
"strconv"
"github.com/labstack/echo"
"github.com/otezz/go-echo-rest/app/models"
"golang.org/x/crypto/bcrypt"
)
// get all users
func AllUsers(c echo.Context) error {
var (
users []models.User
err error
)
users, err = models.GetUsers()
if err != nil {
return c.JSON(http.StatusForbidden, err)
}
return c.JSON(http.StatusOK, users)
}
// get one user
func ShowUser(c echo.Context) error {
var (
user models.User
err error
)
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
user, err = models.GetUserById(id)
if err != nil {
return c.JSON(http.StatusForbidden, err)
}
return c.JSON(http.StatusOK, user)
}
//create user
func CreateUser(c echo.Context) error {
user := new(models.User)
user.Username = c.FormValue("username")
user.Email = c.FormValue("email")
user.Password = hashPassword(c.FormValue("password"))
err := models.CreateUser(user)
if err != nil {
return c.JSON(http.StatusUnprocessableEntity, err)
}
return c.JSON(http.StatusCreated, user)
}
//update user
func UpdateUser(c echo.Context) error {
// Parse the content
user := new(models.User)
user.Username = c.FormValue("username")
user.Email = c.FormValue("email")
user.Password = hashPassword(c.FormValue("password"))
// get the param id
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
m, err := models.GetUserById(id)
if err != nil {
return c.JSON(http.StatusUnprocessableEntity, err)
}
// update user data
err = m.UpdateUser(user)
if err != nil {
return c.JSON(http.StatusForbidden, err)
}
return c.JSON(http.StatusOK, m)
}
//delete user
func DeleteUser(c echo.Context) error {
var err error
// get the param id
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
m, err := models.GetUserById(id)
if err != nil {
return c.JSON(http.StatusForbidden, err)
}
err = m.DeleteUser()
return c.JSON(http.StatusNoContent, err)
}
func hashPassword(input string) string {
password := []byte(input)
hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
panic(err)
}
return string(hashedPassword)
}