-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathauth.py
More file actions
71 lines (61 loc) · 2.34 KB
/
auth.py
File metadata and controls
71 lines (61 loc) · 2.34 KB
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
61
62
63
64
65
66
67
68
69
70
71
from fastapi.security import OAuth2PasswordRequestForm
from fastapi import APIRouter, Depends, HTTPException, status
from datetime import timedelta
from app.db.session import get_db
from app.core import security
from app.core.auth import authenticate_user, sign_up_new_user
from app.core.enrichr import is_disposable_email
auth_router = r = APIRouter()
@r.post("/token")
async def login(
db=Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
):
user = authenticate_user(db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(
minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES
)
if user.is_superuser:
permissions = "admin"
else:
permissions = "user"
access_token = security.create_access_token(
data={"sub": user.email, "permissions": permissions},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
@r.post("/signup")
async def signup(
db=Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
):
# Block disposable/throwaway email addresses before touching the database.
# Requires ENRICHR_API_KEY in your environment — skipped silently if not set.
if await is_disposable_email(form_data.username):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Disposable email addresses are not allowed. Please use your real email.",
)
user = sign_up_new_user(db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Account already exists",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(
minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES
)
if user.is_superuser:
permissions = "admin"
else:
permissions = "user"
access_token = security.create_access_token(
data={"sub": user.email, "permissions": permissions},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}