Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#223 => Step 10 : Simplify Code #247

Closed
wants to merge 10 commits into from
10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@
"trailingComma": "es5",
"printWidth": 100
},
"jest": {
"transform": {
".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx)$",
"moduleFileExtensions": [
"ts",
"js"
]
},
"renovate": {
"extends": [
"config:base"
Expand Down
18 changes: 10 additions & 8 deletions packages/email-ns-debug/src/email-ns-debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,14 @@ export default class EmailNotificationServiceDebug implements NotificationServic
private plugins: NotificationPlugins;

constructor(config: Configuration){

// Register plugins
this.plugins = config.plugins.reduce(
(a: NotificationPlugins ,notificationPlugin: NotificationPlugin) =>
({ ...a, [notificationPlugin.name]: notificationPlugin })
,{})

}
this.registerPlugins(config.plugins)
}

public send = (mail: object): void => {
// tslint:disable-next-line
console.dir(mail)
}
}

public notify (notificationPluginName: string, actionName: string, params: object): void {
const plugin = this.plugins[notificationPluginName];
Expand All @@ -36,4 +31,11 @@ export default class EmailNotificationServiceDebug implements NotificationServic
action(this.send, params);
}

private registerPlugins(plugins: NotificationPlugin[]): void {
this.plugins = plugins.reduce(
(a: NotificationPlugins ,notificationPlugin: NotificationPlugin) =>
({ ...a, [notificationPlugin.name]: notificationPlugin })
,{})
}

}
22 changes: 9 additions & 13 deletions packages/password/src/accounts-password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
ConnectionInformations,
Message
} from '@accounts/types';
import { trim, isEmpty, isFunction, isString, isPlainObject, get, find, includes } from 'lodash';
import { trim, isEmpty, isFunction, isString, isPlainObject, get } from 'lodash';
import { HashAlgorithm } from '@accounts/common';
import { TwoFactor, AccountsTwoFactorOptions } from '@accounts/two-factor';
import { AccountsServer, getFirstUserEmail } from '@accounts/server';
Expand Down Expand Up @@ -127,17 +127,13 @@ export default class AccountsPassword implements AuthenticationService {
throw new Error('Verify email link expired');
}

const verificationTokens: TokenRecord[] = get(
user,
['services', 'email', 'verificationTokens'],
[]
);
const tokenRecord = find(verificationTokens, (t: TokenRecord) => t.token === token);
const verificationTokens: TokenRecord[] = get(user, 'services.email.verificationTokens', []);
const tokenRecord = verificationTokens.find((t: TokenRecord) => t.token === token);
if (!tokenRecord) {
throw new Error('Verify email link expired');
}
// TODO check time for expiry date
const emailRecord = find(user.emails, (e: EmailRecord) => e.address === tokenRecord.address);
const emailRecord = user.emails.find((e: EmailRecord) => e.address === tokenRecord.address);
if (!emailRecord) {
throw new Error('Verify email link is for unknown address');
}
Expand All @@ -158,15 +154,15 @@ export default class AccountsPassword implements AuthenticationService {
}

// TODO move this getter into a password service module
const resetTokens = get(user, ['services', 'password', 'reset']);
const resetTokenRecord = find(resetTokens, t => t.token === token);
const resetTokens = get(user, 'services.password.reset', []);
const resetTokenRecord = resetTokens.find(t => t.token === token);

if (this.server.tokenManager.isEmailTokenExpired(token, resetTokenRecord)) {
throw new Error('Reset password link expired');
}

const emails = user.emails || [];
if (!includes(emails.map((email: EmailRecord) => email.address), resetTokenRecord.address)) {
const emails: EmailRecord[] = user.emails || [];
if (!emails.find((e: EmailRecord) => e.address === resetTokenRecord.address )) {
throw new Error('Token has invalid email address');
}

Expand Down Expand Up @@ -195,7 +191,7 @@ export default class AccountsPassword implements AuthenticationService {
}
// Make sure the address is valid
const emails = user.emails || [];
if (!address || !includes(emails.map(email => email.address), address)) {
if (!emails.find((e: EmailRecord) => e.address === address )) {
throw new Error('No such email address for user');
}
const token = this.server.tokenManager.generateRandomToken();
Expand Down
9 changes: 4 additions & 5 deletions packages/rest-express/src/transport-express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ export default class TransportExpress {
try {
const accessToken = this.tokenTransport.getAccessToken(req)
const { username } = req.body;
const { userAgent, ip } = getConnectionInformations(req)
const { tokens, ...data } = await this.accountsServer.impersonate(accessToken, username, ip, userAgent);
const connectionInfo = getConnectionInformations(req)
const { tokens, ...data } = await this.accountsServer.impersonate(accessToken, username, connectionInfo);
this.tokenTransport.setTokens(tokens, res);
this.send(res, data)
} catch (err) {
Expand All @@ -108,12 +108,11 @@ export default class TransportExpress {
private refreshTokens = async ( req: Request, res: Response ) => {
try {
const { accessToken, refreshToken } = this.tokenTransport.getTokens(req)
const { userAgent, ip } = getConnectionInformations(req)
const connectionInfo = getConnectionInformations(req)
const refreshedSession = await this.accountsServer.refreshTokens(
accessToken,
refreshToken,
ip,
userAgent
connectionInfo
);
const { tokens, ...data } = refreshedSession;
this.tokenTransport.setTokens(tokens, res);
Expand Down
61 changes: 11 additions & 50 deletions packages/server/__tests__/account-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,26 +37,6 @@ describe('AccountsServer', () => {
});
});

describe('getServices', () => {
it('should return instance services', async () => {
const passwordService = {
serviceName: 'password',
link: () => passwordService
}
const authenticationServices = [passwordService]

const expectedServices: any = {
password: passwordService
};
const account = new AccountsServer({
db: {},
tokenManager,
authenticationServices
} as any);
expect(account.getServices()).toEqual(expectedServices);
});
});

describe('loginWithUser', () => {
it('creates a session when given a proper user object', async () => {
const user = {
Expand Down Expand Up @@ -468,7 +448,7 @@ describe('AccountsServer', () => {
accessToken: 'newAccessToken',
refreshToken: 'newRefreshToken',
});
const res = await accountsServer.refreshTokens(accessToken, refreshToken, 'ip', 'user agent');
const res = await accountsServer.refreshTokens(accessToken, refreshToken, { ip:'ip', userAgent:'user agent' });
expect(updateSession.mock.calls[0]).toEqual(['456', { ip: 'ip', userAgent: 'user agent' }]);
expect(res.user).toEqual({
userId: '123',
Expand Down Expand Up @@ -637,21 +617,6 @@ describe('AccountsServer', () => {
});
});

describe('findUserById', () => {
it('call this.db.findUserById', async () => {
const findUserById = jest.fn(() => Promise.resolve('user'));
const accountsServer = new AccountsServer(
{
db: { findUserById } as any,
tokenManager,
}
);
const user = await accountsServer.findUserById('id');
expect(findUserById.mock.calls[0]).toEqual(['id']);
expect(user).toEqual('user');
});
});

describe('resumeSession', () => {
it('throws error if user is not found', async () => {
const accountsServer = new AccountsServer(
Expand Down Expand Up @@ -963,7 +928,7 @@ describe('AccountsServer', () => {
userId: '123',
} as any);

const impersonationAuthorize = accountsServer.getOptions().impersonationAuthorize;
const impersonationAuthorize = accountsServer.config.impersonationAuthorize;
expect(impersonationAuthorize).toBeDefined();

const res = await accountsServer.impersonate(accessToken, { userId: 'userId' }, null, null);
Expand Down Expand Up @@ -1016,27 +981,23 @@ describe('AccountsServer', () => {
const userObject = { username: 'test', services: [], id: '123' };

it('internal sanitizer should clean services field from the user object', () => {
const accountsServer = new AccountsServer(
{
db: db as any,
tokenManager,
}
);
const accountsServer = new AccountsServer({ db: db as any, tokenManager });
const modifiedUser = accountsServer.sanitizeUser(userObject);
expect(modifiedUser.services).toBeUndefined();
});

it('should run external sanitizier when provided one', () => {
const accountsServer = new AccountsServer(
{
db: db as any,
tokenManager,

userObjectSanitizer: (user, omit) => omit(user, ['username']),
const accountsServer = new AccountsServer({
db: db as any,
tokenManager,
sanitizeUser: (user) => {
const { username, ...rest } = user;
return rest
}
);
});
const modifiedUser = accountsServer.sanitizeUser(userObject);
expect(modifiedUser.username).toBeUndefined();
expect(modifiedUser.services).toBeUndefined();
});
});
});
Loading