Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 39538
1
###
2
Temporary authentication token for user.
3
###
4
5
async = require('async')
6
7
random_key = require("random-key")
8
9
misc = require('smc-util/misc')
10
{defaults, types, required} = misc
11
12
auth = require('./auth')
13
14
# map {account_id:{user_account_id:timestamp}}
15
ban = {}
16
17
BAN_TIME_MS = 1000*60
18
19
exports.get_user_auth_token = (opts) ->
20
opts = defaults opts, # temporary until types is more than just a WARNING
21
database : required
22
account_id : required
23
user_account_id : required
24
password : required
25
cb : required
26
types opts,
27
database : types.object.isRequired
28
account_id : types.string.isRequired
29
user_account_id : types.string.isRequired
30
password : types.string.isRequired
31
cb : types.func.isRequired # cb(err, auth_token)
32
33
auth_token = undefined
34
b = ban[opts.account_id]?[opts.user_account_id]
35
if b? and (new Date() - b < BAN_TIME_MS)
36
opts.cb("banned -- please wait at least #{BAN_TIME_MS/1000}s before trying again")
37
return
38
39
async.series([
40
(cb) ->
41
# confirm auth
42
auth.is_password_correct
43
database : opts.database
44
account_id : opts.user_account_id
45
password : opts.password
46
allow_empty_password : false # user must have a password
47
cb : (err, is_correct) ->
48
if err
49
cb(err)
50
else if not is_correct
51
# ban opts.account_id from attempting again for 1 minute (say)
52
b = ban[opts.account_id] ?= {}
53
b[opts.user_account_id] = new Date()
54
cb("incorrect password")
55
else
56
cb()
57
(cb) ->
58
# generate token
59
auth_token = random_key.generate(24)
60
# save in db
61
opts.database.save_auth_token
62
account_id : opts.user_account_id
63
auth_token : auth_token
64
ttl : 86400 # ttl in seconds (default: 1 day)
65
cb : cb
66
], (err) ->
67
opts.cb(err, auth_token)
68
)
69
70
exports.revoke_user_auth_token = (opts) ->
71
opts = defaults opts,
72
database : required
73
auth_token : required
74
cb : required
75
types opts,
76
database : types.object.isRequired
77
auth_token : types.string.isRequired
78
cb : types.func.isRequired # cb(err, auth_token)
79
opts.database.delete_auth_token
80
auth_token : opts.auth_token
81
cb : cb
82