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

[discuss] code authentication service #776

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
35 changes: 35 additions & 0 deletions packages/code-provider-twilio/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# @accounts/code-provider-twilio

## Install

```
yarn add @accounts/code-provider-twilio
```

## Usage

```js
import { AccountsServer } from '@accounts/server';
import { AccountsCode } from '@accounts/code';
import { CodeProviderTwilio } from '@accounts/code-provider-twilio';

const codeProvider = new CodeProviderTwilio({
sid: 'TWILIO_SID',
secret: 'TWILIO_SECRET',
phoneNumber: 'TWILIO_FROM_PHONE_NUMBER',
});

export const accountsCode = new AccountsCode({
codeProvider,
// options
});

const accountsServer = new AccountsServer(
{
// options
},
{
code: accountsCode,
}
);
```
27 changes: 27 additions & 0 deletions packages/code-provider-twilio/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "@accounts/code-provider-twilio",
"version": "0.18.0",
"license": "MIT",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"scripts": {
"clean": "rimraf lib",
"start": "tsc --watch",
"precompile": "yarn clean",
"compile": "tsc",
"prepublishOnly": "yarn compile"
},
"jest": {
"testEnvironment": "node",
"preset": "ts-jest"
},
"dependencies": {
"twilio": "^3.33.3"
},
"devDependencies": {
"@accounts/code": "^0.18.0"
},
"peerDependencies": {
"@accounts/code": "^0.18.0"
}
}
50 changes: 50 additions & 0 deletions packages/code-provider-twilio/src/code-provider-twilio.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Twilio } from 'twilio';

import { CodeProvider } from '@accounts/code';

export type MessageCreator = (code: string) => string;

export interface TwilioSmsCodeProviderOptions {
sid: string;
secret: string;
phoneNumber?: string;
messagingServiceSid?: string;
messageCreator?: MessageCreator;
}

export default class TwilioSmsCodeProvider implements CodeProvider {
private messageCreator: MessageCreator;
private phoneNumber?: string;
private messagingServiceSid?: string;
private twilio: Twilio;

constructor({
sid,
secret,
phoneNumber,
messagingServiceSid,
messageCreator = code => `This is your authentication code: ${code}`,
}: TwilioSmsCodeProviderOptions) {
this.twilio = new Twilio(sid, secret);
this.phoneNumber = phoneNumber;
this.messagingServiceSid = messagingServiceSid;
this.messageCreator = messageCreator;
}

public async sendToClient(serviceId: string, code: string): Promise<void> {
const options: any = {
body: this.messageCreator(code),
to: serviceId,
};

if (this.phoneNumber) {
options.from = this.phoneNumber;
} else if (this.messagingServiceSid) {
options.messagingServiceSid = this.messagingServiceSid;
} else {
throw new Error('Not enough twilio credentials');
}

await this.twilio.messages.create(options);
}
}
4 changes: 4 additions & 0 deletions packages/code-provider-twilio/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import CodeProviderTwilio from './code-provider-twilio';

export default CodeProviderTwilio;
export { CodeProviderTwilio };
9 changes: 9 additions & 0 deletions packages/code-provider-twilio/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./lib",
"importHelpers": true
},
"exclude": ["node_modules", "__tests__", "lib"]
}
30 changes: 30 additions & 0 deletions packages/code/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# @accounts/code

## Install

```
yarn add @accounts/code
```

## Usage

```js
import { AccountsServer } from '@accounts/server';
import { AccountsCode } from '@accounts/code';

const codeProvider = '...';

export const accountsCode = new AccountsCode({
codeProvider,
// options
});

const accountsServer = new AccountsServer(
{
// options
},
{
code: accountsCode,
}
);
```
195 changes: 195 additions & 0 deletions packages/code/__tests__/accounts-code.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
import { AccountsCode, CodeProvider, ErrorMessages } from '../src';

function createCodeProvider(success: boolean): CodeProvider {
return {
sendToClient: jest.fn(() => (success ? Promise.resolve() : Promise.reject())),
};
}

const errors: ErrorMessages = {
userNotFound: '0',
codeExpired: '1',
codeWasNotFound: '2',
wrongCode: '3',
failedToProvideCode: '4',
};

describe('AccountsCode', () => {
describe('preparation', () => {
it('throws error when no user is found', async () => {
const code = new AccountsCode({ codeProvider: createCodeProvider(true), errors });
const findUserByServiceId = jest.fn(() => Promise.resolve());
code.setStore({ findUserByServiceId } as any);

try {
await code.prepareAuthentication('1234');
} catch (e) {
expect(e.message).toEqual(errors.userNotFound);
}

expect.assertions(1);
});

it('throws error when failed to send code to the client', async () => {
const code = new AccountsCode({ codeProvider: createCodeProvider(false), errors });

const user = {
id: '123',
};

const findUserByServiceId = jest.fn(() => Promise.resolve(user));
const setService = jest.fn(() => Promise.resolve());
code.setStore({ findUserByServiceId, setService } as any);

try {
await code.prepareAuthentication('1234');
} catch (e) {
expect(e.message).toEqual(errors.failedToProvideCode);
}

expect.assertions(1);
});

it('completes successfully', async () => {
const code = new AccountsCode({ codeProvider: createCodeProvider(true), errors });

const user = {
id: '123',
};

const findUserByServiceId = jest.fn(() => Promise.resolve(user));
const setService = jest.fn(() => Promise.resolve());
code.setStore({ findUserByServiceId, setService } as any);

const res = await code.prepareAuthentication('1234');

expect(res).toBeUndefined();
expect(setService).toHaveBeenCalledTimes(1);
expect(setService).toHaveBeenCalledWith('123', code.serviceName, {
id: '1234',
code: expect.any(String),
expiry: expect.any(Number),
});
});
});

describe('Authentication', () => {
const code = new AccountsCode({ codeProvider: createCodeProvider(true), errors });

it('throws error when no user is found', async () => {
const findUserByServiceId = jest.fn(() => Promise.resolve(null));
code.setStore({ findUserByServiceId } as any);

try {
await code.authenticate({ serviceId: '1234', code: '2233' });
} catch (e) {
expect(e.message).toEqual(errors.userNotFound);
}

expect.assertions(1);
});

it('throws error when no code is found', async () => {
const findUserByServiceId = jest.fn(() =>
Promise.resolve({
id: '123',
})
);
code.setStore({ findUserByServiceId } as any);

try {
await code.authenticate({ serviceId: '1234', code: '2233' });
} catch (e) {
expect(e.message).toEqual(errors.codeWasNotFound);
}

expect.assertions(1);
});

it('throws error when no code is found 2', async () => {
const findUserByServiceId = jest.fn(() =>
Promise.resolve({
id: '123',
services: {
[code.serviceName]: {},
},
})
);
code.setStore({ findUserByServiceId } as any);

try {
await code.authenticate({ serviceId: '1234', code: '2233' });
} catch (e) {
expect(e.message).toEqual(errors.codeWasNotFound);
}

expect.assertions(1);
});

it('throws error when code is wrong', async () => {
const findUserByServiceId = jest.fn(() =>
Promise.resolve({
id: '123',
services: {
[code.serviceName]: {
code: '1111',
},
},
})
);
code.setStore({ findUserByServiceId } as any);

try {
await code.authenticate({ serviceId: '1234', code: '2233' });
} catch (e) {
expect(e.message).toEqual(errors.wrongCode);
}

expect.assertions(1);
});

it('throws error when code is expired', async () => {
const findUserByServiceId = jest.fn(() =>
Promise.resolve({
id: '123',
services: {
[code.serviceName]: {
code: 'vKw3G1T1mUWhSqSeLkCOXW5NvFk4f12M/GsBXUDVuwI=',
expiry: Date.now() - 10000,
},
},
})
);
code.setStore({ findUserByServiceId } as any);

try {
await code.authenticate({ serviceId: '1234', code: '2233' });
} catch (e) {
expect(e.message).toEqual(errors.codeExpired);
}

expect.assertions(1);
});

it('authenticates successfully and returns user', async () => {
const user = {
id: '123',
services: {
[code.serviceName]: {
code: 'vKw3G1T1mUWhSqSeLkCOXW5NvFk4f12M/GsBXUDVuwI=',
expiry: Date.now() + 10000,
},
},
};
const findUserByServiceId = jest.fn(() => Promise.resolve(user));
const setService = jest.fn(() => Promise.resolve());
code.setStore({ findUserByServiceId, setService } as any);

const res = await code.authenticate({ serviceId: '1234', code: '2233' });

expect(res).toEqual(user);
expect(setService).toHaveBeenCalledTimes(1);
expect(setService).toHaveBeenCalledWith('123', code.serviceName, { id: '1234' });
});
});
});
36 changes: 36 additions & 0 deletions packages/code/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "@accounts/code",
"version": "0.18.0",
"license": "MIT",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"scripts": {
"clean": "rimraf lib",
"start": "tsc --watch",
"precompile": "yarn clean",
"compile": "tsc",
"prepublishOnly": "yarn compile",
"testonly": "jest --coverage",
"coverage": "jest --coverage"
},
"jest": {
"testEnvironment": "node",
"preset": "ts-jest"
},
"dependencies": {
"@accounts/types": "^0.18.0",
"lodash": "^4.17.15",
"randomstring": "^1.1.5",
"tslib": "1.10.0"
},
"devDependencies": {
"@accounts/server": "^0.18.0",
"@types/randomstring": "^1.1.6",
"@types/jest": "24.0.16",
"jest": "24.8.0",
"rimraf": "2.6.3"
},
"peerDependencies": {
"@accounts/server": "^0.18.0"
}
}
Loading