gitscope
https://dev.kronoz.win/r/marzneshin.git
app/utils/auth.py · v0.4.0
Source
1 a47eb4c Dawsh 2y ago from datetime import datetime, timedelta
2 a47eb4c Dawsh 2y ago from typing import Union
3 a47eb4c Dawsh 2y ago
4 e652421 Dawsh 2y ago import jwt
5 a47eb4c Dawsh 2y ago
6 8111eb7 Dawsh 2y ago from app.config import get_secret_key
7 8111eb7 Dawsh 2y ago from app.config.env import JWT_ACCESS_TOKEN_EXPIRE_MINUTES
8 a47eb4c Dawsh 2y ago
9 a47eb4c Dawsh 2y ago
10 a47eb4c Dawsh 2y ago def create_admin_token(username: str, is_sudo=False) -> str:
11 01cdf2e Dawsh 2y ago data = {
12 01cdf2e Dawsh 2y ago "sub": username,
13 01cdf2e Dawsh 2y ago "access": "sudo" if is_sudo else "admin",
14 01cdf2e Dawsh 2y ago "iat": datetime.utcnow(),
15 01cdf2e Dawsh 2y ago }
16 a47eb4c Dawsh 2y ago if JWT_ACCESS_TOKEN_EXPIRE_MINUTES > 0:
17 f1ab16c Dawsh 2y ago expire = datetime.utcnow() + timedelta(
18 f1ab16c Dawsh 2y ago minutes=JWT_ACCESS_TOKEN_EXPIRE_MINUTES
19 f1ab16c Dawsh 2y ago )
20 a47eb4c Dawsh 2y ago data["exp"] = expire
21 a47eb4c Dawsh 2y ago encoded_jwt = jwt.encode(data, get_secret_key(), algorithm="HS256")
22 a47eb4c Dawsh 2y ago return encoded_jwt
23 a47eb4c Dawsh 2y ago
24 a47eb4c Dawsh 2y ago
25 a47eb4c Dawsh 2y ago def get_admin_payload(token: str) -> Union[dict, None]:
26 a47eb4c Dawsh 2y ago try:
27 a47eb4c Dawsh 2y ago payload = jwt.decode(token, get_secret_key(), algorithms=["HS256"])
28 7b55c27 dawsh 2y ago except jwt.InvalidTokenError:
29 a47eb4c Dawsh 2y ago return
30 e652421 Dawsh 2y ago
31 e652421 Dawsh 2y ago username: str = payload.get("sub")
32 e652421 Dawsh 2y ago access: str = payload.get("access")
33 e652421 Dawsh 2y ago if not username or access not in ("admin", "sudo"):
34 e652421 Dawsh 2y ago return
35 e652421 Dawsh 2y ago try:
36 e652421 Dawsh 2y ago created_at = datetime.utcfromtimestamp(payload["iat"])
37 e652421 Dawsh 2y ago except KeyError:
38 e652421 Dawsh 2y ago created_at = None
39 e652421 Dawsh 2y ago
40 e652421 Dawsh 2y ago return {
41 e652421 Dawsh 2y ago "username": username,
42 e652421 Dawsh 2y ago "is_sudo": access == "sudo",
43 e652421 Dawsh 2y ago "created_at": created_at,
44 e652421 Dawsh 2y ago }