File size: 1,254 Bytes
a317be6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from datetime import datetime
from typing import Optional
from bson import ObjectId


class User:
    """User model for MongoDB."""
    
    collection_name = "users"
    
    def __init__(
        self,
        email: str,
        hashed_password: str,
        created_at: Optional[datetime] = None,
        _id: Optional[ObjectId] = None
    ):
        self._id = _id or ObjectId()
        self.email = email
        self.hashed_password = hashed_password
        self.created_at = created_at or datetime.utcnow()
    
    def to_dict(self) -> dict:
        """Convert user to dictionary for MongoDB insertion."""
        return {
            "_id": self._id,
            "email": self.email,
            "hashed_password": self.hashed_password,
            "created_at": self.created_at
        }
    
    @classmethod
    def from_dict(cls, data: dict) -> "User":
        """Create User instance from MongoDB document."""
        return cls(
            _id=data.get("_id"),
            email=data.get("email"),
            hashed_password=data.get("hashed_password"),
            created_at=data.get("created_at")
        )
    
    @property
    def id(self) -> str:
        """Get string representation of user ID."""
        return str(self._id)