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

78.57% Statements 11/14
60% Branches 3/5
100% Functions 3/3
78.57% Lines 11/14

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    61x     2x 1x           2x     2x       2x 1x   1x         1x 1x       61x  
import { Application, NextFunction, Response } from 'express';
import { IAuthRequest } from '../routes/unleash-types';
import AuthenticationRequired from '../types/authentication-required';
 
function ossAuthHook(app: Application, baseUriPath: string): void {
    const generateAuthResponse = async () =>
        new AuthenticationRequired({
            type: 'password',
            path: `${baseUriPath}/auth/simple/login`,
            message: 'You must sign in order to use Unleash',
        });
 
    app.use(
        `${baseUriPath}/api`,
        async (req: IAuthRequest, res: Response, next: NextFunction) => {
            Iif (req.session && req.session.user) {
                req.user = req.session.user;
                return next();
            }
            if (req.user) {
                return next();
            }
            Iif (req.header('authorization')) {
                // API clients should get 401 without body
                return res.sendStatus(401);
            }
            // Admin UI users should get auth-response
            const authRequired = await generateAuthResponse();
            return res.status(401).json(authRequired);
        },
    );
}
export default ossAuthHook;