-
Notifications
You must be signed in to change notification settings - Fork 12
/
users.red
120 lines (105 loc) · 2.11 KB
/
users.red
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
#!/usr/local/bin/red
Red [
Note: "need enbase64url from http-tools"
]
users-file: %/var/www/data/users.red
tokens-file: %/var/www/data/tokens.red
users: none
tokens: none
; -- user management --------------------------------------------------------
load-users: func [][
users: either any [
not exists? users-file
zero? size? users-file
][
copy #()
][
load users-file
]
]
save-users: func [][
save users-file users
]
make-user: func [
"Returns FALSE when user exists, TOKEN when not and is created"
name [string!]
password [string!]
/local user
][
if select users name [return false]
user: compose [
name: none
password: none
salt: none
version: 1
created: now/precise
]
user/name: name
user/salt: checksum form now/time/precise 'SHA256
user/password: checksum rejoin [user/salt password] 'SHA256
users/:name: user
save-users
make-token name
]
login-user: func [
"Return NONE when user not exists, FALSE when password is wrong or TOKEN"
name [string!]
password [string!]
/local user
][
user: select users name
unless user [return none]
password: checksum rejoin [user/salt password] 'SHA256
unless equal? password user/password [return false]
make-token name
]
; -- token management -------------------------------------------------------
load-tokens: func [][
tokens: either any [
not exists? tokens-file
zero? size? tokens-file
][
copy #()
][
load tokens-file
]
check-tokens
]
save-tokens: func [][
save tokens-file tokens
]
check-tokens: func [][
foreach [token data] tokens [
if data/expires < now/precise [
remove/key tokens token
save-tokens
]
]
]
make-token: func [name /refresh data /local token][
data: any [
data
enbase64url checksum form now/precise 'sha256
]
token: compose [
name: none
value: (data)
expires: (now/precise + 01:00:00) ; TODO: move expiration to settings
]
token/name: name
tokens/:name: token
save-tokens
make map! token
]
match-token: func [value][
foreach [user token] tokens [
if equal? value token/value [
make-token/refresh user value
return user
]
]
return false
]
; -- initalization
load-users
load-tokens