All files / src/lib/middleware demo-authentication.ts

91.3% Statements 21/23
62.5% Branches 5/8
100% Functions 5/5
91.3% Lines 21/23

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  61x     61x 61x               10x 7x 7x 7x         7x 7x               10x   11x   8x   11x     10x   9x                   9x     10x   20x 17x   3x                           61x  
import { Application } from 'express';
import AuthenticationRequired from '../types/authentication-required';
import { IUnleashServices } from '../types/services';
import { IUnleashConfig } from '../types/option';
import ApiUser from '../types/api-user';
import { ApiTokenType } from '../types/models/api-token';
 
function demoAuthentication(
    app: Application,
    basePath: string = '', // eslint-disable-line
    { userService }: Pick<IUnleashServices, 'userService'>,
    { authentication }: Pick<IUnleashConfig, 'authentication'>,
): void {
    app.post(`${basePath}/auth/demo/login`, async (req, res) => {
        const { email } = req.body;
        try {
            const user = await userService.loginUserWithoutPassword(
                email,
                true,
            );
            //@ts-ignore
            req.session.user = user;
            return res.status(200).json(user);
        } catch (e) {
            res.status(400)
                .json({ error: `Could not sign in with ${email}` })
                .end();
        }
    });
 
    app.use(`${basePath}/api/admin/`, (req, res, next) => {
        // @ts-ignore
        if (req.session.user && req.session.user.email) {
            // @ts-ignore
            req.user = req.session.user;
        }
        next();
    });
 
    app.use(`${basePath}/api/client`, (req, res, next) => {
        // @ts-ignore
        Iif (!authentication.enableApiToken && !req.user) {
            // @ts-ignore
            req.user = new ApiUser({
                username: 'unauthed-default-client',
                permissions: [],
                environment: 'default',
                type: ApiTokenType.CLIENT,
                project: '*',
            });
        }
        next();
    });
 
    app.use(`${basePath}/api`, (req, res, next) => {
        // @ts-ignore
        if (req.user) {
            return next();
        }
        return res
            .status(401)
            .json(
                new AuthenticationRequired({
                    path: `${basePath}/auth/demo/login`,
                    type: 'demo',
                    message:
                        'You have to identify yourself in order to use Unleash.',
                }),
            )
            .end();
    });
}
 
export default demoAuthentication;