All files / src/endpoint/html create-session.ts

28.13% Statements 9/32
100% Branches 0/0
0% Functions 0/6
28.13% Lines 9/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  2x 2x 2x 2x 2x 2x 2x 2x                                                                                                                                                             2x  
import Node from 'type/node';
import SystemId from 'system/enum/id';
import HttpHeader from 'http/enum/header';
import buildCookie from 'http/utility/build-cookie';
import HtmlEndpoint from 'endpoint/html';
import TimeInterval from 'enum/time-interval';
import KeyGenerator from 'utility/key-generator';
import FetchAccountOperation from 'operation/fetch-account';
import CreateInstanceOperation from 'operation/create-instance';
 
interface Input {
	readonly username: string;
	readonly password: string;
}
 
class HtmlCreateSessionEndpoint extends HtmlEndpoint<Input> {
	protected async process(): Promise<void> {
		const account = await this.fetchAccount();
		const session = await this.createSession(account);
 
		this.setCookieFromSession(session);
		this.redirectToUrl('/');
	}
 
	private async fetchAccount(): Promise<Node> {
		const repository = this.getRepository();
		const account = await repository.fetchSystemAccount();
 
		const credentials = {
			username: this.getUsername(),
			password: this.getPassword()
		};
 
		const input = {
			credentials,
			repository,
			account
		};
 
		const operation = new FetchAccountOperation(input);
 
		return operation.perform();
	}
 
	private async createSession(account: Node): Promise<Node> {
		const id = KeyGenerator.id();
		const repository = this.getRepository();
		const system_account = await repository.fetchSystemAccount();
		const account_url = repository.buildNodeUrl(account);
 
		const input = {
			id,
			type_id: SystemId.SESSION_TYPE,
			fields: [
				{
					key: 'account',
					value: account_url
				}
			],
			repository,
			account: system_account
		};
 
		const operation = new CreateInstanceOperation(input);
 
		return operation.perform();
	}
 
	private setCookieFromSession(session: Node): void {
		const cookie = buildCookie(session.id, TimeInterval.ONE_DAY);
 
		this.setHeaderValue(HttpHeader.SET_COOKIE, cookie);
	}
 
	private getUsername(): string {
		const request_body = this.getRequestBody();
 
		return request_body.username;
	}
 
	private getPassword(): string {
		const request_body = this.getRequestBody();
 
		return request_body.password;
	}
}
 
export default HtmlCreateSessionEndpoint;