1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-06-04 01:18:20 +02:00
unleash.unleash/src/lib/middleware/demo-authentication.ts
Gastón Fournier 1724219487
feat: encrypt emails at rest for demo login (#5759)
## About the changes
This allows us to encrypt emails at signup for demo users to further
secure our demo instance. Currently, emails are anonymized before
displaying events performed by demo users. But this means that emails
are stored at rest in our DB. By encrypting the emails at login, we're
adding another layer of protection.

This can be enabled with a flag and requires the encryption key and the
initialization vector (IV for short) to be present as environment
variables.
2024-01-05 14:21:20 +01:00

79 lines
2.4 KiB
TypeScript

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';
import { IAuthRequest } from 'lib/server-impl';
import { IApiRequest } from 'lib/routes/unleash-types';
import { encrypt } from '../util';
function demoAuthentication(
app: Application,
basePath: string,
{ userService }: Pick<IUnleashServices, 'userService'>,
{
authentication,
flagResolver,
}: Pick<IUnleashConfig, 'authentication' | 'flagResolver'>,
): void {
app.post(`${basePath}/auth/demo/login`, async (req: IAuthRequest, res) => {
let { email } = req.body;
email = flagResolver.isEnabled('encryptEmails', { email })
? encrypt(email)
: email;
try {
const user = await userService.loginUserWithoutPassword(
email,
true,
);
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: IAuthRequest, res, next) => {
if (req.session.user?.email) {
req.user = req.session.user;
}
next();
});
app.use(`${basePath}/api/client`, (req: IApiRequest, res, next) => {
if (!authentication.enableApiToken && !req.user) {
req.user = new ApiUser({
tokenName: 'unauthed-default-client',
permissions: [],
environment: 'default',
type: ApiTokenType.CLIENT,
project: '*',
secret: 'a',
});
}
next();
});
app.use(`${basePath}/api`, (req: IAuthRequest, res, next) => {
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;