auth.resolver.ts 1.9 KB

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