auth.resolver.ts 2.0 KB

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