Guest User

Untitled

a guest
Mar 29th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. // With async/await
  2. export async function login(ctx: Context, next: Function) {
  3. const body: userService.LoginPayload = ctx.request.body;
  4.  
  5. try {
  6. const user: userService.User = await userService.readOne(body.email);
  7. const hash: string = user ? user.password : '';
  8. const validPassword: boolean = await compare(body.password, hash);
  9.  
  10. if (!user || !validPassword) {
  11. throw new AuthenticationError({
  12. email: 'ERROR_INVALID_EMAIL',
  13. password: 'ERROR_INVALID_PASSWORD'
  14. });
  15. }
  16.  
  17. const token = await jwt.generate({
  18. id: user.id,
  19. type: user.type
  20. });
  21.  
  22. ctx.response.status = 200;
  23. ctx.response.body = {
  24. user_id: user.id,
  25. token: token
  26. };
  27. }
  28. catch(error) {
  29. throw error;
  30. }
  31. }
  32.  
  33. /**
  34. * Without async/await, might not be logically correct.
  35. * I wrote it without running it first.
  36. **/
  37. export function login(ctx: Context, next: Function) {
  38. const body: userService.LoginPayload = ctx.request.body;
  39.  
  40. userService.readOne(body.email).then((user) => {
  41. const hash = user ? user.password : '';
  42. compare(body.password, hash).then((validPassword) => {
  43. if (!user || !validPassword) {
  44. throw new AuthenticationError({
  45. email: 'ERROR_INVALID_EMAIL',
  46. password: 'ERROR_INVALID_PASSWORD'
  47. });
  48. }
  49. jwt.generate({id: user.id, type: user.type}).then((token) => {
  50. ctx.response.status = 200;
  51. ctx.response.body = {
  52. user_id: user.id,
  53. token: token
  54. };
  55. })
  56. });
  57. })
  58. .catch(function(error) {
  59. throw error;
  60. });
  61. }
Add Comment
Please, Sign In to add comment