1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-25 00:07:47 +01:00
unleash.unleash/src/lib/services/user-service.ts

476 lines
15 KiB
TypeScript
Raw Normal View History

2022-01-06 20:43:57 +01:00
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, IUserWithRootRole } 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 { IAuthOption, 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,
UserCreatedEvent,
UserUpdatedEvent,
UserDeletedEvent,
} from '../types/events';
import { IUserStore } from '../types/stores/user-store';
import { RoleName } from '../types/model';
import SettingService from './setting-service';
import { SimpleAuthSettings } from '../server-impl';
import { simpleAuthSettingsKey } from '../types/settings/simple-auth-settings';
import DisabledError from '../error/disabled-error';
import BadDataError from '../error/bad-data-error';
import { isDefined } from '../util/isDefined';
import { TokenUserSchema } from '../openapi/spec/token-user-schema';
Clean up old errors (#3633) This PR attempts to improve the error handling introduced in #3607. ## About the changes ## **tl;dr:** - Make `UnleashError` constructor protected - Make all custom errors inherit from `UnleashError`. - Add tests to ensure that all special error cases include their relevant data - Remove `PasswordMismatchError` and `BadRequestError`. These don't exist. - Add a few new error types: `ContentTypeError`, `NotImplementedError`, `UnauthorizedError` - Remove the `...rest` parameter from error constructor - Add an unexported `GenericUnleashError` class - Move OpenAPI conversion function to `BadDataError` clas - Remove explicit `Error.captureStackTrace`. This is done automatically. - Extract `getPropFromString` function and add tests ### **In a more verbose fashion** The main thing is that all our internal errors now inherit from`UnleashError`. This allows us to simplify the `UnleashError` constructor and error handling in general while still giving us the extra benefits we added to that class. However, it _does_ also mean that I've had to update **all** existing error classes. The constructor for `UnleashError` is now protected and all places that called that constructor directly have been updated. Because the base error isn't available anymore, I've added three new errors to cover use cases that we didn't already have covered: `NotImplementedError`, `UnauthorizedError`, `ContentTypeError`. This is to stay consistent in how we report errors to the user. There is also an internal class, `GenericUnleashError` that inherits from the base error. This class is only used in conversions for cases where we don't know what the error is. It is not exported. In making all the errors inherit, I've also removed the `...rest` parameter from the `UnleashError` constructor. We don't need this anymore. Following on from the fixes with missing properties in #3638, I have added tests for all errors that contain extra data. Some of the error names that were originally used when creating the list don't exist in the backend. `BadRequestError` and `PasswordMismatchError` have been removed. The `BadDataError` class now contains the conversion code for OpenAPI validation errors. In doing so, I extracted and tested the `getPropFromString` function. ### Main files Due to the nature of the changes, there's a lot of files to look at. So to make it easier to know where to turn your attention: The changes in `api-error.ts` contain the main changes: protected constructor, removal of OpenAPI conversion (moved into `BadDataError`. `api-error.test.ts` contains tests to make sure that errors work as expected. Aside from `get-prop-from-string.ts` and the tests, everything else is just the required updates to go through with the changes. ## Discussion points I've gone for inheritance of the Error type over composition. This is in large part because throwing actual Error instances instead of just objects is preferable (because they collect stack traces, for instance). However, it's quite possible that we could solve the same thing in a more elegant fashion using composition. ## For later / suggestions for further improvements The `api-error` files still contain a lot of code. I think it might be beneficial to break each Error into a separate folder that includes the error, its tests, and its schema (if required). It would help decouple it a bit. We don't currently expose the schema anywhere, so it's not available in the openapi spec. We should look at exposing it too. Finally, it would be good to go through each individual error message and update each one to be as helpful as possible.
2023-05-11 11:10:57 +02:00
import PasswordMismatch from '../error/password-mismatch';
import EventService from './event-service';
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;
}
const saltRounds = 10;
class UserService {
private logger: Logger;
private store: IUserStore;
private eventService: EventService;
private accessService: AccessService;
private resetTokenService: ResetTokenService;
private sessionService: SessionService;
private emailService: EmailService;
private settingService: SettingService;
private passwordResetTimeouts: { [key: string]: NodeJS.Timeout } = {};
feat: unify error responses (#3607) This PR implements the first version of a suggested unification (and documentation) of the errors that we return from the API today. The goal is for this to be the first step towards the error type defined in this internal [linear task](https://linear.app/unleash/issue/1-629/define-the-error-type 'Define the new API error type'). ## The state of things today As things stand, we currently have no (or **very** little) documentation of the errors that are returned from the API. We mention error codes, but never what the errors may contain. Second, there is no specified format for errors, so what they return is arbitrary, and based on ... Who knows? As a result, we have multiple different errors returned by the API depending on what operation you're trying to do. What's more, with OpenAPI validation in the mix, it's absolutely possible for you to get two completely different error objects for operations to the same endpoint. Third, the errors we do return are usually pretty vague and don't really provide any real help to the user. "You don't have the right permissions". Great. Well what permissions do I need? And how would I know? "BadDataError". Sick. Why is it bad? ... You get it. ## What we want to achieve The ultimate goal is for error messages to serve both humans and machines. When the user provides bad data, we should tell them what parts of the data are bad and what they can do to fix it. When they don't have the right permissions, we should tell them what permissions they need. Additionally, it would be nice if we could provide an ID for each error instance, so that you (or an admin) can look through the logs and locate he incident. ## What's included in **this** PR? This PR does not aim to implement everything above. It's not intended to magically fix everything. Its goal is to implement the necessary **breaking** changes, so that they can be included in v5. Changing error messages is a slightly grayer area than changing APIs directly, but changing the format is definitely something I'd consider breaking. So this PR: - defines a minimal version of the error type defined in the [API error definition linear task](https://linear.app/unleash/issue/1-629/define-the-error-type). - aims to catch all errors we return today and wrap them in the error type - updates tests to match the new expectations. An important point: because we are cutting v5 very soon and because work for this wasn't started until last week, the code here isn't necessarily very polished. But it doesn't need to be. The internals can be as messy as we want, as long as the API surface is stable. That said, I'm very open to feedback about design and code completeness, etc, but this has intentionally been done quickly. Please also see my inline comments on the changes for more specific details. ### Proposed follow-ups As mentioned, this is the first step to implementing the error type. The public API error type only exposes `id`, `name`, and `message`. This is barely any more than most of the previous messages, but they are now all using the same format. Any additional properties, such as `suggestion`, `help`, `documentationLink` etc can be added as features without breaking the current format. This is an intentional limitation of this PR. Regarding additional properties: there are some error responses that must contain extra properties. Some of these are documented in the types of the new error constructor, but not all. This includes `path` and `type` properties on 401 errors, `details` on validation errors, and more. Also, because it was put together quickly, I don't yet know exactly how we (as developers) would **prefer** to use these new error messages within the code, so the internal API (the new type, name, etc), is just a suggestion. This can evolve naturally over time if (based on feedback and experience) without changing the public API. ## Returning multiple errors Most of the time when we return errors today, we only return a single error (even if many things are wrong). AJV, the OpenAPI integration we use does have a setting that allows it to return all errors in a request instead of a single one. I suggest we turn that on, but that we do it in a separate PR (because it updates a number of other snapshots). When returning errors that point to `details`, the objects in the `details` now contain a new `description` property. This "deprecates" the `message` property. Due to our general deprecation policy, this should be kept around for another full major and can be removed in v6. ```json { "name": "BadDataError", "message": "Something went wrong. Check the `details` property for more information." "details": [{ "message": "The .params property must be an object. You provided an array.", "description": "The .params property must be an object. You provided an array.", }] } ```
2023-04-25 15:40:46 +02:00
private baseUriPath: string;
constructor(
stores: Pick<IUnleashStores, 'userStore'>,
{
feat: unify error responses (#3607) This PR implements the first version of a suggested unification (and documentation) of the errors that we return from the API today. The goal is for this to be the first step towards the error type defined in this internal [linear task](https://linear.app/unleash/issue/1-629/define-the-error-type 'Define the new API error type'). ## The state of things today As things stand, we currently have no (or **very** little) documentation of the errors that are returned from the API. We mention error codes, but never what the errors may contain. Second, there is no specified format for errors, so what they return is arbitrary, and based on ... Who knows? As a result, we have multiple different errors returned by the API depending on what operation you're trying to do. What's more, with OpenAPI validation in the mix, it's absolutely possible for you to get two completely different error objects for operations to the same endpoint. Third, the errors we do return are usually pretty vague and don't really provide any real help to the user. "You don't have the right permissions". Great. Well what permissions do I need? And how would I know? "BadDataError". Sick. Why is it bad? ... You get it. ## What we want to achieve The ultimate goal is for error messages to serve both humans and machines. When the user provides bad data, we should tell them what parts of the data are bad and what they can do to fix it. When they don't have the right permissions, we should tell them what permissions they need. Additionally, it would be nice if we could provide an ID for each error instance, so that you (or an admin) can look through the logs and locate he incident. ## What's included in **this** PR? This PR does not aim to implement everything above. It's not intended to magically fix everything. Its goal is to implement the necessary **breaking** changes, so that they can be included in v5. Changing error messages is a slightly grayer area than changing APIs directly, but changing the format is definitely something I'd consider breaking. So this PR: - defines a minimal version of the error type defined in the [API error definition linear task](https://linear.app/unleash/issue/1-629/define-the-error-type). - aims to catch all errors we return today and wrap them in the error type - updates tests to match the new expectations. An important point: because we are cutting v5 very soon and because work for this wasn't started until last week, the code here isn't necessarily very polished. But it doesn't need to be. The internals can be as messy as we want, as long as the API surface is stable. That said, I'm very open to feedback about design and code completeness, etc, but this has intentionally been done quickly. Please also see my inline comments on the changes for more specific details. ### Proposed follow-ups As mentioned, this is the first step to implementing the error type. The public API error type only exposes `id`, `name`, and `message`. This is barely any more than most of the previous messages, but they are now all using the same format. Any additional properties, such as `suggestion`, `help`, `documentationLink` etc can be added as features without breaking the current format. This is an intentional limitation of this PR. Regarding additional properties: there are some error responses that must contain extra properties. Some of these are documented in the types of the new error constructor, but not all. This includes `path` and `type` properties on 401 errors, `details` on validation errors, and more. Also, because it was put together quickly, I don't yet know exactly how we (as developers) would **prefer** to use these new error messages within the code, so the internal API (the new type, name, etc), is just a suggestion. This can evolve naturally over time if (based on feedback and experience) without changing the public API. ## Returning multiple errors Most of the time when we return errors today, we only return a single error (even if many things are wrong). AJV, the OpenAPI integration we use does have a setting that allows it to return all errors in a request instead of a single one. I suggest we turn that on, but that we do it in a separate PR (because it updates a number of other snapshots). When returning errors that point to `details`, the objects in the `details` now contain a new `description` property. This "deprecates" the `message` property. Due to our general deprecation policy, this should be kept around for another full major and can be removed in v6. ```json { "name": "BadDataError", "message": "Something went wrong. Check the `details` property for more information." "details": [{ "message": "The .params property must be an object. You provided an array.", "description": "The .params property must be an object. You provided an array.", }] } ```
2023-04-25 15:40:46 +02:00
server,
getLogger,
authentication,
feat: unify error responses (#3607) This PR implements the first version of a suggested unification (and documentation) of the errors that we return from the API today. The goal is for this to be the first step towards the error type defined in this internal [linear task](https://linear.app/unleash/issue/1-629/define-the-error-type 'Define the new API error type'). ## The state of things today As things stand, we currently have no (or **very** little) documentation of the errors that are returned from the API. We mention error codes, but never what the errors may contain. Second, there is no specified format for errors, so what they return is arbitrary, and based on ... Who knows? As a result, we have multiple different errors returned by the API depending on what operation you're trying to do. What's more, with OpenAPI validation in the mix, it's absolutely possible for you to get two completely different error objects for operations to the same endpoint. Third, the errors we do return are usually pretty vague and don't really provide any real help to the user. "You don't have the right permissions". Great. Well what permissions do I need? And how would I know? "BadDataError". Sick. Why is it bad? ... You get it. ## What we want to achieve The ultimate goal is for error messages to serve both humans and machines. When the user provides bad data, we should tell them what parts of the data are bad and what they can do to fix it. When they don't have the right permissions, we should tell them what permissions they need. Additionally, it would be nice if we could provide an ID for each error instance, so that you (or an admin) can look through the logs and locate he incident. ## What's included in **this** PR? This PR does not aim to implement everything above. It's not intended to magically fix everything. Its goal is to implement the necessary **breaking** changes, so that they can be included in v5. Changing error messages is a slightly grayer area than changing APIs directly, but changing the format is definitely something I'd consider breaking. So this PR: - defines a minimal version of the error type defined in the [API error definition linear task](https://linear.app/unleash/issue/1-629/define-the-error-type). - aims to catch all errors we return today and wrap them in the error type - updates tests to match the new expectations. An important point: because we are cutting v5 very soon and because work for this wasn't started until last week, the code here isn't necessarily very polished. But it doesn't need to be. The internals can be as messy as we want, as long as the API surface is stable. That said, I'm very open to feedback about design and code completeness, etc, but this has intentionally been done quickly. Please also see my inline comments on the changes for more specific details. ### Proposed follow-ups As mentioned, this is the first step to implementing the error type. The public API error type only exposes `id`, `name`, and `message`. This is barely any more than most of the previous messages, but they are now all using the same format. Any additional properties, such as `suggestion`, `help`, `documentationLink` etc can be added as features without breaking the current format. This is an intentional limitation of this PR. Regarding additional properties: there are some error responses that must contain extra properties. Some of these are documented in the types of the new error constructor, but not all. This includes `path` and `type` properties on 401 errors, `details` on validation errors, and more. Also, because it was put together quickly, I don't yet know exactly how we (as developers) would **prefer** to use these new error messages within the code, so the internal API (the new type, name, etc), is just a suggestion. This can evolve naturally over time if (based on feedback and experience) without changing the public API. ## Returning multiple errors Most of the time when we return errors today, we only return a single error (even if many things are wrong). AJV, the OpenAPI integration we use does have a setting that allows it to return all errors in a request instead of a single one. I suggest we turn that on, but that we do it in a separate PR (because it updates a number of other snapshots). When returning errors that point to `details`, the objects in the `details` now contain a new `description` property. This "deprecates" the `message` property. Due to our general deprecation policy, this should be kept around for another full major and can be removed in v6. ```json { "name": "BadDataError", "message": "Something went wrong. Check the `details` property for more information." "details": [{ "message": "The .params property must be an object. You provided an array.", "description": "The .params property must be an object. You provided an array.", }] } ```
2023-04-25 15:40:46 +02:00
}: Pick<IUnleashConfig, 'getLogger' | 'authentication' | 'server'>,
services: {
accessService: AccessService;
resetTokenService: ResetTokenService;
emailService: EmailService;
eventService: EventService;
sessionService: SessionService;
settingService: SettingService;
},
) {
this.logger = getLogger('service/user-service.js');
this.store = stores.userStore;
this.eventService = services.eventService;
this.accessService = services.accessService;
this.resetTokenService = services.resetTokenService;
this.emailService = services.emailService;
this.sessionService = services.sessionService;
this.settingService = services.settingService;
if (authentication.createAdminUser !== false) {
process.nextTick(() =>
this.initAdminUser({
createAdminUser: authentication.createAdminUser,
initialAdminUser: authentication.initialAdminUser,
}),
);
}
feat: unify error responses (#3607) This PR implements the first version of a suggested unification (and documentation) of the errors that we return from the API today. The goal is for this to be the first step towards the error type defined in this internal [linear task](https://linear.app/unleash/issue/1-629/define-the-error-type 'Define the new API error type'). ## The state of things today As things stand, we currently have no (or **very** little) documentation of the errors that are returned from the API. We mention error codes, but never what the errors may contain. Second, there is no specified format for errors, so what they return is arbitrary, and based on ... Who knows? As a result, we have multiple different errors returned by the API depending on what operation you're trying to do. What's more, with OpenAPI validation in the mix, it's absolutely possible for you to get two completely different error objects for operations to the same endpoint. Third, the errors we do return are usually pretty vague and don't really provide any real help to the user. "You don't have the right permissions". Great. Well what permissions do I need? And how would I know? "BadDataError". Sick. Why is it bad? ... You get it. ## What we want to achieve The ultimate goal is for error messages to serve both humans and machines. When the user provides bad data, we should tell them what parts of the data are bad and what they can do to fix it. When they don't have the right permissions, we should tell them what permissions they need. Additionally, it would be nice if we could provide an ID for each error instance, so that you (or an admin) can look through the logs and locate he incident. ## What's included in **this** PR? This PR does not aim to implement everything above. It's not intended to magically fix everything. Its goal is to implement the necessary **breaking** changes, so that they can be included in v5. Changing error messages is a slightly grayer area than changing APIs directly, but changing the format is definitely something I'd consider breaking. So this PR: - defines a minimal version of the error type defined in the [API error definition linear task](https://linear.app/unleash/issue/1-629/define-the-error-type). - aims to catch all errors we return today and wrap them in the error type - updates tests to match the new expectations. An important point: because we are cutting v5 very soon and because work for this wasn't started until last week, the code here isn't necessarily very polished. But it doesn't need to be. The internals can be as messy as we want, as long as the API surface is stable. That said, I'm very open to feedback about design and code completeness, etc, but this has intentionally been done quickly. Please also see my inline comments on the changes for more specific details. ### Proposed follow-ups As mentioned, this is the first step to implementing the error type. The public API error type only exposes `id`, `name`, and `message`. This is barely any more than most of the previous messages, but they are now all using the same format. Any additional properties, such as `suggestion`, `help`, `documentationLink` etc can be added as features without breaking the current format. This is an intentional limitation of this PR. Regarding additional properties: there are some error responses that must contain extra properties. Some of these are documented in the types of the new error constructor, but not all. This includes `path` and `type` properties on 401 errors, `details` on validation errors, and more. Also, because it was put together quickly, I don't yet know exactly how we (as developers) would **prefer** to use these new error messages within the code, so the internal API (the new type, name, etc), is just a suggestion. This can evolve naturally over time if (based on feedback and experience) without changing the public API. ## Returning multiple errors Most of the time when we return errors today, we only return a single error (even if many things are wrong). AJV, the OpenAPI integration we use does have a setting that allows it to return all errors in a request instead of a single one. I suggest we turn that on, but that we do it in a separate PR (because it updates a number of other snapshots). When returning errors that point to `details`, the objects in the `details` now contain a new `description` property. This "deprecates" the `message` property. Due to our general deprecation policy, this should be kept around for another full major and can be removed in v6. ```json { "name": "BadDataError", "message": "Something went wrong. Check the `details` property for more information." "details": [{ "message": "The .params property must be an object. You provided an array.", "description": "The .params property must be an object. You provided an array.", }] } ```
2023-04-25 15:40:46 +02:00
this.baseUriPath = server.baseUriPath || '';
}
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(
initialAdminUserConfig: Pick<
IAuthOption,
'createAdminUser' | 'initialAdminUser'
>,
): Promise<void> {
let username: string;
let password: string;
if (
initialAdminUserConfig.createAdminUser !== false &&
initialAdminUserConfig.initialAdminUser
) {
username = initialAdminUserConfig.initialAdminUser.username;
password = initialAdminUserConfig.initialAdminUser.password;
} else {
username = 'admin';
password = 'unleash4all';
}
const userCount = await this.store.count();
if (userCount === 0 && username && password) {
// create default admin user
try {
this.logger.info(
`Creating default user '${username}' with password '${password}'`,
);
const user = await this.store.insert({
username,
});
const passwordHash = await bcrypt.hash(password, 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 '${username}'`,
);
}
}
}
async getAll(): Promise<IUserWithRootRole[]> {
const users = await this.store.getAll();
const defaultRole = await this.accessService.getPredefinedRole(
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<IUserWithRootRole> {
const user = await this.store.get(id);
const rootRole = await this.accessService.getRootRoleForUser(id);
return { ...user, rootRole: rootRole.id };
}
async search(query: string): 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?: IUser,
): Promise<IUserWithRootRole> {
if (!username && !email) {
throw new BadDataError('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 BadDataError('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);
}
const userCreated = await this.getUser(user.id);
await this.eventService.storeEvent(
new UserCreatedEvent({
createdBy: this.getCreatedBy(updatedBy),
userCreated,
}),
);
return userCreated;
}
private getCreatedBy(updatedBy: IUser = systemUser) {
return updatedBy.username || updatedBy.email;
}
async updateUser(
{ id, name, email, rootRole }: IUpdateUser,
updatedBy?: IUser,
): Promise<IUserWithRootRole> {
const preUser = await this.getUser(id);
if (email) {
Joi.assert(email, Joi.string().email(), 'Email');
}
if (rootRole) {
await this.accessService.setUserRootRole(id, rootRole);
}
const payload: Partial<IUser> = {
name: name || preUser.name,
email: email || preUser.email,
};
// Empty updates will throw, so make sure we have something to update.
const user = Object.values(payload).some(isDefined)
? await this.store.update(id, payload)
: preUser;
const storedUser = await this.getUser(user.id);
await this.eventService.storeEvent(
new UserUpdatedEvent({
createdBy: this.getCreatedBy(updatedBy),
preUser: preUser,
postUser: storedUser,
}),
);
return storedUser;
}
async deleteUser(userId: number, updatedBy?: IUser): Promise<void> {
const user = await this.getUser(userId);
await this.accessService.wipeUserPermissions(userId);
await this.sessionService.deleteSessionsForUser(userId);
await this.store.delete(userId);
await this.eventService.storeEvent(
new UserDeletedEvent({
createdBy: this.getCreatedBy(updatedBy),
deletedUser: user,
}),
);
}
async loginUser(usernameOrEmail: string, password: string): Promise<IUser> {
const settings = await this.settingService.get<SimpleAuthSettings>(
simpleAuthSettingsKey,
);
if (settings?.disabled) {
throw new DisabledError(
'Logging in with username/password has been disabled.',
);
}
const idQuery = isEmail(usernameOrEmail)
? { email: usernameOrEmail }
: { username: usernameOrEmail };
let user, passwordHash;
try {
user = await this.store.getByQuery(idQuery);
passwordHash = await this.store.getPasswordHash(user.id);
} catch (error) {}
if (user && passwordHash) {
const match = await bcrypt.compare(password, passwordHash);
if (match) {
await this.store.successfullyLogin(user);
return user;
}
}
Clean up old errors (#3633) This PR attempts to improve the error handling introduced in #3607. ## About the changes ## **tl;dr:** - Make `UnleashError` constructor protected - Make all custom errors inherit from `UnleashError`. - Add tests to ensure that all special error cases include their relevant data - Remove `PasswordMismatchError` and `BadRequestError`. These don't exist. - Add a few new error types: `ContentTypeError`, `NotImplementedError`, `UnauthorizedError` - Remove the `...rest` parameter from error constructor - Add an unexported `GenericUnleashError` class - Move OpenAPI conversion function to `BadDataError` clas - Remove explicit `Error.captureStackTrace`. This is done automatically. - Extract `getPropFromString` function and add tests ### **In a more verbose fashion** The main thing is that all our internal errors now inherit from`UnleashError`. This allows us to simplify the `UnleashError` constructor and error handling in general while still giving us the extra benefits we added to that class. However, it _does_ also mean that I've had to update **all** existing error classes. The constructor for `UnleashError` is now protected and all places that called that constructor directly have been updated. Because the base error isn't available anymore, I've added three new errors to cover use cases that we didn't already have covered: `NotImplementedError`, `UnauthorizedError`, `ContentTypeError`. This is to stay consistent in how we report errors to the user. There is also an internal class, `GenericUnleashError` that inherits from the base error. This class is only used in conversions for cases where we don't know what the error is. It is not exported. In making all the errors inherit, I've also removed the `...rest` parameter from the `UnleashError` constructor. We don't need this anymore. Following on from the fixes with missing properties in #3638, I have added tests for all errors that contain extra data. Some of the error names that were originally used when creating the list don't exist in the backend. `BadRequestError` and `PasswordMismatchError` have been removed. The `BadDataError` class now contains the conversion code for OpenAPI validation errors. In doing so, I extracted and tested the `getPropFromString` function. ### Main files Due to the nature of the changes, there's a lot of files to look at. So to make it easier to know where to turn your attention: The changes in `api-error.ts` contain the main changes: protected constructor, removal of OpenAPI conversion (moved into `BadDataError`. `api-error.test.ts` contains tests to make sure that errors work as expected. Aside from `get-prop-from-string.ts` and the tests, everything else is just the required updates to go through with the changes. ## Discussion points I've gone for inheritance of the Error type over composition. This is in large part because throwing actual Error instances instead of just objects is preferable (because they collect stack traces, for instance). However, it's quite possible that we could solve the same thing in a more elegant fashion using composition. ## For later / suggestions for further improvements The `api-error` files still contain a lot of code. I think it might be beneficial to break each Error into a separate folder that includes the error, its tests, and its schema (if required). It would help decouple it a bit. We don't currently expose the schema anywhere, so it's not available in the openapi spec. We should look at exposing it too. Finally, it would be good to go through each individual error message and update each one to be as helpful as possible.
2023-05-11 11:10:57 +02:00
throw new PasswordMismatch(
`The combination of password and username you provided is invalid. If you have forgotten your password, visit ${this.baseUriPath}/forgotten-password or get in touch with your instance administrator.`,
);
}
/**
* 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.
2021-08-25 12:43:42 +02:00
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;
}
}
await this.store.successfullyLogin(user);
return user;
}
async changePassword(userId: number, password: string): Promise<void> {
this.validatePassword(password);
const passwordHash = await bcrypt.hash(password, saltRounds);
await this.store.setPasswordHash(userId, passwordHash);
await this.sessionService.deleteSessionsForUser(userId);
await this.resetTokenService.expireExistingTokensForUser(userId);
}
async changePasswordWithVerification(
userId: number,
newPassword: string,
oldPassword: string,
): Promise<void> {
const currentPasswordHash = await this.store.getPasswordHash(userId);
const match = await bcrypt.compare(oldPassword, currentPasswordHash);
if (!match) {
throw new PasswordMismatch(
`The old password you provided is invalid. If you have forgotten your password, visit ${this.baseUriPath}/forgotten-password or get in touch with your instance administrator.`,
);
}
await this.changePassword(userId, newPassword);
}
async getUserForToken(token: string): Promise<TokenUserSchema> {
const { createdBy, userId } =
await this.resetTokenService.isValid(token);
const user = await this.getUser(userId);
feat: custom project roles (#1220) * wip: environment for permissions * fix: add migration for roles * fix: connect environment with access service * feat: add tests * chore: Implement scaffolding for new rbac * fix: add fake store * feat: Add api endpoints for roles and permissions list * feat: Add ability to provide permissions when creating a role and rename environmentName to name in the list permissions datastructure * fix: Make project roles resolve correctly against new environments permissions structure * fix: Patch migration to also populate permission names * fix: Make permissions actually work with new environments * fix: Add back to get permissions working for editor role * fix: Removed ability to set role type through api during creation - it's now always custom * feat: Return permissions on get role endpoint * feat: Add in support for updating roles * fix: Get a bunch of tests working and delete a few that make no sense anymore * chore: A few small cleanups - remove logging and restore default on dev server config * chore: Refactor role/access stores into more logical domains * feat: Add in validation for roles * feat: Patch db migration to handle old stucture * fix: migration for project roles * fix: patch a few broken tests * fix: add permissions to editor * fix: update test name * fix: update user permission mapping * fix: create new user * fix: update root role test * fix: update tests * feat: Validation now works when updating a role * fix: Add in very barebones down migration for rbac so that tests work * fix: Improve responses from role resolution - getting a non existant role will throw a NotFound error * fix: remove unused permissions * fix: add test for connecting roles and deleting project * fix: add test for adding a project member with a custom role * fix: add test for changing user role * fix: add guard for deleting role if the role is in use * fix: alter migration * chore: Minor code cleanups * chore: Small code cleanups * chore: More minor cleanups of code * chore: Trim some dead code to make the linter happy * feat: Schema validation for roles * fix: setup permission for variant * fix: remove unused import * feat: Add cascading delete for role_permissions when deleting a role * feat: add configuration option for disabling legacy api * chore: update frontend to beta version * 4.6.0-beta.0 * fix: export default project constant * fix: update snapshot * fix: module pattern ../../lib * fix: move DEFAULT_PROJECT to types * fix: remove debug logging * fix: remove debug log state * fix: Change permission descriptions * fix: roles should have unique name * fix: root roles should be connected to the default project * fix: typo in role-schema.ts * fix: Role permission empty string for non environment type * feat: new permission for moving project * fix: add event for changeProject * fix: Removing a user from a project will now check to see if that project has an owner, rather than checking if any project has an owner * fix: add tests for move project * fix: Add in missing create/delete tag permissions * fix: Removed duplicate impl caused by multiple good samaritans putting it back in! * fix: Trim out add tag permissions, for now at least * chore: Trim out new add and delete tag permissions - we're going with update feature instead * chore: update frontend * 4.6.0-beta.1 * feat: Prevent editing of built in roles * fix: Patch an issue where permissions for variants/environments didn't match the front end * fix: lint Co-authored-by: Ivar Conradi Østhus <ivarconr@gmail.com> Co-authored-by: Fredrik Oseberg <fredrik.no@gmail.com>
2022-01-13 11:14:17 +01:00
const role = await this.accessService.getRoleData(user.rootRole);
return {
token,
createdBy,
email: user.email,
name: user.name,
id: user.id,
role: {
id: user.rootRole,
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);
} else {
throw new InvalidTokenError();
}
}
async createResetPasswordEmail(
receiverEmail: string,
user: IUser = systemUser,
): Promise<URL> {
const receiver = await this.getByEmail(receiverEmail);
if (!receiver) {
throw new NotFoundError(`Could not find ${receiverEmail}`);
}
if (this.passwordResetTimeouts[receiver.id]) {
return;
}
const resetLink = await this.resetTokenService.createResetPasswordUrl(
receiver.id,
user.username || user.email,
);
this.passwordResetTimeouts[receiver.id] = setTimeout(() => {
delete this.passwordResetTimeouts[receiver.id];
}, 1000 * 60); // 1 minute
await this.emailService.sendResetMail(
receiver.name,
receiver.email,
resetLink.toString(),
);
return resetLink;
}
}
export default UserService;