Coverage for docs_src/security/tutorial005_an_py310.py: 100%

93 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from datetime import datetime, timedelta, timezone 1abc

2from typing import Annotated 1abc

3 

4import jwt 1abc

5from fastapi import Depends, FastAPI, HTTPException, Security, status 1abc

6from fastapi.security import ( 1abc

7 OAuth2PasswordBearer, 

8 OAuth2PasswordRequestForm, 

9 SecurityScopes, 

10) 

11from jwt.exceptions import InvalidTokenError 1abc

12from passlib.context import CryptContext 1abc

13from pydantic import BaseModel, ValidationError 1abc

14 

15# to get a string like this run: 

16# openssl rand -hex 32 

17SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" 1abc

18ALGORITHM = "HS256" 1abc

19ACCESS_TOKEN_EXPIRE_MINUTES = 30 1abc

20 

21 

22fake_users_db = { 1abc

23 "johndoe": { 

24 "username": "johndoe", 

25 "full_name": "John Doe", 

26 "email": "johndoe@example.com", 

27 "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", 

28 "disabled": False, 

29 }, 

30 "alice": { 

31 "username": "alice", 

32 "full_name": "Alice Chains", 

33 "email": "alicechains@example.com", 

34 "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm", 

35 "disabled": True, 

36 }, 

37} 

38 

39 

40class Token(BaseModel): 1abc

41 access_token: str 1abc

42 token_type: str 1abc

43 

44 

45class TokenData(BaseModel): 1abc

46 username: str | None = None 1abc

47 scopes: list[str] = [] 1abc

48 

49 

50class User(BaseModel): 1abc

51 username: str 1abc

52 email: str | None = None 1abc

53 full_name: str | None = None 1abc

54 disabled: bool | None = None 1abc

55 

56 

57class UserInDB(User): 1abc

58 hashed_password: str 1abc

59 

60 

61pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") 1abc

62 

63oauth2_scheme = OAuth2PasswordBearer( 1abc

64 tokenUrl="token", 

65 scopes={"me": "Read information about the current user.", "items": "Read items."}, 

66) 

67 

68app = FastAPI() 1abc

69 

70 

71def verify_password(plain_password, hashed_password): 1abc

72 return pwd_context.verify(plain_password, hashed_password) 1abc

73 

74 

75def get_password_hash(password): 1abc

76 return pwd_context.hash(password) 1abc

77 

78 

79def get_user(db, username: str): 1abc

80 if username in db: 1abc

81 user_dict = db[username] 1abc

82 return UserInDB(**user_dict) 1abc

83 

84 

85def authenticate_user(fake_db, username: str, password: str): 1abc

86 user = get_user(fake_db, username) 1abc

87 if not user: 1abc

88 return False 1abc

89 if not verify_password(password, user.hashed_password): 1abc

90 return False 1abc

91 return user 1abc

92 

93 

94def create_access_token(data: dict, expires_delta: timedelta | None = None): 1abc

95 to_encode = data.copy() 1abc

96 if expires_delta: 1abc

97 expire = datetime.now(timezone.utc) + expires_delta 1abc

98 else: 

99 expire = datetime.now(timezone.utc) + timedelta(minutes=15) 1abc

100 to_encode.update({"exp": expire}) 1abc

101 encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) 1abc

102 return encoded_jwt 1abc

103 

104 

105async def get_current_user( 1abc

106 security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)] 

107): 

108 if security_scopes.scopes: 1abc

109 authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' 1abc

110 else: 

111 authenticate_value = "Bearer" 1abc

112 credentials_exception = HTTPException( 1abc

113 status_code=status.HTTP_401_UNAUTHORIZED, 

114 detail="Could not validate credentials", 

115 headers={"WWW-Authenticate": authenticate_value}, 

116 ) 

117 try: 1abc

118 payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) 1abc

119 username: str = payload.get("sub") 1abc

120 if username is None: 1abc

121 raise credentials_exception 1abc

122 token_scopes = payload.get("scopes", []) 1abc

123 token_data = TokenData(scopes=token_scopes, username=username) 1abc

124 except (InvalidTokenError, ValidationError): 1abc

125 raise credentials_exception 1abc

126 user = get_user(fake_users_db, username=token_data.username) 1abc

127 if user is None: 1abc

128 raise credentials_exception 1abc

129 for scope in security_scopes.scopes: 1abc

130 if scope not in token_data.scopes: 1abc

131 raise HTTPException( 1abc

132 status_code=status.HTTP_401_UNAUTHORIZED, 

133 detail="Not enough permissions", 

134 headers={"WWW-Authenticate": authenticate_value}, 

135 ) 

136 return user 1abc

137 

138 

139async def get_current_active_user( 1abc

140 current_user: Annotated[User, Security(get_current_user, scopes=["me"])], 

141): 

142 if current_user.disabled: 1abc

143 raise HTTPException(status_code=400, detail="Inactive user") 1abc

144 return current_user 1abc

145 

146 

147@app.post("/token") 1abc

148async def login_for_access_token( 1abc

149 form_data: Annotated[OAuth2PasswordRequestForm, Depends()], 

150) -> Token: 

151 user = authenticate_user(fake_users_db, form_data.username, form_data.password) 1abc

152 if not user: 1abc

153 raise HTTPException(status_code=400, detail="Incorrect username or password") 1abc

154 access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) 1abc

155 access_token = create_access_token( 1abc

156 data={"sub": user.username, "scopes": form_data.scopes}, 

157 expires_delta=access_token_expires, 

158 ) 

159 return Token(access_token=access_token, token_type="bearer") 1abc

160 

161 

162@app.get("/users/me/", response_model=User) 1abc

163async def read_users_me( 1abc

164 current_user: Annotated[User, Depends(get_current_active_user)], 

165): 

166 return current_user 1abc

167 

168 

169@app.get("/users/me/items/") 1abc

170async def read_own_items( 1abc

171 current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], 

172): 

173 return [{"item_id": "Foo", "owner": current_user.username}] 1abc

174 

175 

176@app.get("/status/") 1abc

177async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]): 1abc

178 return {"status": "ok"} 1abc