ckn.server
Version:
88 lines (83 loc) • 2.82 kB
JavaScript
import { ckn } from "ckn";
class CKNSession {
constructor(request, response) {
this.request = request;
this.response = response;
this.rootPath = "";
ckn.loop((this.request.originalUrl.match(/\//g) || []).length, i => {
this.rootPath += "../";
});
}
checkBearerAuthentication = (token) => {
let authen = this.request.header("Authorization");
return authen == "Bearer " + token;
}
send = async (dataOrStatus, obj = null) => {
if (typeof dataOrStatus === "number") {
let tmp = this.response.status(dataOrStatus);
if (obj) {
tmp.send(obj);
}
}
else {
this.response.send(dataOrStatus);
}
return this.response;
}
sendStatus = async (code) => {
await this.response.sendStatus(code);
}
render = async (view, data) => {
if (data == null) data = {};
data.session = this;
data.self = data;
this.response.render(view, data);
}
redirect = (url) => {
this.response.redirect(url);
}
fullUrl = () => {
let req = this.request;
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
return fullUrl;
}
url = () => {
let req = this.request;
let fullUrl = req.protocol + '://' + req.get('host');
return fullUrl;
}
cookies = {
set: (key, value) => {
const oneDayToSeconds = 24 * 60 * 60;
this.response.cookie(key, value,
{
maxAge: oneDayToSeconds,
// You can't access these tokens in the client's javascript
httpOnly: true,
// Forces to use https in production
secure: process.env.NODE_ENV === 'production' ? true : false
}
);
},
get: (key) => {
// We extract the raw cookies from the request headers
let rawCookies = this.request.headers.cookie;
if (rawCookies != null) {
rawCookies = rawCookies.split('; ');
// rawCookies = ['myapp=secretcookie, 'analytics_cookie=beacon;']
const parsedCookies = {};
rawCookies.forEach(rawCookie => {
const parsedCookie = rawCookie.split('=');
// parsedCookie = ['myapp', 'secretcookie'], ['analytics_cookie', 'beacon']
parsedCookies[parsedCookie[0]] = parsedCookie[1];
});
return parsedCookies[key];
}
return null;
},
remove: (key) => {
this.response.clearCookie(key);
}
}
}
export { CKNSession };