-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.go
96 lines (77 loc) · 2.57 KB
/
model.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
package iam
import (
"time"
"github.com/dannypaul/go-skeleton/internal/config"
"github.com/dannypaul/go-skeleton/internal/exception"
"github.com/dannypaul/go-skeleton/internal/primitive"
"github.com/dannypaul/go-skeleton/internal/repository"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
)
const CtxClaimsKey = "claims"
type IdentityType string
const (
EMAIL IdentityType = "EMAIL"
PHONE IdentityType = "PHONE"
)
type Phone struct {
Number string `bson:"number,omitempty" json:"number"`
}
type Identity struct {
Id primitive.Id `bson:"_id,omitempty" json:"id"`
Type IdentityType `bson:"type" json:"type"`
Verified bool `bson:"verified" json:"verified"`
EmailId string `bson:"emailId,omitempty" json:"emailId"`
Phone *Phone `bson:"phone,omitempty" json:"phone"`
}
type IdentityList []Identity
func (i IdentityList) getIdentity(identityType IdentityType) (Identity, int, error) {
for index, identity := range i {
if identity.Type == identityType {
return identity, index, nil
}
}
return Identity{}, 0, exception.ErrNotFound
}
type Role string
const (
PlatformAdmin Role = "PLATFORM_ADMIN"
MerchantAdmin Role = "MERCHANT_ADMIN"
)
type User struct {
Id primitive.Id `bson:"_id,omitempty" json:"id"`
Role Role `bson:"role" json:"role"`
Name string `bson:"name" json:"name"`
Version int `bson:"version" json:"version"`
FailedAuthAttempts int `bson:"failedAuthAttempts" json:"-"`
Identities IdentityList `bson:"identities" json:"identities"`
Password string `bson:"password" json:"-"`
}
func (u User) equalsPassword(password string) bool {
return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password)) == nil
}
func (u *User) updatePassword(newPassword string) {
//TODO: handle the error returned by GenerateFromPassword
bytes, _ := bcrypt.GenerateFromPassword([]byte(newPassword), 14)
u.Password = string(bytes)
}
type UserList struct {
Users []User `json:"users"`
Page repository.Page `json:"page"`
}
func (u User) createToken(verified bool) (string, error) {
conf, _ := config.Get()
claims := &Claims{
UserId: u.Id,
UserVersion: u.Version,
Role: u.Role,
Verified: verified,
StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().UTC().Add(conf.JwtTTL).Unix()},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(conf.JwtSecret))
}
type Session struct {
User User `json:"user"`
Token string `json:"token"`
}