File size: 1,205 Bytes
c6cc0f2
 
 
faa9d54
 
c6cc0f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faa9d54
 
 
 
 
 
 
 
 
 
 
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
from fastapi import HTTPException

from trauma.api.account.model import AccountModel
from trauma.api.common.db_requests import check_unique_fields_existence
from trauma.api.security.schemas import LoginAccountRequest, RegisterAccountRequest
from trauma.core.config import settings
from trauma.core.security import verify_password


async def authenticate_account(data: LoginAccountRequest) -> AccountModel:
    account = await settings.DB_CLIENT.accounts.find_one(
        {"email": data.email},
        collation={"locale": "en", "strength": 2})
    if account is None:
        raise HTTPException(status_code=404, detail="Invalid email or password.")

    account = AccountModel.from_mongo(account)

    if not verify_password(data.password, account.password):
        raise HTTPException(status_code=401, detail="Invalid email or password.")
    return account


async def register_account(data: RegisterAccountRequest) -> AccountModel:
    await check_unique_fields_existence("email", data.email)
    account = AccountModel(
        email=data.email,
        password=data.password,
        role=data.role,
    )
    await settings.DB_CLIENT.accounts.insert_one(account.to_mongo())
    return account