Spaces:
Sleeping
Sleeping
| # routes/profile.py | |
| from flask import Blueprint, request, jsonify, g | |
| from bson.objectid import ObjectId | |
| from db import db | |
| import bcrypt | |
| from utils.auth import token_required | |
| from utils.validators import valid_password | |
| from datetime import datetime | |
| profile_bp = Blueprint("profile", __name__) | |
| def get_profile(): | |
| user = g.current_user.copy() | |
| user.pop("password", None) | |
| return jsonify(user) | |
| def update_profile(): | |
| data = request.json or {} | |
| allowed = ["name", "phone", "dob", "address", "profile_pic"] | |
| update = {} | |
| for k in allowed: | |
| if k in data: | |
| update[k] = data[k] | |
| if "dob" in update: | |
| # accept ISO string, store as string or parse to date as needed: | |
| try: | |
| update["dob"] = datetime.fromisoformat(update["dob"]).isoformat() | |
| except: | |
| pass | |
| if update: | |
| db.users.update_one({"_id": ObjectId(g.current_user["_id"])}, {"$set": update}) | |
| return jsonify({"message":"Profile updated"}) | |
| def change_password(): | |
| data = request.json or {} | |
| current = data.get("current_password", "") | |
| newpw = data.get("new_password", "") | |
| if not current or not newpw: | |
| return jsonify({"error":"Missing passwords"}), 400 | |
| # verify current | |
| user = db.users.find_one({"_id": ObjectId(g.current_user["_id"])}) | |
| if not bcrypt.checkpw(current.encode(), user["password"].encode()): | |
| return jsonify({"error":"Current password invalid"}), 401 | |
| if not valid_password(newpw): | |
| return jsonify({"error":"New password not strong enough"}), 400 | |
| hashed = bcrypt.hashpw(newpw.encode(), bcrypt.gensalt()).decode() | |
| db.users.update_one({"_id": user["_id"]}, {"$set": {"password": hashed}}) | |
| return jsonify({"message":"Password changed"}) | |