auth.resolver.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { Args, Context, Mutation, Query, Resolver } from '@nestjs/graphql';
  2. import { Request } from 'express';
  3. import { Permission } from 'shared/generated-types';
  4. import { AUTH_TOKEN_KEY, REFRESH_TOKEN_KEY } from '../../../../shared/shared-constants';
  5. import { User } from '../../entity/user/user.entity';
  6. import { AuthService } from '../../service/providers/auth.service';
  7. import { ChannelService } from '../../service/providers/channel.service';
  8. import { Allow } from '../common/roles-guard';
  9. @Resolver('Auth')
  10. export class AuthResolver {
  11. constructor(private authService: AuthService, private channelService: ChannelService) {}
  12. /**
  13. * Attempts a login given the username and password of a user. If successful, returns
  14. * the user data and a token to be used by Bearer auth.
  15. */
  16. @Mutation()
  17. async login(@Args() args: { username: string; password: string }) {
  18. const { user, authToken, refreshToken } = await this.authService.createTokens(
  19. args.username,
  20. args.password,
  21. );
  22. if (authToken) {
  23. return {
  24. [AUTH_TOKEN_KEY]: authToken,
  25. [REFRESH_TOKEN_KEY]: refreshToken,
  26. user: this.publiclyAccessibleUser(user),
  27. };
  28. }
  29. }
  30. /**
  31. * Returns information about the current authenticated user.
  32. */
  33. @Query()
  34. @Allow(Permission.Authenticated)
  35. async me(@Context('req') request: Request & { user: User }) {
  36. const user = await this.authService.validateUser(request.user.identifier);
  37. return user ? this.publiclyAccessibleUser(user) : null;
  38. }
  39. /**
  40. * Exposes a subset of the User properties which we want to expose to the public API.
  41. */
  42. private publiclyAccessibleUser(user: User): any {
  43. return {
  44. id: user.id,
  45. identifier: user.identifier,
  46. roles: user.roles.reduce(
  47. (roleTypes, role) => [...roleTypes, ...role.permissions],
  48. [] as Permission[],
  49. ),
  50. channelTokens: this.getAvailableChannelTokens(user),
  51. };
  52. }
  53. private getAvailableChannelTokens(user: User): string[] {
  54. return user.roles.reduce((tokens, role) => role.channels.map(c => c.token), [] as string[]);
  55. }
  56. }