blob: d6e8b5a00aa86c3eab786f8fd899ec35a030e710 (
plain)
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
|
package models
import (
"errors"
"nexus/types/account"
"nexus/utils/validate"
"strings"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type Account struct {
gorm.Model
ID uuid.UUID `gorm:"type:uuid;primaryKey"`
Username string `gorm:"uniqueIndex;not null"`
Email string `gorm:"uniqueIndex;not null"`
PasswordHash string `gorm:"not null"`
IsActive bool `gorm:"default:true"`
IsVerified bool `gorm:"default:false"`
Characters []Character `gorm:"foreignKey:AccountID"`
Sessions []Session `gorm:"foreignKey:AccountID"`
}
func (self *Account) BeforeCreate(tx *gorm.DB) error {
if self.ID == uuid.Nil {
self.ID = uuid.New()
}
self.Email = strings.TrimSpace(strings.ToLower(self.Email))
self.Username = strings.TrimSpace(self.Username)
if !validate.Email(self.Email) {
return errors.New(validate.InvalidEmail)
}
if self.Username == "" {
return errors.New("username is required")
}
return nil
}
func (self *Account) BeforeUpdate(tx *gorm.DB) error {
self.Email = strings.TrimSpace(strings.ToLower(self.Email))
self.Username = strings.TrimSpace(self.Username)
if !validate.Email(self.Email) {
return errors.New(validate.InvalidEmail)
}
return nil
}
func (self *Account) SetPassword(password string) error {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
self.PasswordHash = string(hash)
return nil
}
func (self *Account) CheckPassword(password string) bool {
return bcrypt.CompareHashAndPassword([]byte(self.PasswordHash), []byte(password)) == nil
}
func (self *Account) ToResponse() account.Response {
return account.Response{
ID: self.ID,
Username: self.Username,
Email: self.Email,
IsVerified: self.IsVerified,
CreatedAt: self.CreatedAt,
}
}
|