added task_3

parent 841d3b17
import hashlib
import json
import hmac
import base64
from datetime import datetime, timedelta
import jwt
SECRET_KEY = 'BwzBFTfdNJfVWi2CY1BK9KQBDdb5auQR'
# Get tokens by jwt
def get_access_token(username: str) -> str:
payload = {
"sub": username,
"exp": datetime.utcnow() + timedelta(minutes=30)
}
return jwt.encode(payload, SECRET_KEY, algorithm='HS256')
def get_refresh_token(username: str) -> str:
payload = {
"sub": username,
"exp": datetime.utcnow() + timedelta(days=30)
}
return jwt.encode(payload, SECRET_KEY, algorithm='HS256')
def get_tokens_by_lib(username: str) -> dict:
access_token = get_access_token(username)
refresh_token = get_refresh_token(username)
return {"access_token": access_token, "refresh_token": refresh_token}
# Get tokens
def get_tokens(username: str) -> dict:
header = {"alg": "HS256", "typ": "JWT"}
access_payload = {
"sub": f"{username}",
"exp": (datetime.utcnow() + timedelta(minutes=30)).isoformat()
}
refresh_payload = {
"sub": f"{username}",
"exp": (datetime.utcnow() + timedelta(days=30)).isoformat()
}
encoded_header = base64.urlsafe_b64encode(
json.dumps(header).encode()
).decode('utf-8')
encoded_access_payload = base64.urlsafe_b64encode(
json.dumps(access_payload).encode()
).decode('utf-8')
encoded_refresh_payload = base64.urlsafe_b64encode(
json.dumps(refresh_payload).encode()
).decode('utf-8')
unsigned_access_token = encoded_header + '.' + encoded_access_payload
unsigned_refresh_token = encoded_header + '.' + encoded_refresh_payload
access_signature = hmac.new(SECRET_KEY.encode(), unsigned_access_token.encode(), hashlib.sha256).digest()
refresh_signature = hmac.new(SECRET_KEY.encode(), unsigned_refresh_token.encode(), hashlib.sha256).digest()
access = encoded_header + '.' + encoded_access_payload + '.' + base64.urlsafe_b64encode(access_signature).decode()
refresh = encoded_header + '.' + encoded_refresh_payload + '.' + base64.urlsafe_b64encode(refresh_signature).decode()
return {
"access": access,
"refresh": refresh
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment