File size: 1,311 Bytes
6c9c901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from datetime import datetime
from typing import Optional

from bson import ObjectId

from ..database import get_collection


USERS_COLLECTION = "users"


def serialize_user(document) -> Optional[dict]:
    if not document:
        return None
    return {
        "id": str(document.get("_id")),
        "email": document.get("email"),
        "display_name": document.get("display_name"),
        "organization": document.get("organization"),
        "role": document.get("role"),
        "created_at": document.get("created_at"),
    }


async def get_users_collection():
    return get_collection(USERS_COLLECTION)


async def get_user_by_email(email: str) -> Optional[dict]:
    users = await get_users_collection()
    return await users.find_one({"email": email})


async def create_user(data: dict) -> dict:
    users = await get_users_collection()
    now = datetime.utcnow()
    payload = {
        **data,
        "created_at": now,
        "updated_at": now,
    }
    result = await users.insert_one(payload)
    payload["_id"] = result.inserted_id
    return payload


async def get_user_by_id(user_id: str) -> Optional[dict]:
    users = await get_users_collection()
    try:
        oid = ObjectId(user_id)
    except Exception:
        return None
    return await users.find_one({"_id": oid})