Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // With async/await
- export async function login(ctx: Context, next: Function) {
- const body: userService.LoginPayload = ctx.request.body;
- try {
- const user: userService.User = await userService.readOne(body.email);
- const hash: string = user ? user.password : '';
- const validPassword: boolean = await compare(body.password, hash);
- if (!user || !validPassword) {
- throw new AuthenticationError({
- email: 'ERROR_INVALID_EMAIL',
- password: 'ERROR_INVALID_PASSWORD'
- });
- }
- const token = await jwt.generate({
- id: user.id,
- type: user.type
- });
- ctx.response.status = 200;
- ctx.response.body = {
- user_id: user.id,
- token: token
- };
- }
- catch(error) {
- throw error;
- }
- }
- /**
- * Without async/await, might not be logically correct.
- * I wrote it without running it first.
- **/
- export function login(ctx: Context, next: Function) {
- const body: userService.LoginPayload = ctx.request.body;
- userService.readOne(body.email).then((user) => {
- const hash = user ? user.password : '';
- compare(body.password, hash).then((validPassword) => {
- if (!user || !validPassword) {
- throw new AuthenticationError({
- email: 'ERROR_INVALID_EMAIL',
- password: 'ERROR_INVALID_PASSWORD'
- });
- }
- jwt.generate({id: user.id, type: user.type}).then((token) => {
- ctx.response.status = 200;
- ctx.response.body = {
- user_id: user.id,
- token: token
- };
- })
- });
- })
- .catch(function(error) {
- throw error;
- });
- }
Add Comment
Please, Sign In to add comment