-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
155 lines (128 loc) · 3.89 KB
/
auth.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
package auth
import (
"net/http"
"time"
"github.com/btdjangbah001/chat-app/models"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
var jwtKey = []byte("my_secret_key")
type Claims struct {
UserID uint
jwt.StandardClaims
}
func createToken(user *models.User) (string, error) {
// Create JWT claims
claims := &Claims{
UserID: user.ID,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 24).Unix(),
IssuedAt: time.Now().Unix(),
Subject: "myapp_user",
},
}
// Create JWT token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign JWT token
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return "", err
}
return tokenString, nil
}
func RegisterUser(c *gin.Context) {
var user models.User
var userRegister models.UserSignUp
err := c.ShouldBindJSON(&userRegister)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if !models.UserFieldIsEmail(userRegister.Email) {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "enter a valid email"})
return
}
if userRegister.Password != userRegister.ConfirmPassword {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "passwords do not match"})
return
}
// if !isStrongPassword(userLogin.Password) {
// c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "password is not strong enough"})
// return
// }
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(userRegister.Password), bcrypt.DefaultCost)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "something went wrong please try again"})
return
}
exists, _ := models.UsernameOrEmailExists(&userRegister)
if exists {
c.JSON(400, gin.H{"error": "username or email already exists"})
return
}
user.Username = userRegister.Username
user.Email = userRegister.Email
user.Password = string(hashedPassword)
err = user.CreateUser()
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
token, err := createToken(&user)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "something went wrong please try again"})
return
}
c.JSON(200, gin.H{"user": user, "token": token})
}
func LoginUser(c *gin.Context) {
var userLogin models.UserLogin
var user *models.User
var err error
err = c.ShouldBindJSON(&userLogin)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if models.UserFieldIsEmail(userLogin.UserField) {
user, err = models.GetUserByEmail(userLogin.UserField)
if err != nil {
// try to get user by username if not found by email
user, err = models.GetUserByUsername(userLogin.UserField)
if err != nil {
c.JSON(400, gin.H{"error": "invalid email or username or password"})
return
}
}
} else {
user, err = models.GetUserByUsername(userLogin.UserField)
if err != nil {
c.JSON(400, gin.H{"error": "invalid email or username or password"})
return
}
}
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(userLogin.Password))
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid email or username or password"})
return
}
token, err := createToken(user)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "something went wrong please try again"})
return
}
c.JSON(200, gin.H{"user": user, "token": token})
}
/*
This regex matches a password string that:
is 8 to 15 characters long
contains at least one lowercase letter (a-z)
contains at least one uppercase letter (A-Z)
contains at least one digit (0-9)
contains at least one special character that is not alphanumeric (e.g., !@#$%^&*)
*/
// func isStrongPassword(password string) bool {
// re := regexp.MustCompile(`^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$`)
// return re.MatchString(password)
// }