UNPKG

quickstruc

Version:

quickstruc is a Node.js-powered module designed to streamline project scaffolding.

125 lines (124 loc) 6.2 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const User_1 = require("../models/User"); const JwtServices_1 = __importDefault(require("../services/JwtServices")); const logger_1 = __importDefault(require("../utils/logger")); // Import the logger class AuthController { constructor() { } /** * Creates a new user account after validating the input. * @param {Request} req - The request object containing user signup data. * @param {Response} res - The response object used to send back the response. * @param {NextFunction} next - The next middleware function in the stack. * @returns {Object} - A JSON response with a success or error message. */ createUser(req, res, next) { return __awaiter(this, void 0, void 0, function* () { const { username, email, password, } = req.body; try { // Check if a user with the provided email already exists let hasAccount = yield User_1.User.findOne({ where: { email: email } }); if (hasAccount) { logger_1.default.warn(`Account already exists with email: ${email}`); // Log a warning if account exists return res.status(401).json({ status: "failed", message: "An account already exists with this email address.", }); } // Create a new user const newUser = new User_1.User({ username, email, password, // Assuming password is hashed in the User model via a pre-save hook }); // Save the user to the database yield newUser.save(); // Generate JWT token after successful user creation let token = JwtServices_1.default.generateToken({ id: newUser.id, }); // Log successful user creation logger_1.default.info(`New user created: ${newUser.email}`); // Uncomment to send a welcome email // await EmailServices.sendWelcomeEmail(newUser.email, newUser.username); return res.status(201).json({ status: "success", message: "User created successfully", token: token, // Send the token to the client }); } catch (err) { logger_1.default.error("Error creating user:", err); // Log the error return res.status(500).json({ status: "error", message: "Internal server error", }); } }); } /** * Handles user login by validating email and password. * @param {Request} req - The request object containing user login data. * @param {Response} res - The response object used to send back the response. * @param {NextFunction} next - The next middleware function in the stack. * @returns {Object} - A JSON response with a status message and JWT token on success. */ login(req, res, next) { return __awaiter(this, void 0, void 0, function* () { const { email, password } = req.body; try { // Await the result of the database query to check if user exists let hasAccount = yield User_1.User.findOne({ where: { email: email } }); // Check if the account exists if (hasAccount) { // Check if the password is valid const isPasswordValid = yield hasAccount.comparePassword(password); if (!isPasswordValid) { logger_1.default.warn(`Failed login attempt for email: ${email}`); // Log failed login attempt return res.status(401).json({ status: "error", message: "Invalid credentials", }); } // Generate JWT token after successful login let token = JwtServices_1.default.generateToken({ data: hasAccount.id }); // Log successful login logger_1.default.info(`User logged in successfully: ${hasAccount.email}`); return res.status(200).json({ status: "success", token: token, user: hasAccount, }); } else { logger_1.default.warn(`Account not found for email: ${email}`); // Log account not found return res.status(404).json({ status: "error", message: "Account not found", }); } } catch (error) { // Log error and send response in case of unexpected issues logger_1.default.error("Error during login:", error); // Log the error return res.status(500).json({ status: "error", message: "Internal server error", }); } }); } } exports.default = new AuthController();