All files / src simple-auth.resolver.ts

100% Statements 21/21
100% Branches 8/8
100% Functions 4/4
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                      11x 10x   1x           1x   1x 1x         1x   3x 3x 3x       1x 10x 9x 9x 1x       9x 9x 9x   9x    
import { Inject, PipeTransform } from '@nestjs/common';
import { Args, Query, Resolver } from '@nestjs/graphql';
import { Ctx, EventBus, RequestContext } from '@vendure/core';
import { validate as isEmail } from 'isemail';
import { SIMPLE_AUTH_PLUGIN_OPTIONS } from './constants';
import { OneTimeCodeRequestedEvent } from './events';
import { ISimpleAuthPluginOptions } from './interfaces';
import { SimpleAuthService } from './simple-auth.service';
 
class EmailValidation implements PipeTransform<string,string> {
  transform(value: string): string {
    if (isEmail(value)) {
      return value.toLowerCase()
    }
    throw new Error(`${value} is not a valid email`);
  }
  
}
 
export class RequestOneTimeCodeError {
  readonly __typename = 'RequestOneTimeCodeError';
 
  constructor(private message: string, private errorCode: string) {
    console.log('runhere');
  }
}
 
@Resolver()
export class SimpleAuthResolver {
  constructor(
    @Inject(SimpleAuthService) private service: SimpleAuthService, 
    @Inject(EventBus) private eventBus: EventBus,
    @Inject(SIMPLE_AUTH_PLUGIN_OPTIONS) private pluginOptions: ISimpleAuthPluginOptions) {
    }
  
  @Query()
  async requestOneTimeCode(@Ctx() ctx: RequestContext, @Args('email', EmailValidation) email: string) {
    if (this.pluginOptions.preventCrossStrategies) {
      const foundStrategy = await this.service.checkCrossStrategies(ctx, email);
      if (foundStrategy) 
        return new RequestOneTimeCodeError(
          `Email already used with "${foundStrategy}" authentication`, 
          'CROSS_EMAIL_AUTHENTICATION')
    }
    const value = await this.service.generateCode(email);
    const fiteredValue = this.pluginOptions.isDev ? value : 'A code sent to your email';
    this.eventBus.publish(new OneTimeCodeRequestedEvent(value, email, ctx));
 
    return { __typename: 'OneTimeCode', value: fiteredValue };
  } 
}