-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_classes.py
More file actions
70 lines (59 loc) · 2.46 KB
/
auth_classes.py
File metadata and controls
70 lines (59 loc) · 2.46 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
from fastapi import FastAPI, Header, HTTPException, Depends, status, Response, Request, APIRouter, Form
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.security import OAuth2, OAuth2PasswordRequestForm
from fastapi.security.utils import get_authorization_scheme_param
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
from starlette.datastructures import URL
import datetime as dt
from typing import Dict, List, Optional
class Settings:
SECRET_KEY: str = "secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 # in mins
COOKIE_NAME = "access_token"
class OAuth2PasswordBearerWithCookie(OAuth2):
"""
This class is taken directly from FastAPI:
https://github.com/tiangolo/fastapi/blob/26f725d259c5dbe3654f221e608b14412c6b40da/fastapi/security/oauth2.py#L140-L171
The only change made is that authentication is taken from a cookie
instead of from the header!
"""
def __init__(
self,
tokenUrl: str,
scheme_name: Optional[str] = None,
scopes: Optional[Dict[str, str]] = None,
description: Optional[str] = None,
auto_error: bool = True,
):
if not scopes:
scopes = {}
flows = OAuthFlowsModel(password={"tokenUrl": tokenUrl, "scopes": scopes})
super().__init__(
flows=flows,
scheme_name=scheme_name,
description=description,
auto_error=auto_error,
)
async def __call__(self, request: Request) -> Optional[str]:
# IMPORTANT: this is the line that differs from FastAPI. Here we use
# `request.cookies.get(settings.COOKIE_NAME)` instead of
# `request.headers.get("Authorization")`
authorization: str = request.cookies.get(settings.COOKIE_NAME)
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
if self.auto_error:
return None
# raise HTTPException(
# status_code=status.HTTP_401_UNAUTHORIZED,
# detail="Not authenticated",
# headers={"WWW-Authenticate": "Bearer"}
# )
else:
return None
return param
settings = Settings()