-
Notifications
You must be signed in to change notification settings - Fork 10
/
contextProvider.ts
109 lines (83 loc) · 2.94 KB
/
contextProvider.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import {IHttpContextProvider, IHttpRequest, IHttpResponse} from 'queueit-knownuser/dist/HttpContextProvider'
export default class CloudflareHttpContextProvider implements IHttpContextProvider {
_httpRequest: RequestProvider;
_httpResponse: ResponseProvider;
_outputCookie: string;
isError: boolean;
constructor(public request: any, public bodyString: string) {
this._httpRequest = new RequestProvider(this);
this._httpResponse = new ResponseProvider(this);
}
public getHttpRequest() {
return this._httpRequest;
}
public getHttpResponse() {
return this._httpResponse;
}
public setOutputCookie(setCookie: string) {
this._outputCookie = setCookie;
}
public getOutputCookie() {
return this._outputCookie;
}
}
class RequestProvider implements IHttpRequest {
_parsedCookieDic: Record<string, string>;
constructor(private _context: CloudflareHttpContextProvider) {
}
public getUserAgent() {
return this.getHeader("user-agent");
}
public getHeader(name: string) {
return this._context.request.headers.get(name) || "";
}
public getAbsoluteUri() {
return this._context.request.url;
}
public getUserHostAddress() {
return this.getHeader("cf-connecting-ip");
}
public getCookieValue(name: string) {
if (!this._parsedCookieDic) {
this._parsedCookieDic = this.__parseCookies(this.getHeader('cookie'));
}
var cookieValue = this._parsedCookieDic[name];
if (cookieValue)
return decodeURIComponent(cookieValue);
return cookieValue;
}
public getRequestBodyAsString() {
return this._context.bodyString;
}
private __parseCookies(cookieValue: string) {
let parsedCookie = {};
cookieValue.split(';').forEach(function (cookie) {
if (cookie) {
var parts = cookie.split('=');
if (parts.length >= 2)
parsedCookie[parts[0].trim()] = parts[1].trim();
}
});
return parsedCookie;
}
}
class ResponseProvider implements IHttpResponse {
constructor(private _context: CloudflareHttpContextProvider) {
}
public setCookie(cookieName: string, cookieValue: string, domain: string, expiration: number, httpOnly: boolean, isSecure: boolean) {
// expiration is in secs, but Date needs it in milisecs
let expirationDate = new Date(expiration * 1000);
let setCookieString = `${cookieName}=${encodeURIComponent(cookieValue)}; expires=${expirationDate.toUTCString()};`;
if (domain) {
setCookieString += ` domain=${domain};`;
}
if (httpOnly) {
setCookieString += ' HttpOnly;'
}
if (isSecure) {
setCookieString += ' Secure;'
}
setCookieString += " path=/";
this._context.setOutputCookie(setCookieString);
}
}