All files google-auth.strategy.ts

94.44% Statements 17/18
87.5% Branches 14/16
100% Functions 4/4
94.44% Lines 17/18

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 52 53 54 55 56 57 58 59 60                      2x           2x             5x 5x 4x 4x 1x     3x   2x               2x     2x 1x   1x 1x           2x 2x 2x      
import { AuthenticationStrategy, ExternalAuthenticationService, Injector, RequestContext, User } from "@vendure/core";
import { DocumentNode } from "graphql";
import { gql } from 'graphql-tag';
import { GOOGLE_STRATEGY_NAME } from "./constants";
import { GoogleAuthData, UserExistedInAnotherStrategyError } from "./interfaces";
import { GoogleAuthService } from "./google-auth.service";
import { CrossStrategiesChecker } from "./cross-strategies-checker.service";
 
 
 
export class GoogleAuthStrategy implements AuthenticationStrategy {
    name: string = GOOGLE_STRATEGY_NAME;
    private googleService: GoogleAuthService;
    private externalAuthService: ExternalAuthenticationService;
    private crossStrategyChecker: CrossStrategiesChecker;
 
    defineInputType(): DocumentNode {
        return gql(`
            input GoogleAuthInput {
                token: String!
            }
        `);
    }
    async authenticate(ctx: RequestContext, data: GoogleAuthData): Promise<string | false | User> {
        try {
            const payload = await this.googleService.verify(data.token)
            let user = await this.externalAuthService.findCustomerUser(ctx, this.name, payload.email)
            if (user) {
                return user
            }
 
            await this.crossStrategyChecker.check(ctx, payload.email, this.name)
 
            user = await this.externalAuthService.createCustomerAndUser(ctx, {
                    emailAddress: payload.email,
                    externalIdentifier: payload.email,
                    strategy: this.name,
                    verified: payload.email_verified??false,
                    firstName: payload.given_name??'',
                    lastName: payload.family_name??''
                })
            return user
 
        } catch (err) {
            if (err instanceof UserExistedInAnotherStrategyError) {
                return err.message
            }
            Eif (typeof err === 'object' && err && 'message' in err && typeof err.message === 'string')
                return err.message
            return 'Unknown error'
        }
    }
 
    init(injector: Injector) {
        this.googleService = injector.get(GoogleAuthService);
        this.externalAuthService = injector.get(ExternalAuthenticationService);
        this.crossStrategyChecker = injector.get(CrossStrategiesChecker);
    }
 
}