-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
117 lines (85 loc) · 2.52 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
package controllers
import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/f1rezy/book-store/internal/config"
"github.com/f1rezy/book-store/internal/models"
"github.com/f1rezy/book-store/pkg/db/postgresql"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
var jwtKey = []byte(config.EnvString("SECRET_KEY", "secret"))
func Signup(c *gin.Context) {
var user models.User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
var existingUser models.User
postgresql.DB.Where("email = ?", user.Email).First(&existingUser)
if existingUser.ID != 0 {
c.JSON(400, gin.H{"error": "user already exists"})
return
}
var errHash error
user.Password, errHash = GenerateHashPassword(user.Password)
if errHash != nil {
c.JSON(500, gin.H{"error": "could not generate password hash"})
return
}
postgresql.DB.Create(&user)
c.JSON(200, gin.H{"success": "user created"})
}
func Login(c *gin.Context) {
var user models.User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
var existingUser models.User
postgresql.DB.Where("email = ?", user.Email).First(&existingUser)
if existingUser.ID == 0 {
c.JSON(400, gin.H{"error": "user does not exist"})
return
}
errHash := CompareHashPassword(user.Password, existingUser.Password)
if !errHash {
c.JSON(400, gin.H{"error": "invalid password"})
return
}
expirationTime := time.Now().Add(5 * time.Minute)
claims := &models.Claims{
StandardClaims: jwt.StandardClaims{
Subject: existingUser.Email,
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
c.JSON(500, gin.H{"error": "could not generate token"})
return
}
c.JSON(200, gin.H{"token": tokenString})
}
func GenerateHashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func CompareHashPassword(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func ParseToken(tokenString string) (claims *models.Claims, err error) {
token, err := jwt.ParseWithClaims(tokenString, &models.Claims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(config.EnvString("SECRET_KEY", "secret")), nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(*models.Claims)
if !ok {
return nil, err
}
return claims, nil
}