-
-
Notifications
You must be signed in to change notification settings - Fork 20
Add Forgot Password feature with backend and frontend integration #59
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
MIHIR2006
merged 9 commits into
MIHIR2006:main
from
AvaneeshKesavan:forgot-password-feature
Sep 16, 2025
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
761e990
Implement forgot password feature with frontend and backend updates
AvaneeshKesavan ceb26d9
Update backend/app/routers/auth.py
AvaneeshKesavan 63a0ea2
Update backend/app/routers/auth.py
AvaneeshKesavan ab6836c
Update backend/app/routers/auth.py
AvaneeshKesavan 07ad6b6
Update backend/app/routers/auth.py
AvaneeshKesavan 71c37b2
Update frontend/app/forgot-password/page.tsx
AvaneeshKesavan 73396ae
Delete frontend/.env
AvaneeshKesavan 60e9797
Fix: add missing react-hot-toast dependency
AvaneeshKesavan 8ab10e1
Resolve merge conflicts
AvaneeshKesavan 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
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,19 @@ | ||
| from sqlalchemy import create_engine | ||
| from sqlalchemy.orm import sessionmaker, declarative_base | ||
| import os | ||
|
|
||
| DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./stockvision.db") | ||
|
|
||
| # For SQLite + multithreading with FastAPI, use connect_args | ||
| connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {} | ||
|
|
||
| engine = create_engine(DATABASE_URL, connect_args=connect_args, echo=False) | ||
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | ||
| Base = declarative_base() | ||
|
|
||
| def get_db(): | ||
| db = SessionLocal() | ||
| try: | ||
| yield db | ||
| finally: | ||
| db.close() |
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,78 @@ | ||
| from fastapi import APIRouter, Depends, HTTPException, status | ||
| from sqlalchemy.orm import Session | ||
| from datetime import datetime, timedelta | ||
| from pydantic import EmailStr | ||
| import secrets | ||
| import os | ||
| import smtplib | ||
| from email.mime.text import MIMEText | ||
| from passlib.context import CryptContext | ||
|
|
||
| from app.db import get_db | ||
| from app.user_models import UserDB | ||
| from app.models import ForgotPasswordRequest, ResetPasswordRequest | ||
|
|
||
| router = APIRouter(prefix="/auth", tags=["Auth"]) | ||
|
|
||
| pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") | ||
|
|
||
| # Signup (for testing/demo) | ||
| @router.post("/signup") | ||
| def signup(email: EmailStr, password: str, db: Session = Depends(get_db)): | ||
| user = db.query(UserDB).filter(UserDB.email == email).first() | ||
| if user: | ||
| raise HTTPException(status_code=400, detail="User already exists") | ||
| hashed = pwd_context.hash(password) | ||
| new_user = UserDB(email=email, hashed_password=hashed) | ||
| db.add(new_user) | ||
| db.commit() | ||
| db.refresh(new_user) | ||
| return {"message": "User registered successfully"} | ||
|
|
||
| # Forgot password | ||
| @router.post("/forgot-password") | ||
| def forgot_password(payload: ForgotPasswordRequest, db: Session = Depends(get_db)): | ||
| user = db.query(UserDB).filter(UserDB.email == payload.email).first() | ||
| generic_response = {"message": "If an account with that email exists, a reset link has been sent."} | ||
| if not user: | ||
| return generic_response | ||
|
|
||
| token = secrets.token_urlsafe(32) | ||
| expiry = datetime.utcnow() + timedelta(minutes=15) | ||
| user.reset_token = token | ||
| user.reset_token_expiry = expiry | ||
| db.add(user) | ||
| db.commit() | ||
|
|
||
| reset_link = f"{os.getenv('FRONTEND_URL', 'https://stock-vision-seven.vercel.app')}/reset-password/{token}" | ||
|
|
||
| msg = MIMEText(f"Click to reset your password: {reset_link}") | ||
| msg["Subject"] = "StockVision Password Reset" | ||
| msg["From"] = os.getenv("EMAIL_USER") | ||
| msg["To"] = user.email | ||
|
|
||
| try: | ||
| smtp_server = os.getenv("SMTP_SERVER", "smtp.gmail.com") | ||
| smtp_port = int(os.getenv("SMTP_PORT", 587)) | ||
| with smtplib.SMTP(smtp_server, smtp_port) as server: | ||
| server.starttls() | ||
| server.login(os.getenv("EMAIL_USER"), os.getenv("EMAIL_PASS")) | ||
| server.send_message(msg) | ||
| except smtplib.SMTPException as e: | ||
| # TODO: Log the error `e` for debugging purposes. | ||
| raise HTTPException(status_code=500, detail="Could not send email. Please try again later.") | ||
|
|
||
| return generic_response | ||
|
|
||
| # Reset password | ||
| @router.post("/reset-password") | ||
| def reset_password(payload: ResetPasswordRequest, db: Session = Depends(get_db)): | ||
| user = db.query(UserDB).filter(UserDB.reset_token == payload.token).first() | ||
| if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow(): | ||
| raise HTTPException(status_code=400, detail="Invalid or expired token") | ||
| user.hashed_password = pwd_context.hash(payload.new_password) | ||
| user.reset_token = None | ||
| user.reset_token_expiry = None | ||
| db.add(user) | ||
| db.commit() | ||
| return {"message": "Password has been reset successfully"} |
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,15 @@ | ||
| from sqlalchemy import Column, Integer, String, DateTime, Boolean | ||
| from datetime import datetime | ||
| from .db import Base | ||
|
|
||
| class UserDB(Base): | ||
| __tablename__ = "users" | ||
|
|
||
| id = Column(Integer, primary_key=True, index=True) | ||
| email = Column(String, unique=True, index=True, nullable=False) | ||
| hashed_password = Column(String, nullable=False) | ||
| reset_token = Column(String, nullable=True, index=True) | ||
| reset_token_expiry = Column(DateTime, nullable=True) | ||
| is_active = Column(Boolean, default=True) | ||
| created_at = Column(DateTime, default=datetime.utcnow) | ||
| updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) |
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
Binary file not shown.
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,73 @@ | ||
| "use client"; | ||
| import { useState } from "react"; | ||
| import { useRouter } from "next/navigation"; | ||
| import toast, { Toaster } from "react-hot-toast"; | ||
|
|
||
| export default function ForgotPasswordPage() { | ||
| const [email, setEmail] = useState(""); | ||
| const [loading, setLoading] = useState(false); | ||
| const router = useRouter(); | ||
|
|
||
| const handleSubmit = async (e: React.FormEvent) => { | ||
| e.preventDefault(); | ||
| setLoading(true); | ||
|
|
||
| try { | ||
| const res = await fetch( | ||
| `${process.env.NEXT_PUBLIC_BACKEND_URL}/auth/forgot-password`, | ||
| { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ email }), | ||
| } | ||
| ); | ||
| const data = await res.json(); | ||
| if (!res.ok) { | ||
| toast.error("Unable to send reset link. Please try again later."); | ||
| } else { | ||
| toast.success("Password reset link sent to your email!"); | ||
| } | ||
| } catch (err) { | ||
| toast.error("Unable to send reset link. Try again later."); | ||
| } finally { | ||
| setLoading(false); | ||
| } | ||
| }; | ||
|
|
||
| return ( | ||
| <main className="flex flex-col items-center justify-center min-h-screen bg-gray-50 dark:bg-gray-900"> | ||
| <Toaster position="top-center" reverseOrder={false} /> | ||
| <div className="w-full max-w-md mx-auto mt-20 p-8 bg-white dark:bg-gray-800 rounded-3xl shadow-2xl border border-gray-200 dark:border-gray-700"> | ||
| <h1 className="text-2xl md:text-3xl font-bold text-center text-gray-900 dark:text-white mb-8"> | ||
| Forgot Password | ||
| </h1> | ||
| <form onSubmit={handleSubmit} className="flex flex-col gap-4"> | ||
| <input | ||
| type="email" | ||
| placeholder="Enter your email" | ||
| value={email} | ||
| onChange={(e) => setEmail(e.target.value)} | ||
| className="w-full px-4 py-3 rounded-xl bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:focus:ring-blue-400 dark:focus:border-blue-400 transition-all duration-200" | ||
| required | ||
| /> | ||
| <button | ||
| type="submit" | ||
| className="w-full px-4 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-xl shadow-lg font-semibold transition-all duration-200" | ||
| disabled={loading} | ||
| > | ||
| {loading ? "Sending..." : "Send Reset Link"} | ||
| </button> | ||
| </form> | ||
| <div className="text-center mt-6 text-gray-600 dark:text-gray-300"> | ||
| Remember your password?{" "} | ||
| <button | ||
| onClick={() => router.push("/login")} | ||
| className="text-blue-600 dark:text-blue-400 hover:underline" | ||
| > | ||
| Sign In | ||
| </button> | ||
| </div> | ||
| </div> | ||
| </main> | ||
| ); | ||
| } |
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
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.