-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
66 lines (53 loc) · 1.35 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
package models
import (
"fmt"
"os"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type User struct {
ID uuid.UUID `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// GORM HOOKS
// CREATE USER ID AND HASH PASSWORD
func (u *User) BeforeCreate(tx *gorm.DB) error {
u.ID = uuid.New()
fmt.Println("called")
return u.HashPassword()
}
func (u *User) HashPassword() error {
hash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
u.Password = string(hash)
return nil
}
func (u *User) ComparePassword(password string) error {
return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
}
func (u *User) Sanitize() {
u.Password = ""
}
func (u *User) GenerateToken() (string, error) {
jwtSigningMethod := jwt.SigningMethodHS256
jwtMapClaims := jwt.MapClaims{"id": u.ID}
token := jwt.NewWithClaims(jwtSigningMethod, jwtMapClaims)
return token.SignedString([]byte(os.Getenv("JWT_SECRET_KEY")))
}
type UserWithToken struct {
User
Token string `json:"token"`
}
type Author struct {
ID uuid.UUID `json:"id"`
Username string `json:"username"`
}