generated from OPCODE-Open-Spring-Fest/template
-
Notifications
You must be signed in to change notification settings - Fork 17
feat: added proper structure in backend and fixed email verification #60
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
04shubham7
merged 1 commit into
OPCODE-Open-Spring-Fest:main
from
ADARSHsri2004:feat/backend_restructure
Nov 4, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| // src/controllers/authController.ts | ||
| import { Request, Response } from "express"; | ||
| import jwt from "jsonwebtoken"; | ||
| import crypto from "crypto"; | ||
| import nodemailer from "nodemailer"; | ||
| import { User } from "../models/user.model"; | ||
|
|
||
| const JWT_SECRET = process.env.JWT_SECRET || "secretkey"; | ||
| const CLIENT_URL = process.env.CLIENT_URL || "http://localhost:3000"; | ||
|
|
||
| const transporter = nodemailer.createTransport({ | ||
| // service: "gmail", | ||
| // auth: { | ||
| // user: process.env.EMAIL_USER, | ||
| // pass: process.env.EMAIL_PASS, | ||
| // }, | ||
| host: 'smtp.ethereal.email', | ||
| port: 587, | ||
| auth: { | ||
| user: '[email protected]', | ||
| pass: 'Du8rSm184HzwwHsHYm' | ||
| } | ||
| }); | ||
|
|
||
| const generateToken = (id: string) => { | ||
| return jwt.sign({ id }, JWT_SECRET, { expiresIn: "7d" }); | ||
| }; | ||
|
|
||
| // Register user | ||
| export const register = async (req: Request, res: Response) => { | ||
| try { | ||
| const { name, email, password } = req.body; | ||
| const existingUser = await User.findOne({ email }); | ||
| if (existingUser) return res.status(400).json({ message: "User already exists" }); | ||
|
|
||
| const verificationToken = crypto.randomBytes(20).toString("hex"); | ||
| const user = await User.create({ name, email, password, verificationToken }); | ||
|
|
||
| const verificationLink = `${CLIENT_URL}/verify/${verificationToken}`; | ||
| await transporter.sendMail({ | ||
| to: email, | ||
| subject: "Verify your email", | ||
| html: `<p>Click <a href="${verificationLink}">here</a> to verify your account.</p>`, | ||
| }); | ||
|
|
||
| res.status(201).json({ message: "User registered. Check your email for verification link." }); | ||
| } catch (error) { | ||
| res.status(500).json({ message: "Registration failed", error }); | ||
| } | ||
| }; | ||
|
|
||
| // Verify email | ||
| export const verifyEmail = async (req: Request, res: Response) => { | ||
| try { | ||
| const { token } = req.params; | ||
| const user = await User.findOne({ verificationToken: token }); | ||
|
|
||
| if (!user) return res.status(400).json({ message: "Invalid or expired token" }); | ||
|
|
||
| user.isVerified = true; | ||
| user.verificationToken = undefined; | ||
| await user.save(); | ||
|
|
||
| res.status(200).json({ message: "Email verified successfully" }); | ||
| } catch (error) { | ||
| res.status(500).json({ message: "Verification failed", error }); | ||
| } | ||
| }; | ||
|
|
||
| // Login | ||
| export const login = async (req: Request, res: Response) => { | ||
| try { | ||
| const { email, password } = req.body; | ||
| const user = await User.findOne({ email }); | ||
|
|
||
| if (!user) return res.status(400).json({ message: "Invalid credentials" }); | ||
| if (!user.isVerified) return res.status(403).json({ message: "Please verify your email" }); | ||
|
|
||
| const isMatch = await user.comparePassword(password); | ||
| if (!isMatch) return res.status(400).json({ message: "Invalid credentials" }); | ||
|
|
||
| const token = generateToken(String(user._id)); | ||
| res.status(200).json({ token, user: { name: user.name, email: user.email } }); | ||
| } catch (error) { | ||
| res.status(500).json({ message: "Login failed", error }); | ||
| } | ||
| }; | ||
|
|
||
| // Get current user | ||
| export const getMe = async (req: Request, res: Response) => { | ||
| try { | ||
| const userId = (req as any).user?.id; | ||
| if (!userId) return res.status(401).json({ message: "Unauthorized" }); | ||
|
|
||
| const user = await User.findById(userId).select("-password"); | ||
| if (!user) return res.status(404).json({ message: "User not found" }); | ||
|
|
||
| res.status(200).json(user); | ||
| } catch (error) { | ||
| res.status(500).json({ message: "Error fetching user", error }); | ||
| } | ||
| }; |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,41 +1,28 @@ | ||
| import { Request, Response, NextFunction } from 'express'; | ||
| import { verifyAccessToken } from '../controllers/auth'; | ||
| // src/middlewares/authMiddleware.ts | ||
| import { Request, Response, NextFunction } from "express"; | ||
| import jwt from "jsonwebtoken"; | ||
| import { User } from "../models/user.model"; | ||
|
|
||
| export interface AuthenticatedRequest extends Request { | ||
| const JWT_SECRET = process.env.JWT_SECRET || "secretkey"; | ||
|
|
||
| export interface AuthRequest extends Request { | ||
| user?: any; | ||
| } | ||
|
|
||
| export type AuthRequest = AuthenticatedRequest; | ||
|
|
||
| // (Middleware file - authMiddleware.ts) | ||
| export const protect = async (req: AuthRequest, res: Response, next: NextFunction) => { | ||
| let token; | ||
|
|
||
| export function authenticate(req: AuthenticatedRequest, res: Response, next: NextFunction) { | ||
| const header = req.headers.authorization; | ||
| const token = header?.startsWith('Bearer ') ? header.slice(7) : undefined; | ||
|
|
||
| if (!token) { | ||
| // Use 401 for NO credentials (token missing entirely) | ||
| return res.status(401).json({ error: 'No token provided' }); | ||
| if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")) { | ||
| token = req.headers.authorization.split(" ")[1]; | ||
| } | ||
|
|
||
| if (!token) return res.status(401).json({ message: "Not authorized, no token" }); | ||
|
|
||
| try { | ||
| const payload = verifyAccessToken(token); | ||
| req.user = payload; | ||
| const decoded = jwt.verify(token, JWT_SECRET) as { id: string }; | ||
| req.user = await User.findById(decoded.id).select("-password"); | ||
| next(); | ||
| } catch { | ||
| // Use 403 for INVALID credentials (token present but invalid/expired/rejected) | ||
| // This is often seen as a better status for expired tokens. | ||
| return res.status(403).json({ error: 'Invalid or expired token' }); | ||
| } catch (error) { | ||
| res.status(401).json({ message: "Not authorized, token failed" }); | ||
| } | ||
| } | ||
| export function authorizeRole(role: string) { | ||
| return (req: AuthenticatedRequest, res: Response, next: NextFunction) => { | ||
| if (!req.user) { | ||
| return res.status(401).json({ error: 'Not authenticated' }); | ||
| } | ||
| if (req.user.role !== role) { | ||
| return res.status(403).json({ error: 'Forbidden' }); | ||
| } | ||
| next(); | ||
| }; | ||
| } | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.