-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmodels.go
77 lines (66 loc) · 2.34 KB
/
models.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
package db
import (
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type UUIDBase struct {
ID uuid.UUID `gorm:"primarykey;type:uuid" json:"id"`
}
func (base *UUIDBase) BeforeCreate(tx *gorm.DB) (err error) {
base.ID = uuid.New()
return
}
type TimeBase struct {
CreatedAt time.Time `gorm:"autoCreateTime" json:"createdAt"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt,omitempty"`
}
type User struct {
UUIDBase
TimeBase
Username string `gorm:"uniqueIndex;not null;type:varchar(30)" json:"username"`
Password []byte `gorm:"not null" json:"-" hidden:"true" readOnly:"true"`
Name *string `gorm:"size:128" json:"name"`
Books []Book `gorm:"foreignKey:OwnerID" json:"books,omitempty"`
}
func (u *User) SetPassword(newPlainPassword string) {
hashedPw, err := bcrypt.GenerateFromPassword([]byte(newPlainPassword), bcrypt.DefaultCost)
if err != nil {
panic(err)
}
u.Password = hashedPw
}
func (u *User) IsPasswordMatch(plainPassword string) bool {
if err := bcrypt.CompareHashAndPassword(u.Password, []byte(plainPassword)); err == nil {
return true
}
return false
}
type Note struct {
UUIDBase
TimeBase
Name string `gorm:"not null;type:varchar(80)" json:"name"`
Slug string `gorm:"index:idx_note,unique;not null;type:varchar(80)" json:"slug" validate:"slug"`
BookID uuid.UUID `gorm:"index:idx_note,unique;not null;type:uuid" json:"bookId"`
Book Book `gorm:"foreignKey:BookID" json:"-"`
Assets []NoteAsset `gorm:"foreignKey:NoteID" json:"assets,omitempty"`
}
type NoteAsset struct {
UUIDBase
CreatedAt time.Time `gorm:"autoCreateTime" json:"createdAt"`
Name string `gorm:"not null;type:varchar(80)" json:"name"`
NoteID uuid.UUID `gorm:"index:idx_note_asset;not null;type:uuid" json:"noteId"`
Note Note `json:"-"`
}
type Book struct {
UUIDBase
TimeBase
Name string `gorm:"not null;type:varchar(80)" json:"name"`
Slug string `gorm:"index:idx_book,unique;not null;type:varchar(80)" json:"slug" validate:"slug"`
OwnerID uuid.UUID `gorm:"index:idx_book,unique;not null;type:uuid" json:"ownerId"`
IsPublic bool `gorm:"not null;default:false;type:boolean" json:"isPublic"`
Owner User `json:"-"`
Notes []Note `gorm:"foreignKey:BookID" json:"notes,omitempty"`
}