All files / src/controllers/system-controller logInUserWithGoogle.js

0% Statements 0/19
0% Branches 0/8
0% Functions 0/1
0% Lines 0/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                                                                   
import UsersModel from "../../models/Users.js";
import googleAccountGetter from "../../utilities/googleAccountGetter.js";
import messageResponse from "../../utilities/messageResponse.js";
import { generateJWT } from "../../utilities/jwtUtilities.js";
import { compareSync } from "bcrypt";
 
export default async function logInUserWithGoogle(googleUserAccessToken) {
    try {
        const response = await googleAccountGetter(googleUserAccessToken);
        const { googleResponse, ok } = response
        if (ok) {
            const projection = { userPassword: 1, signingMethod: 1 }
            const userData = await UsersModel.findOne({ userEmail: googleResponse.email }, projection);
            if (userData) {
                if (userData.signingMethod === "Google") {
                    const correctPassword = compareSync(googleResponse.sub, userData.userPassword);
                    if (correctPassword) {
                        const userId = userData._id;
                        const token = generateJWT({ userId, role: "user" })
                        return { status: 200, response: { ok: true, userId, accessToken: token } };
                    } else {
                        return messageResponse("Authorization Failed")
                    }
                }
                else return messageResponse("This email signed up with another sign up method")
            }
            else return messageResponse("This email did not signed up with us before, Go to Sign up page")
        }
        else return googleResponse
    } catch (error) {
        console.log(error);
        return messageResponse("There is unexpected error happened")
    }
}