This repository was archived by the owner on May 26, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathsecurity.py
More file actions
191 lines (140 loc) · 5.4 KB
/
security.py
File metadata and controls
191 lines (140 loc) · 5.4 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
from datetime import datetime, timedelta
from typing import Callable, List, Optional, Union
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from sqlmodel import Field, Relationship, Session, SQLModel
from project_name.models.content import Content, ContentResponse
from .config import settings
from .db import engine
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
SECRET_KEY = settings.security.secret_key
ALGORITHM = settings.security.algorithm
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: Optional[str] = None
class HashedPassword(str):
"""Takes a plain text password and hashes it.
use this as a field in your SQLModel
class User(SQLModel, table=True):
username: str
password: HashedPassword
"""
@classmethod
def __get_validators__(cls):
# one or more validators may be yielded which will be called in the
# order to validate the input, each validator will receive as an input
# the value returned from the previous validator
yield cls.validate
@classmethod
def validate(cls, v):
"""Accepts a plain text password and returns a hashed password."""
if not isinstance(v, str): # pragma: no coverage
raise TypeError("string required")
hashed_password = get_password_hash(v)
# you could also return a string here which would mean model.password
# would be a string, pydantic won't care but you could end up with some
# confusion since the value's type won't match the type annotation
# exactly
return cls(hashed_password)
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
username: str = Field(sa_column_kwargs={"unique": True})
password: HashedPassword
superuser: bool = False
disabled: bool = False
# it populates the .user attribute on the Content Model
contents: List["Content"] = Relationship(back_populates="user")
class UserResponse(BaseModel):
"""This is the User model to be used as a response_model
it doesn't include the password.
"""
id: int
username: str
disabled: bool
superuser: bool
contents: Optional[List[ContentResponse]] = Field(default_factory=list)
class UserCreate(BaseModel):
"""This is the User model to be used when creating a new user."""
username: str
password: str
superuser: bool = False
disabled: bool = False
class UserPasswordPatch(SQLModel):
"""This is to accept password for changing"""
password: str
password_confirm: str
def verify_password(plain_password, hashed_password) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password) -> str:
return pwd_context.hash(password)
def create_access_token(
data: dict, expires_delta: Optional[timedelta] = None
) -> str:
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else: # pragma: no cover
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def authenticate_user(
get_user: Callable, username: str, password: str
) -> Union[User, bool]:
user = get_user(username)
if not user:
return False
if not verify_password(password, user.password):
return False
return user
def get_user(username) -> Optional[User]:
with Session(engine) as session:
return session.query(User).where(User.username == username).first()
def get_current_user(
token: str = Depends(oauth2_scheme), request: Request = None
) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
if request:
if authorization := request.headers.get("authorization"):
try:
token = authorization.split(" ")[1]
except IndexError: # pragma: no cover
raise credentials_exception
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_data = TokenData(username=username)
except JWTError:
raise credentials_exception
user = get_user(username=token_data.username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(
current_user: User = Depends(get_current_user),
) -> User:
if current_user.disabled: # pragma: no cover
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
AuthenticatedUser = Depends(get_current_active_user)
async def get_current_admin_user(
current_user: User = Depends(get_current_user),
) -> User:
if not current_user.superuser: # pragma: no cover
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Not an admin user"
)
return current_user
AdminUser = Depends(get_current_admin_user)