/
auth.go
332 lines (269 loc) · 7.5 KB
/
auth.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package gos
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/hex"
"fmt"
"github.com/jiorry/db"
"github.com/jiorry/libs/crypto"
"github.com/jiorry/libs/util"
"strconv"
"strings"
"time"
)
var poolRSAKey []*RSAKey
var privateSecret string = util.Unique()
var separator []byte = []byte("|")
type AuthVO struct {
Table, FieldId, FieldNick, FieldToken, FieldEmail, FieldSalt, FieldLastSee string
CookieKey, CookiePublicKey string
}
type RSAKey struct {
Key *rsa.PrivateKey
CreatedAt time.Time
}
func init() {
poolRSAKey = make([]*RSAKey, 3)
}
func newRSAKey() *rsa.PrivateKey {
key, err := rsa.GenerateKey(rand.Reader, 512)
if err != nil {
return nil
}
return key
}
// The Rsa key will be changed after every 3 minute
func GetRSAKey(unix int64) *RSAKey {
now := time.Now()
if poolRSAKey[0] == nil {
poolRSAKey[0] = &RSAKey{newRSAKey(), now}
} else {
if now.Unix()-poolRSAKey[0].CreatedAt.Unix() > 180 {
poolRSAKey[2] = poolRSAKey[1]
poolRSAKey[1] = poolRSAKey[0]
poolRSAKey[0] = &RSAKey{newRSAKey(), now}
}
}
if unix == 0 {
return poolRSAKey[0]
}
for _, k := range poolRSAKey {
if k != nil && k.CreatedAt.Unix() == unix {
return k
}
}
return nil
}
type UserAuth struct {
user db.DataRow
ctx *Context
RegistFunc func(string, string) error
GroupId int
VO *AuthVO
}
func (this *UserAuth) SetContext(c *Context) *UserAuth {
this.ctx = c
if this.VO == nil {
this.VO = &AuthVO{}
this.VO.CookieKey = "gosauth"
this.VO.CookiePublicKey = "gospub"
this.VO.Table = "users"
this.VO.FieldId = "id"
this.VO.FieldNick = "nick"
this.VO.FieldToken = "token"
this.VO.FieldEmail = "email"
this.VO.FieldSalt = "salt"
this.VO.FieldLastSee = "last_see_at"
}
return this
}
func (this *UserAuth) SetUser(row db.DataRow) *UserAuth {
this.user = row
return this
}
func (this *UserAuth) GenerateUserToken(login string, pwd string, salt string) string {
return util.MD5String(login + salt + pwd + salt)
}
func (this *UserAuth) Auth(ctype string, cipher []byte) (string, error) {
ts, b, err := this.PraseCipher(cipher)
if err != nil {
return "", err
}
arr := bytes.Split(b, separator)
loginString := string(arr[0])
pwd := string(arr[1])
if time.Now().Unix()-int64(ts) > 30 {
return "", NewError(0, "user auth is overdue").Log("notice")
}
var user db.DataRow
if ctype == "nick" {
user = this.Query(loginString)
} else {
user = this.QueryByEmail(loginString)
}
if user == nil {
return loginString, NewError(0, loginString+" not found").Log("notice")
}
if user.GetString(this.VO.FieldToken) != this.GenerateUserToken(user.GetString(this.VO.FieldNick), pwd, user.GetString(this.VO.FieldSalt)) {
this.ClearCookie()
this.user = nil
return loginString, NewError(0, "login failed").Log("notice")
}
this.user = user
data := db.DataRow{}
data[this.VO.FieldLastSee] = time.Now()
(&db.UpdateBuilder{}).Table(this.VO.Table).
Where(this.VO.FieldId+"=?", this.user.GetInt64(this.VO.FieldId)).
Update(data)
return loginString, nil
}
func (this *UserAuth) Query(login string) db.DataRow {
find := (&db.QueryBuilder{}).Table(this.VO.Table).Where(this.VO.FieldNick+"=?", login).Cache(300)
row, err := find.QueryOne()
if err != nil {
return nil
}
return row
}
func (this *UserAuth) QueryByEmail(email string) db.DataRow {
find := (&db.QueryBuilder{}).Table(this.VO.Table).Where(this.VO.FieldEmail+"=?", email).Cache(300)
row, err := find.QueryOne()
if err != nil {
return nil
}
return row
}
func (this *UserAuth) createAuthToken(login string, ts int64, usertoken string, salt string) string {
return util.MD5String(fmt.Sprint(salt, login, ts, usertoken, salt))
}
func (this *UserAuth) SetCookie(age int64) {
ts := time.Now().Unix()
var unix int64 = 0
if age > 0 {
unix = ts + age
}
this.ctx.SetCookie(this.VO.CookieKey, fmt.Sprintf("%s|%d|%s", this.Nick(), ts, this.createAuthToken(this.Nick(), ts, this.user.GetString(this.VO.FieldToken), privateSecret)), unix, "/", "", true)
this.ctx.SetCookie(this.VO.CookiePublicKey, fmt.Sprint(this.Nick(), "|", this.GroupId), unix, "/", "", false)
}
func (this *UserAuth) ClearCookie() {
this.ctx.SetCookie(this.VO.CookieKey, "", -1, "/", "", true)
this.ctx.SetCookie(this.VO.CookiePublicKey, "", -1, "/", "", false)
}
func (this *UserAuth) CheckLogin(successUrl string) bool {
if this.NotOk() {
this.ClearCookie()
if successUrl != "" {
this.ctx.Redirect(successUrl + "?redirect=" + this.ctx.Request.URL.RequestURI())
}
return false
}
return true
}
func (this *UserAuth) IsOk() bool {
return len(this.CurrentUser()) > 0
}
func (this *UserAuth) NotOk() bool {
return len(this.CurrentUser()) == 0
}
func (this *UserAuth) UserId() int64 {
if this.IsOk() {
return this.user.GetInt64(this.VO.FieldId)
}
return -1
}
func (this *UserAuth) Nick() string {
if this.IsOk() {
return this.user.GetString(this.VO.FieldNick)
}
return ""
}
func (this *UserAuth) User() db.DataRow {
return this.CurrentUser()
}
func (this *UserAuth) CurrentUser() db.DataRow {
if len(this.user) > 0 {
return this.user
}
v, err := this.ctx.Request.Cookie(this.VO.CookieKey)
if err != nil {
return this.user
}
arr := strings.Split(v.Value, string(separator))
if len(arr) != 3 {
return this.user
}
login := arr[0]
this.user = this.Query(login)
n, _ := strconv.Atoi(arr[1])
ts := int64(n)
if this.user == nil || arr[2] != this.createAuthToken(login, ts, this.user.GetString(this.VO.FieldToken), privateSecret) {
this.user = nil
}
return this.user
}
func (this *UserAuth) PraseCipher(cipher []byte) (int64, []byte, error) {
arr := bytes.Split(cipher, separator)
rsakeyUnix, _ := strconv.Atoi(string(arr[0]))
rsaCipher := make([]byte, len(arr[1])/2)
hex.Decode(rsaCipher, arr[1])
ppk := GetRSAKey(int64(rsakeyUnix))
if ppk == nil {
return 0, nil, NewError(0, "no rsa key found!").Log("error")
}
aeskeyBase64, err := rsa.DecryptPKCS1v15(rand.Reader, ppk.Key, rsaCipher)
if err != nil {
return 0, nil, NewError(0, "decrypt::", err).Log("error")
}
aeskey := make([]byte, 18)
base64.StdEncoding.Decode(aeskey, aeskeyBase64)
if len(aeskey) == 0 {
return 0, nil, NewError(0, "aeskey is empty").Log("error")
}
aeskey = aeskey[:16]
code, err := base64.StdEncoding.DecodeString(string(arr[2]))
if err != nil {
return 0, nil, NewError(0, "base64 decode:", err).Log("error")
}
now := time.Now()
ts, _ := strconv.Atoi(fmt.Sprintf("%x", code[0:8]))
if now.Unix()-int64(ts/1000) > 30 {
return 0, nil, NewError(0, "login ts is exprie").Log("error")
}
b := crypto.AESDecrypt(code[8:24], aeskey[0:16], code[24:])
n := bytes.Index(b, []byte("-"))
l, err := strconv.Atoi(string(b[0:n]))
if err != nil {
return 0, nil, NewError(0, err).Log("error")
}
return int64(ts), b[n+1 : n+1+l], nil
}
func (this *UserAuth) Regist(login string, email string, cipher string) error {
if login == "" || email == "" {
return NewError(0, "login or email is empty")
}
e := (&db.ExistsBuilder{}).
Table(this.VO.Table).
Where(this.VO.FieldNick+"=? or "+this.VO.FieldEmail+"=?", login, email)
if isExist, _ := e.Exists(); isExist {
return NewError(0, "login or email exists")
}
_, text, err := this.PraseCipher([]byte(cipher))
if err != nil {
return NewError(0, err)
}
salt := util.Unique()
err = this.RegistFunc(salt, this.GenerateUserToken(login, string(text), salt))
if err != nil {
return err
}
u := this.Query(login)
if u == nil {
return NewError(0, "user is empty")
} else {
this.SetUser(u)
this.SetCookie(0)
}
return nil
}