<commit_before>import {logger} from '../logger';
import * as colors from 'colors';
import {Request, Response} from 'express';
import {Headers} from './headers';
import {ErrorResponse} from '../../../commons/RamAPI';
import {CreateIdentityDTO} from '../../../commons/RamAPI';
import {IIdentity, IdentityModel} from '../models/identity.model';
import {DOB_SHARED_SECRET_TYPE_CODE} from '../models/sharedSecretType.model';

class Security {

    public prepareRequest():(req:Request, res:Response, next:() => void) => void {
        return (req:Request, res:Response, next:() => void) => {
            const idValue = this.getIdValue(req, res);
            if (idValue) {
                // id supplied, try to lookup and if not found create a new identity before carrying on
                IdentityModel.findByIdValue(idValue)
                    .then(this.createIdentityIfNotFound(req, res))
                    .then(this.prepareResponseLocals(req, res, next), this.reject(res, next));
            } else {
                // id not supplied, carry on
                Promise.resolve(null)
                    .then(this.prepareResponseLocals(req, res, next), this.reject(res, next));
            }
        };
    }

    /**
     * Attempts to provide an Identity Value by looking in the following:
     *  header,
     *  locals,
     *  cookie
     */
    private getIdValue(req:Request, res:Response):string {

        // if the header contains identity the return that
        if(req.get(Headers.IdentityIdValue)) {
            console.log('found header', req.get(Headers.IdentityIdValue));
           return req.get(Headers.IdentityIdValue);
        }

        // check locals
        if(res.locals[Headers.IdentityIdValue]) {
            console.log('found local', res.locals[Headers.IdentityIdValue]);
            return res.locals[Headers.IdentityIdValue];
        }

        // check cookie - case insensitive match
        return SecurityHelper.getIdentityIdValueFromCookies(req);

    }

    /* tslint:disable:max-func-body-length */
    private createIdentityIfNotFound(req:Request, res:Response) {
        return (identity?:IIdentity) => {
            const rawIdValue = req.get(Headers.IdentityRawIdValue);
            if (identity) {
                logger.info('Identity context: Using existing identity ...');
                return Promise.resolve(identity);
            } else if (!rawIdValue) {
                logger.info('Identity context: Unable to create identity as raw id value was not supplied ...'.red);
                return Promise.resolve(null);
            } else {
                const dto = new CreateIdentityDTO(
                    rawIdValue,
                    req.get(Headers.PartyType),
                    req.get(Headers.GivenName),
                    req.get(Headers.FamilyName),
                    req.get(Headers.UnstructuredName),
                    DOB_SHARED_SECRET_TYPE_CODE,
                    req.get(Headers.DOB),<commit_msg>Minor<commit_after>import {logger} from '../logger';
import * as colors from 'colors';
import {Request, Response} from 'express';
import {Headers} from './headers';
import {ErrorResponse} from '../../../commons/RamAPI';
import {CreateIdentityDTO} from '../../../commons/RamAPI';
import {IIdentity, IdentityModel} from '../models/identity.model';
import {DOB_SHARED_SECRET_TYPE_CODE} from '../models/sharedSecretType.model';

class Security {

    public prepareRequest():(req:Request, res:Response, next:() => void) => void {
        return (req:Request, res:Response, next:() => void) => {
            const idValue = this.getIdValue(req, res);
            if (idValue) {
                // id supplied, try to lookup and if not found create a new identity before carrying on
                IdentityModel.findByIdValue(idValue)
                    .then(this.createIdentityIfNotFound(req, res))
                    .then(this.prepareResponseLocals(req, res, next), this.reject(res, next));
            } else {
                // id not supplied, carry on
                Promise.resolve(null)
                    .then(this.prepareResponseLocals(req, res, next), this.reject(res, next));
            }
        };
    }

    /**
     * Attempts to provide an Identity Value by looking in the following:
     *  header,
     *  locals,
     *  cookie
     */
    private getIdValue(req:Request, res:Response):string {

        // look for id in headers
        if(req.get(Headers.IdentityIdValue)) {
            console.log('found header', req.get(Headers.IdentityIdValue));
           return req.get(Headers.IdentityIdValue);
        }

        // look for id in locals
        if(res.locals[Headers.IdentityIdValue]) {
            console.log('found local', res.locals[Headers.IdentityIdValue]);
            return res.locals[Headers.IdentityIdValue];
        }

        // look for id in cookies
        return SecurityHelper.getIdentityIdValueFromCookies(req);

    }

    /* tslint:disable:max-func-body-length */
    private createIdentityIfNotFound(req:Request, res:Response) {
        return (identity?:IIdentity) => {
            const rawIdValue = req.get(Headers.IdentityRawIdValue);
            if (identity) {
                logger.info('Identity context: Using existing identity ...');
                return Promise.resolve(identity);
            } else if (!rawIdValue) {
                logger.info('Identity context: Unable to create identity as raw id value was not supplied ...'.red);
                return Promise.resolve(null);
            } else {
                const dto = new CreateIdentityDTO(
                    rawIdValue,
                    req.get(Headers.PartyType),
                    req.get(Headers.GivenName),
                    req.get(Headers.FamilyName),
                    req.get(Headers.UnstructuredName),
                    DOB_SHARED_SECRET_TYPE_CODE,
                    req.get(Headers.DOB),
{'fraction_non_alphanumeric': 0.11714141243890107, 'fraction_numerical': 0.0, 'mean_word_length': 2.0571870170015454, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6715485', 'n_tokens_mistral': 1584, 'n_tokens_neox': 1530, 'n_words': 369}