Software /
code /
prosody
Comparison
plugins/mod_tokenauth.lua @ 11120:b2331f3dfeea
Merge 0.11->trunk
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Wed, 30 Sep 2020 09:50:33 +0100 |
parent | 10675:5efd6865486c |
child | 12649:86e1187f6274 |
comparison
equal
deleted
inserted
replaced
11119:68df52bf08d5 | 11120:b2331f3dfeea |
---|---|
1 local id = require "util.id"; | |
2 local jid = require "util.jid"; | |
3 local base64 = require "util.encodings".base64; | |
4 | |
5 local token_store = module:open_store("auth_tokens", "map"); | |
6 | |
7 function create_jid_token(actor_jid, token_jid, token_scope, token_ttl) | |
8 token_jid = jid.prep(token_jid); | |
9 if not actor_jid or token_jid ~= actor_jid and not jid.compare(token_jid, actor_jid) then | |
10 return nil, "not-authorized"; | |
11 end | |
12 | |
13 local token_username, token_host, token_resource = jid.split(token_jid); | |
14 | |
15 if token_host ~= module.host then | |
16 return nil, "invalid-host"; | |
17 end | |
18 | |
19 local token_info = { | |
20 owner = actor_jid; | |
21 created = os.time(); | |
22 expires = token_ttl and (os.time() + token_ttl) or nil; | |
23 jid = token_jid; | |
24 session = { | |
25 username = token_username; | |
26 host = token_host; | |
27 resource = token_resource; | |
28 | |
29 auth_scope = token_scope; | |
30 }; | |
31 }; | |
32 | |
33 local token_id = id.long(); | |
34 local token = base64.encode("1;"..jid.join(token_username, token_host)..";"..token_id); | |
35 token_store:set(token_username, token_id, token_info); | |
36 | |
37 return token, token_info; | |
38 end | |
39 | |
40 local function parse_token(encoded_token) | |
41 local token = base64.decode(encoded_token); | |
42 if not token then return nil; end | |
43 local token_jid, token_id = token:match("^1;([^;]+);(.+)$"); | |
44 if not token_jid then return nil; end | |
45 local token_user, token_host = jid.split(token_jid); | |
46 return token_id, token_user, token_host; | |
47 end | |
48 | |
49 function get_token_info(token) | |
50 local token_id, token_user, token_host = parse_token(token); | |
51 if not token_id then | |
52 return nil, "invalid-token-format"; | |
53 end | |
54 if token_host ~= module.host then | |
55 return nil, "invalid-host"; | |
56 end | |
57 | |
58 local token_info, err = token_store:get(token_user, token_id); | |
59 if not token_info then | |
60 if err then | |
61 return nil, "internal-error"; | |
62 end | |
63 return nil, "not-authorized"; | |
64 end | |
65 | |
66 if token_info.expires and token_info.expires < os.time() then | |
67 return nil, "not-authorized"; | |
68 end | |
69 | |
70 return token_info | |
71 end | |
72 | |
73 function revoke_token(token) | |
74 local token_id, token_user, token_host = parse_token(token); | |
75 if not token_id then | |
76 return nil, "invalid-token-format"; | |
77 end | |
78 if token_host ~= module.host then | |
79 return nil, "invalid-host"; | |
80 end | |
81 return token_store:set(token_user, token_id, nil); | |
82 end |