All files / src/lib/services user-service.ts

90.15% Statements 119/132
70.73% Branches 29/41
86.36% Functions 19/22
90.77% Lines 118/130

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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 41363x 63x 63x 63x       63x 63x     63x 63x 63x         63x 63x     63x     63x 63x 63x   63x                                                                           63x                                                                 159x 159x 159x 159x 159x 159x 159x 159x 159x           25x 24x 24x 10x 14x   1x         3x   3x   2x 2x 2x     2x     2x 2x 2x                     3x 3x     3x 3x 56x 11x 11x   3x       16x 16x     16x 16x 16x       1x                     51x   51x 43x     51x 51x 1x     50x           50x   48x 8x 8x     48x           48x       53x       55x     55x                       3x   2x   2x       2x   2x             2x       3x 3x 3x   3x   3x               7x       7x 1x         6x     6x 5x   5x 4x 3x 3x   1x                             16x                     21x 21x   11x 2x       10x 9x           1x     19x 19x       5x 5x 5x       12x     9x 9x 9x                                       6x 5x 3x       3x 3x 3x                                                       63x 63x  
import assert from 'assert';
import bcrypt from 'bcryptjs';
import owasp from 'owasp-password-strength-test';
import Joi from 'joi';
 
import { URL } from 'url';
import { Logger } from '../logger';
import User, { IUser } from '../types/user';
import isEmail from '../util/is-email';
import { AccessService } from './access-service';
import ResetTokenService from './reset-token-service';
import InvalidTokenError from '../error/invalid-token-error';
import NotFoundError from '../error/notfound-error';
import OwaspValidationError from '../error/owasp-validation-error';
import { EmailService } from './email-service';
import { IUnleashConfig } from '../types/option';
import SessionService from './session-service';
import { IUnleashStores } from '../types/stores';
import PasswordUndefinedError from '../error/password-undefined';
import { USER_UPDATED, USER_CREATED, USER_DELETED } from '../types/events';
import { IEventStore } from '../types/stores/event-store';
import { IUserSearch, IUserStore } from '../types/stores/user-store';
import { RoleName } from '../types/model';
import SettingService from './setting-service';
import { SimpleAuthSettings } from '../server-impl';
import { simpleAuthKey } from '../types/settings/simple-auth-settings';
import DisabledError from '../error/disabled-error';
import PasswordMismatch from '../error/password-mismatch';
 
const systemUser = new User({ id: -1, username: 'system' });
 
export interface ICreateUser {
    name?: string;
    email?: string;
    username?: string;
    password?: string;
    rootRole: number | RoleName;
}
 
export interface IUpdateUser {
    id: number;
    name?: string;
    email?: string;
    rootRole?: number | RoleName;
}
 
export interface ILoginUserRequest {
    email: string;
    name?: string;
    rootRole?: number | RoleName;
    autoCreate?: boolean;
}
 
interface IUserWithRole extends IUser {
    rootRole: number;
}
interface IRoleDescription {
    description: string;
    name: string;
    type: string;
}
interface ITokenUser extends IUpdateUser {
    createdBy: string;
    token: string;
    role: IRoleDescription;
}
 
const saltRounds = 10;
 
class UserService {
    private logger: Logger;
 
    private store: IUserStore;
 
    private eventStore: IEventStore;
 
    private accessService: AccessService;
 
    private resetTokenService: ResetTokenService;
 
    private sessionService: SessionService;
 
    private emailService: EmailService;
 
    private settingService: SettingService;
 
    constructor(
        stores: Pick<IUnleashStores, 'userStore' | 'eventStore'>,
        {
            getLogger,
            authentication,
        }: Pick<IUnleashConfig, 'getLogger' | 'authentication'>,
        services: {
            accessService: AccessService;
            resetTokenService: ResetTokenService;
            emailService: EmailService;
            sessionService: SessionService;
            settingService: SettingService;
        },
    ) {
        this.logger = getLogger('service/user-service.js');
        this.store = stores.userStore;
        this.eventStore = stores.eventStore;
        this.accessService = services.accessService;
        this.resetTokenService = services.resetTokenService;
        this.emailService = services.emailService;
        this.sessionService = services.sessionService;
        this.settingService = services.settingService;
        Iif (authentication && authentication.createAdminUser) {
            process.nextTick(() => this.initAdminUser());
        }
    }
 
    validatePassword(password: string): boolean {
        if (password) {
            const result = owasp.test(password);
            if (!result.strong) {
                throw new OwaspValidationError(result);
            } else return true;
        } else {
            throw new PasswordUndefinedError();
        }
    }
 
    async initAdminUser(): Promise<void> {
        const userCount = await this.store.count();
 
        if (userCount === 0) {
            // create default admin user
            try {
                const pwd = 'unleash4all';
                this.logger.info(
                    `Creating default user "admin" with password "${pwd}"`,
                );
                const user = await this.store.insert({
                    username: 'admin',
                });
                const passwordHash = await bcrypt.hash(pwd, saltRounds);
                await this.store.setPasswordHash(user.id, passwordHash);
                await this.accessService.setUserRootRole(
                    user.id,
                    RoleName.ADMIN,
                );
            } catch (e) {
                this.logger.error('Unable to create default user "admin"');
            }
        }
    }
 
    async getAll(): Promise<IUserWithRole[]> {
        const users = await this.store.getAll();
        const defaultRole = await this.accessService.getRootRole(
            RoleName.VIEWER,
        );
        const userRoles = await this.accessService.getRootRoleForAllUsers();
        const usersWithRootRole = users.map((u) => {
            const rootRole = userRoles.find((r) => r.userId === u.id);
            const roleId = rootRole ? rootRole.roleId : defaultRole.id;
            return { ...u, rootRole: roleId };
        });
        return usersWithRootRole;
    }
 
    async getUser(id: number): Promise<IUserWithRole> {
        const roles = await this.accessService.getUserRootRoles(id);
        const defaultRole = await this.accessService.getRootRole(
            RoleName.VIEWER,
        );
        const roleId = roles.length > 0 ? roles[0].id : defaultRole.id;
        const user = await this.store.get(id);
        return { ...user, rootRole: roleId };
    }
 
    async search(query: IUserSearch): Promise<IUser[]> {
        return this.store.search(query);
    }
 
    async getByEmail(email: string): Promise<IUser> {
        return this.store.getByQuery({ email });
    }
 
    async createUser(
        { username, email, name, password, rootRole }: ICreateUser,
        updatedBy?: User,
    ): Promise<IUser> {
        assert.ok(username || email, 'You must specify username or email');
 
        if (email) {
            Joi.assert(email, Joi.string().email(), 'Email');
        }
 
        const exists = await this.store.hasUser({ username, email });
        if (exists) {
            throw new Error('User already exists');
        }
 
        const user = await this.store.insert({
            username,
            email,
            name,
        });
 
        await this.accessService.setUserRootRole(user.id, rootRole);
 
        if (password) {
            const passwordHash = await bcrypt.hash(password, saltRounds);
            await this.store.setPasswordHash(user.id, passwordHash);
        }
 
        await this.eventStore.store({
            type: USER_CREATED,
            createdBy: this.getCreatedBy(updatedBy),
            data: this.mapUserToData(user),
        });
 
        return user;
    }
 
    private getCreatedBy(updatedBy: User = systemUser) {
        return updatedBy.username || updatedBy.email;
    }
 
    private mapUserToData(user?: IUser): any {
        Iif (!user) {
            return undefined;
        }
        return {
            id: user.id,
            name: user.name,
            username: user.username,
            email: user.email,
        };
    }
 
    async updateUser(
        { id, name, email, rootRole }: IUpdateUser,
        updatedBy?: User,
    ): Promise<IUser> {
        Joi.assert(email, Joi.string().email(), 'Email');
 
        const preUser = await this.store.get(id);
 
        Iif (rootRole) {
            await this.accessService.setUserRootRole(id, rootRole);
        }
 
        const user = await this.store.update(id, { name, email });
 
        await this.eventStore.store({
            type: USER_UPDATED,
            createdBy: this.getCreatedBy(updatedBy),
            data: this.mapUserToData(user),
            preData: this.mapUserToData(preUser),
        });
 
        return user;
    }
 
    async deleteUser(userId: number, updatedBy?: User): Promise<void> {
        const user = await this.store.get(userId);
        await this.accessService.unlinkUserRoles(userId);
        await this.sessionService.deleteSessionsForUser(userId);
 
        await this.store.delete(userId);
 
        await this.eventStore.store({
            type: USER_DELETED,
            createdBy: this.getCreatedBy(updatedBy),
            preData: this.mapUserToData(user),
        });
    }
 
    async loginUser(usernameOrEmail: string, password: string): Promise<IUser> {
        const settings = await this.settingService.get<SimpleAuthSettings>(
            simpleAuthKey,
        );
 
        if (settings?.disabled) {
            throw new DisabledError(
                'Logging in with username/password has been disabled.',
            );
        }
 
        const idQuery = isEmail(usernameOrEmail)
            ? { email: usernameOrEmail }
            : { username: usernameOrEmail };
        const user = await this.store.getByQuery(idQuery);
        const passwordHash = await this.store.getPasswordHash(user.id);
 
        const match = await bcrypt.compare(password, passwordHash);
        if (match) {
            await this.store.successfullyLogin(user);
            return user;
        }
        throw new PasswordMismatch();
    }
 
    /**
     * Used to login users without specifying password. Used when integrating
     * with external identity providers.
     *
     * @param usernameOrEmail
     * @param autoCreateUser
     * @returns
     */
    async loginUserWithoutPassword(
        email: string,
        autoCreateUser: boolean = false,
    ): Promise<IUser> {
        return this.loginUserSSO({ email, autoCreate: autoCreateUser });
    }
 
    async loginUserSSO({
        email,
        name,
        rootRole,
        autoCreate = false,
    }: ILoginUserRequest): Promise<IUser> {
        let user: IUser;
 
        try {
            user = await this.store.getByQuery({ email });
            // Update user if autCreate is enabled.
            if (name && user.name !== name) {
                user = await this.store.update(user.id, { name, email });
            }
        } catch (e) {
            // User does not exists. Create if "autoCreate" is enabled
            if (autoCreate) {
                user = await this.createUser({
                    email,
                    name,
                    rootRole: rootRole || RoleName.EDITOR,
                });
            } else {
                throw e;
            }
        }
        this.store.successfullyLogin(user);
        return user;
    }
 
    async changePassword(userId: number, password: string): Promise<void> {
        this.validatePassword(password);
        const passwordHash = await bcrypt.hash(password, saltRounds);
        return this.store.setPasswordHash(userId, passwordHash);
    }
 
    async getUserForToken(token: string): Promise<ITokenUser> {
        const { createdBy, userId } = await this.resetTokenService.isValid(
            token,
        );
        const user = await this.getUser(userId);
        const role = await this.accessService.getRoleData(user.rootRole);
        return {
            token,
            createdBy,
            email: user.email,
            name: user.name,
            id: user.id,
            role: {
                description: role.role.description,
                type: role.role.type,
                name: role.role.name,
            },
        };
    }
 
    /**
     * If the password is a strong password will update password and delete all sessions for the user we're changing the password for
     * @param token - the token authenticating this request
     * @param password - new password
     */
    async resetPassword(token: string, password: string): Promise<void> {
        this.validatePassword(password);
        const user = await this.getUserForToken(token);
        const allowed = await this.resetTokenService.useAccessToken({
            userId: user.id,
            token,
        });
        if (allowed) {
            await this.changePassword(user.id, password);
            await this.sessionService.deleteSessionsForUser(user.id);
        } else E{
            throw new InvalidTokenError();
        }
    }
 
    async createResetPasswordEmail(
        receiverEmail: string,
        user: User = systemUser,
    ): Promise<URL> {
        const receiver = await this.getByEmail(receiverEmail);
        Iif (!receiver) {
            throw new NotFoundError(`Could not find ${receiverEmail}`);
        }
        const resetLink = await this.resetTokenService.createResetPasswordUrl(
            receiver.id,
            user.username || user.email,
        );
 
        await this.emailService.sendResetMail(
            receiver.name,
            receiver.email,
            resetLink.toString(),
        );
        return resetLink;
    }
}
 
module.exports = UserService;
export default UserService;