/
controllers.go
161 lines (134 loc) · 3.96 KB
/
controllers.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
package auth
import (
"fmt"
"time"
"github.com/adeisbright/fiber-user-auth/src/common"
"github.com/adeisbright/fiber-user-auth/src/features/user"
"github.com/adeisbright/fiber-user-auth/src/loaders"
"github.com/dgrijalva/jwt-go"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
var jwtSecret = []byte("example")
func GenerateJWTToken(userID uint) (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["user_id"] = userID
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
return token.SignedString(jwtSecret)
}
type UserSchema struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
}
type LoginUser struct {
Email string `json:"email"`
Username string `json:"username"`
CreatedAt time.Time `json:"createdAt"`
ID uint `json:"id"`
}
type Handler struct {
DB *gorm.DB
}
func (h Handler) AddUser(c *fiber.Ctx) error {
var user user.User
body := UserSchema{}
err := c.BodyParser(&body)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "Internal Server Error",
"success": false,
})
}
err = h.DB.Where("email =?", body.Email).First(&user).Error
if err == nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "A user already exists with the selected email",
"success": false,
})
}
hashedPassword, error := common.HashPassword(body.Password)
if error != nil {
return fiber.NewError(fiber.StatusInternalServerError, error.Error())
}
fmt.Println(hashedPassword)
user.Username = body.Username
user.Email = body.Email
user.Password = hashedPassword
if result := h.DB.Create(&user); result.Error != nil {
return fiber.NewError(fiber.StatusNotFound, result.Error.Error())
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"message": "Your registration was successful. Login with your email and password",
"success": true,
})
}
func (h Handler) HandleLogin(c *fiber.Ctx) error {
var validUser user.User
body := UserSchema{}
err := c.BodyParser(&body)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "Bad Request",
"success": false,
})
}
validUser.Email = body.Email
validUser.Password = body.Password
var foundUser user.User
if err := h.DB.Where("email = ?", validUser.Email).First(&foundUser).Error; err != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
"message": "Invalid Login Credentials. Try again",
"success": false,
})
}
if !common.CheckPasswordHash(body.Password, foundUser.Password) {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"message": "Invalid credentials. Try again",
"success": false,
})
}
token, err := GenerateJWTToken(foundUser.ID)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "Internal Server Error",
"success": false,
})
}
var loginUser LoginUser
loginUser.Email = foundUser.Email
loginUser.Username = foundUser.Username
loginUser.CreatedAt = foundUser.CreatedAt
loginUser.ID = foundUser.ID
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"token": token,
"success": true,
"data": loginUser,
})
}
func (h Handler) HandleLogout(c *fiber.Ctx) error {
authHeader := c.Get("Authorization")
tokenString := authHeader[7:]
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil || !token.Valid {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"message": "Bad Token",
"success": false,
})
}
blacklistedTokenKey := "token:blacklist:" + tokenString
err = loaders.ConnectToRedis().Set(blacklistedTokenKey, tokenString, 0).Err()
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"success": false,
"message": "Internal Server Error",
})
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"message": "Successfully logged out",
"success": true,
})
}