lavkach3

Форк
0
244 строки · 7.4 Кб
1
var cache = {};
2

3
const Singleton = {
4
    secret: 'Singleton',
5
    temp: [],
6
    results: {},
7
    async pushUUID(model, uuid) {
8
        let modelList = this.temp[model]
9
        if (!modelList) {
10
            this.temp[model] = []
11
            this.temp[model].push(uuid)
12
        } else {
13
            if (!this.temp[model].includes(uuid)) {
14
                this.temp[model].push(uuid)
15
            }
16
        }
17
    },
18
    async run() {
19
        console.log('Бесконечно идем в цикл');
20
        while (true) {
21
            let promises = []
22
            for (let model in this.temp) {
23
                if (this.temp[model].length > 0) {
24
                    ids_str = this.temp[model].join(',')
25
                    const items = fetch('/base/get_by_ids?model=' + model + '&id__in=' + encodeURIComponent(ids_str));
26
                    promises.push(items)
27
                } else {
28
                    continue
29
                }
30
                this.temp[model] = []
31
            }
32
            for (let i = 0; i < promises.length; i++) {
33
                const item = await promises[i]
34
                const results = await item.json();
35
                for (let i = 0; i < results.length; i++) {
36
                    this.results[results[i].value] = results[i].label
37
                }
38
            }
39
            await new Promise(r => setTimeout(r, 300));
40
            if (this.results.length > 2000) {
41
                this.results.splice(0, 100);
42
            }
43
        }
44
    }
45
};
46

47
// Заморозим объект на века
48
Object.freeze(Singleton);
49

50
Singleton.run()
51

52
function getCookieValue(name) {
53
    const nameString = name + "="
54

55
    const values = document.cookie.split(";").filter(item => {
56
        return item.includes(nameString)
57
    })
58
    if (values.length) {
59
        let value = []
60
        for (let val in values) {
61
            let is_value = values[val].split('=').filter(item => {
62
                return item.replace(' ', '') === name
63
            })
64
            if (is_value.length) {
65
                value = values[val]
66
                break
67
            }
68
        }
69
        if (value.length) {
70
            return value.substring(nameString.length, value.length).replace('=', '')
71
        }
72
    } else {
73
        return null
74
    }
75
}
76

77
function removeCookie(sKey, sPath, sDomain) {
78
    document.cookie = encodeURIComponent(sKey) +
79
        "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" +
80
        (sDomain ? "; domain=" + sDomain : "") +
81
        (sPath ? "; path=" + sPath : "/");
82
}
83

84
function parseJwt(token) {
85
    var base64Url = token.split('.')[1];
86
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
87
    var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function (c) {
88
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
89
    }).join(''));
90

91
    return JSON.parse(jsonPayload);
92
}
93

94
// auth is a promise returned by our authentication system
95

96
// await the auth token and store it somewhere
97

98
var authToken = null
99
// gate htmx requests on the auth token
100
htmx.on("htmx:confirm", (e) => {
101
    let authToken = getCookieValue('token');
102
    // if there is no auth token
103
    if (authToken == null && !window.location.pathname.includes('login')) {
104
        e.preventDefault()
105

106
        window.history.pushState('Login', 'Login', '/basic/user/login');
107
        console.log('redirect login')
108
        document.location.replace('/basic/user/login')
109
        //console.log(authToken)
110
    }
111
});
112

113
async function refreshToken() {
114
    let user = {
115
        token: getCookieValue('token').replace('=', ''),
116
        refresh_token: getCookieValue('refresh_token').replace('=', '')
117
    };
118
    console.log('refreshing token')
119
    let response = await fetch('/basic/user/refresh', {
120
        method: 'POST',
121
        headers: {
122
            'Content-Type': 'application/json'
123
        },
124
        body: JSON.stringify(user)
125
    });
126
    let result = await response.json();
127
    const parsed = parseJwt(result.token)
128
    const expires = await new Date(parsed.exp * 1000)
129
    document.cookie = "token=" + result.token + "; expires=" + expires + ";path=/;"
130
    document.cookie = "refresh_token=" + result.token + "; expires=" + expires + ";path=/;"
131
    return true
132

133
}
134

135
async function checkAuth() {
136
    var authToken = getCookieValue('token')
137
    if (!authToken) {
138
        authToken = getCookieValue('refresh_token')
139
        if (authToken) {
140
            authToken = refreshToken()
141
            authToken = getCookieValue('token')
142
        }
143
    }
144
    if (!authToken) {
145
        return false
146
    }
147
    var tokenData = parseJwt(authToken)
148
    var now = Date.now() / 1000
149
    if (tokenData.exp <= now) {
150
        await refreshToken()
151
    }
152
    return true
153
}
154

155
// add the auth token to the request as a header
156
htmx.on("htmx:configRequest", (e) => {
157
    //e.detail.headers["AUTH"] = authToken
158

159
    console.log('check cookie')
160
    const res = checkAuth()
161
    e.detail.headers["Authorization"] = getCookieValue('token')
162
})
163
htmx.on("htmx:afterRequest", (e) => {
164

165
    //e.detail.headers["AUTH"] = authToken
166
    if (authToken == null) {
167
        //console.log('afterRequest')
168
        if (e.detail.xhr.status || 200) {
169
            e.detail.shouldSwap = true;
170
            e.detail.isError = false;
171
        }
172
    }
173
})
174
htmx.on('htmx:beforeSwap', function (evt) {
175

176
    if (evt.detail.xhr.status === 200) {
177
        // do nothing
178
    } else if (evt.detail.xhr.status === 404) {
179
        // alert the user when a 404 occurs (maybe use a nicer mechanism than alert())
180
        var myToast = Toastify({
181
            text: evt.detail.pathInfo.requestPath + ' + ' + evt.detail.xhr.responseText,
182
            duration: 3000,
183
            close: true,
184
            style: {
185
                background: "#e94e1d",
186
            },
187

188
        })
189
        myToast.showToast();
190
    } else if (evt.detail.xhr.status === 403) {
191
        // Запрещено
192
        console.log('403')
193
        var message = evt.detail.xhr.responseText.replace(/\\n/g, '\n')
194
        var myToast = Toastify({
195
            text: message,
196
            duration: 3000,
197
            style: {
198
                background: "red",
199
            },
200
        })
201
        myToast.showToast();
202
    } else if (evt.detail.xhr.status === 401 && !window.location.pathname.includes('login')) {
203
        // Запрещено
204

205
        window.history.pushState('Login', 'Login', '/basic/user/login' + "?next=" + window.location.pathname);
206
        htmx.ajax('GET', '/basic/user/login', {
207
            target: '#htmx_content', headers: {
208
                'HX-Replace-Url': 'true'
209
            }
210
        })
211
    } else if (evt.detail.xhr.status === 418) {
212
        // if the response code 418 (I'm a teapot) is returned, retarget the
213
        // content of the response to the element with the id `teapot`
214
        evt.detail.shouldSwap = true;
215
        evt.detail.target = htmx.find("#teapot");
216

217
    } else {
218
        var myToast = Toastify({
219
            text: evt.detail.xhr.responseText,
220
            duration: 3000,
221
            close: true,
222
            style: {
223
                background: "#e94e1d",
224
            },
225

226
        })
227
        myToast.showToast();
228
    }
229
});
230
//htmx.logger = function (elt, event, data) {
231
//    if (console) {
232
//        console.log(event, elt, data);
233
//    }
234
//};
235
htmx.on('htmx:wsConfigReceive', (e) => {
236
    console.log('wsConfigReceive')
237
    console.log(e);
238
    e.detail.headers["Authorization"] = getCookieValue('token')
239
})
240
htmx.on('htmx:wsConfigSend', (e) => {
241
    console.log('wsConfigSend')
242
    console.log(e);
243
    e.detail.headers["Authorization"] = getCookieValue('token')
244
})

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.