-
Notifications
You must be signed in to change notification settings - Fork 0
/
ActionCsrfToken.ts
75 lines (63 loc) · 1.77 KB
/
ActionCsrfToken.ts
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
/// <reference path="Cookies.d.ts" />
/*
CsrfToken manager
ActionCsrfToken.get success: (csrfToken) ->
....
*/
interface CsrfTokenRequest {
success(hash:string);
}
interface CsrfTokenData {
hash: string;
timestamp: number;
ttl: number;
}
export default class ActionCsrfToken {
static csrfToken:CsrfTokenData;
static requestSession(): JQueryXHR {
return jQuery.ajax({
"url": '/=/current_user/csrf',
"error": (resp) => { console.error(resp); }
});
}
/**
* the config.success defines the callback for csrf token response
*/
static get(config:CsrfTokenRequest) {
var cookieCsrf, tokenExpired;
tokenExpired = true;
var csrfToken = ActionCsrfToken.csrfToken;
if (typeof Cookies !== "undefined") {
cookieCsrf = Cookies.get('csrf');
}
if (cookieCsrf) {
return typeof config.success === "function" ? config.success(cookieCsrf) : void 0;
}
if (csrfToken) {
tokenExpired = (new Date).getTime() > (csrfToken.timestamp + csrfToken.ttl) * 1000;
}
if (!tokenExpired) {
return typeof config.success === "function" ? config.success(csrfToken.hash) : void 0;
}
var defer = $.Deferred();
// TODO: handle fail(), always() as well.
ActionCsrfToken.requestSession().done(
(resp) => {
if (resp.error) {
console.error("requestSession error", resp.error);
if (resp.redirect) {
window.location.href = resp.redirect;
}
} else {
console.debug("csrfToken refreshed", resp);
ActionCsrfToken.csrfToken = resp;
if (typeof config.success === "function") {
config.success(ActionCsrfToken.csrfToken.hash);
}
defer.resolve(resp);
}
}
);
return defer;
}
}