File size: 2,950 Bytes
14c4d51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from src.domain.schemas.user import UserCreate, UserLogin
from src.infrastructure.repositories.user_repository import UserRepository
from src.core.security import get_password_hash, verify_password, create_access_token
from fastapi import HTTPException, status

class UserUseCase:
    def __init__(self, repo: UserRepository):
        self.repo = repo

    async def register_user(self, user_in: UserCreate):
        existing_user = await self.repo.get_by_mobile(user_in.mobile)
        if existing_user:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="User already exists")
        
        user_dict = user_in.model_dump()
        hashed_pin = get_password_hash(user_dict.pop("pin"))
        user_dict["hashed_password"] = hashed_pin
        user_dict["role"] = "admin" if user_dict["relation"].lower() in ["admin", "mom", "dad"] else "member"

        return await self.repo.create(user_dict)

    async def authenticate_user(self, user_in: UserLogin):
        user = await self.repo.get_by_mobile(user_in.mobile)
        print(f"DEBUG AUTH: Trying to login mobile='{user_in.mobile}'")
        if not user:
            print("DEBUG AUTH: User not found in DB!")
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials (not found)")
        print(f"DEBUG AUTH: Found user: {user.get('mobile')}")
        valid_pwd = verify_password(user_in.pin, user["hashed_password"])
        print(f"DEBUG AUTH: Password valid? {valid_pwd}")
        if not valid_pwd:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials (bad pin)")
        
        token = create_access_token(subject=str(user["_id"]))
        user["id"] = str(user.pop("_id"))
        return {"access_token": token, "token_type": "bearer", "user": user}
        
    async def get_all_users(self):
        return await self.repo.get_all()

    async def delete_user(self, user_id: str):
        return await self.repo.delete(user_id)

    async def update_user(self, user_id: str, user_in):
        update_data = user_in.model_dump(exclude_unset=True)
        if "pin" in update_data:
            update_data["hashed_password"] = get_password_hash(update_data.pop("pin"))
        if "id" in update_data: del update_data["id"]
        return await self.repo.update(user_id, update_data)

    async def update_profile(self, user_in):
        # We assume the user profile to update will be derived from auth later
        # For now, we update based on mobile or just provide the logic
        update_data = user_in.model_dump(exclude_unset=True)
        if "pin" in update_data:
            update_data["hashed_password"] = get_password_hash(update_data.pop("pin"))
        # This implementation requires a way to identify the current user
        # For first pass we skip until we have a real JWT system if needed
        return {"msg": "Profile update logic ready"}