1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | const TOKEN_COOKIE_NAME = 'ckCsrfToken';
|
10 | const TOKEN_LENGTH = 40;
|
11 | const tokenCharset = 'abcdefghijklmnopqrstuvwxyz0123456789';
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | export function getCsrfToken() {
|
18 | let token = getCookie(TOKEN_COOKIE_NAME);
|
19 | if (!token || token.length != TOKEN_LENGTH) {
|
20 | token = generateToken(TOKEN_LENGTH);
|
21 | setCookie(TOKEN_COOKIE_NAME, token);
|
22 | }
|
23 | return token;
|
24 | }
|
25 |
|
26 |
|
27 |
|
28 | export function getCookie(name) {
|
29 | name = name.toLowerCase();
|
30 | const parts = document.cookie.split(';');
|
31 | for (const part of parts) {
|
32 | const pair = part.split('=');
|
33 | const key = decodeURIComponent(pair[0].trim().toLowerCase());
|
34 | if (key === name) {
|
35 | return decodeURIComponent(pair[1]);
|
36 | }
|
37 | }
|
38 | return null;
|
39 | }
|
40 |
|
41 |
|
42 |
|
43 | export function setCookie(name, value) {
|
44 | document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';path=/';
|
45 | }
|
46 |
|
47 |
|
48 |
|
49 | function generateToken(length) {
|
50 | let result = '';
|
51 | const randValues = new Uint8Array(length);
|
52 | window.crypto.getRandomValues(randValues);
|
53 | for (let j = 0; j < randValues.length; j++) {
|
54 | const character = tokenCharset.charAt(randValues[j] % tokenCharset.length);
|
55 | result += Math.random() > 0.5 ? character.toUpperCase() : character;
|
56 | }
|
57 | return result;
|
58 | }
|