forked from shunfei/cronsun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
account.go
108 lines (90 loc) · 2.29 KB
/
account.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
package cronsun
import (
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const (
Coll_Account = "account"
)
type Account struct {
ID bson.ObjectId `bson:"_id" json:"id"`
Role Role `bson:"role" json:"role"`
Email string `bson:"email" json:"email"`
Password string `bson:"password" json:"password"`
Salt string `bson:"salt" json:"salt"`
Status UserStatus `bson:"status" json:"status"`
Session string `bson:"session" json:"-"`
// If true, role and status are unchangeable, email and password can be change by it self only.
Unchangeable bool `bson:"unchangeable" json:"-"`
CreateTime time.Time `bson:"createTime" json:"createTime"`
}
type Role int
const (
Administrator Role = 1
Developer Role = 2
Reporter Role = 3
)
func (r Role) Defined() bool {
switch r {
case Administrator, Developer, Reporter:
return true
}
return false
}
func (r Role) String() string {
switch r {
case Administrator:
return "Administrator"
case Developer:
return "Developer"
case Reporter:
return "Reporter"
}
return "Undefined"
}
type UserStatus int
const (
UserBanned UserStatus = -1
UserActived UserStatus = 1
)
func (s UserStatus) Defined() bool {
switch s {
case UserBanned, UserActived:
return true
}
return false
}
func GetAccounts(query bson.M) (list []Account, err error) {
err = mgoDB.WithC(Coll_Account, func(c *mgo.Collection) error {
return c.Find(query).All(&list)
})
return
}
func GetAccountByEmail(email string) (u *Account, err error) {
err = mgoDB.FindOne(Coll_Account, bson.M{"email": email}, &u)
return
}
func CreateAccount(u *Account) error {
u.ID = bson.NewObjectId()
u.CreateTime = time.Now()
return mgoDB.Insert(Coll_Account, u)
}
func UpdateAccount(query bson.M, change bson.M) error {
return mgoDB.WithC(Coll_Account, func(c *mgo.Collection) error {
return c.Update(query, bson.M{"$set": change})
})
}
func BanAccount(email string) error {
return mgoDB.WithC(Coll_Account, func(c *mgo.Collection) error {
return c.Update(bson.M{"email": email}, bson.M{"$set": bson.M{"status": UserBanned}})
})
}
func EnsureAccountIndex() error {
return mgoDB.WithC(Coll_Account, func(c *mgo.Collection) error {
return c.EnsureIndex(mgo.Index{
Key: []string{"email"},
Unique: true,
})
})
}