UNPKG

universal_authentication

Version:

Seamless and Secure Authentication for Modern Web Applications: Easily integrate OTP-based email verification, Google OAuth, GitHub, Microsoft, and Okta login into your Node.js app. Modular, flexible, and database-agnostic, this package simplifies user au

76 lines (75 loc) 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.loginHandler = exports.signupHandler = void 0; const password_utils_1 = require("../utils/password.utils"); const validation_utils_1 = require("../utils/validation.utils"); // Signup Handler Function const signupHandler = async (email, password, name, config) => { try { // Validation for email, password, and check if the user already exists if (!(0, validation_utils_1.validateEmail)(email)) { return { status: 400, message: "Invalid email format" }; } if (!(0, validation_utils_1.validatePassword)(password)) { return { status: 400, message: "Invalid password format" }; } if (await config.checkUserExist?.(email)) { return { status: 409, message: "Email already exists" }; } // Generation of secureKey, password hashing const secureKey = config.generateSecureKey ? config.generateSecureKey() : "defaultKey"; const hashedPassword = await (0, password_utils_1.hashPassword)(password, secureKey, config.hashAlgorithm ?? "crypto"); // Create a user const user = await config.createUser?.({ email, name, }); // Create an auth record for the user if (user) { await config.createAuthRecord?.({ userId: user.id, password: hashedPassword, secureKey, ipAddress: "0.0.0.0", lastLogin: new Date(), userAgent: "unknown", }); return { status: 201, message: "User created successfully", user }; } else { return { status: 500, message: "User creation failed" }; } } catch (err) { console.error(err); return { status: 500, message: err.message }; } }; exports.signupHandler = signupHandler; // Login Handler Function const loginHandler = async (email, password, config) => { try { // Check if the user and auth record are present const user = await config.getUserByEmail?.(email); if (!user) { return { status: 401, message: "Invalid email or password" }; } const authRecord = await config.getAuthRecord?.(user.id); if (!authRecord) { return { status: 401, message: "Invalid email or password" }; } // Check if the password is valid const isPasswordValid = await (0, password_utils_1.verifyPassword)(password, authRecord.secureKey, authRecord.password, config.hashAlgorithm ?? "crypto"); if (!isPasswordValid) { return { status: 401, message: "Invalid email or password" }; } return { status: 200, message: "Login successful", user }; } catch (err) { console.error(err); return { status: 500, message: err.message }; } }; exports.loginHandler = loginHandler;