Web API for code.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

64 lines
1.9 KiB

  1. import { RouteHandlerMethod } from 'fastify'
  2. import { Uuid } from '@theoryofnekomata/uuid-buffer'
  3. import { Controller } from 'src/packages/fastify-utils-theoryofnekomata'
  4. import { UserService, UserServiceImpl } from 'src/modules/user'
  5. import { LoginUserFormData } from 'src/modules/auth/models'
  6. import { SessionService, SessionServiceImpl } from 'src/modules/auth/Session.service'
  7. import {
  8. LoggedOutData,
  9. LoggedInData,
  10. UnableToLogInError,
  11. UnableToLogOutError,
  12. } from 'src/modules/auth/responses'
  13. export interface AuthController extends Controller<'logIn' | 'logOut'> {}
  14. export class AuthControllerImpl implements AuthController {
  15. private readonly sessionService: SessionService
  16. private readonly userService: UserService
  17. constructor() {
  18. this.sessionService = new SessionServiceImpl()
  19. this.userService = new UserServiceImpl()
  20. }
  21. readonly logIn: RouteHandlerMethod = async (request, reply) => {
  22. const { username, password } = request.body as LoginUserFormData
  23. try {
  24. const existingUser = await this.userService.getFromCredentials({
  25. username,
  26. password,
  27. })
  28. const newSession = await this.sessionService.create({
  29. userId: existingUser.id,
  30. })
  31. reply.sendData(new LoggedInData(newSession))
  32. } catch (causeRaw) {
  33. const cause = causeRaw as Error
  34. throw new UnableToLogInError(
  35. 'Authorization could not be performed on the credentials provided. Either try again later or ensure registration using the previous credentials.',
  36. { cause },
  37. )
  38. }
  39. }
  40. readonly logOut: RouteHandlerMethod = async (request, reply) => {
  41. const sessionId = request.session?.id;
  42. if (sessionId) {
  43. try {
  44. await this.sessionService.expire(Uuid.from(sessionId))
  45. reply.sendData(new LoggedOutData())
  46. return
  47. } catch {
  48. // noop
  49. }
  50. }
  51. throw new UnableToLogOutError(
  52. 'De-authorization could not be performed. Ensure session data is present and/or clear local data to carry out the operation.')
  53. }
  54. }