Spaces:
Running
Running
File size: 6,729 Bytes
ac3c54a 294884c bbd997e ac3c54a d951fea bbd997e d951fea ac3c54a bbd997e ac3c54a bbd997e ac3c54a d951fea 5dbdab3 294884c d951fea ac3c54a bbd997e aee3aac bbd997e ac3c54a 97aa98f c136b4b 97aa98f 5c6cdb1 c136b4b 97aa98f c136b4b 97aa98f 294884c 97aa98f ac3c54a d951fea 5dbdab3 294884c d951fea 5dbdab3 ac3c54a c644472 6adb51f c644472 aee3aac c644472 |
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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
import datetime
from bson import ObjectId
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=5)
from controller.streaksManagement import streaks_manager
from pymongo import MongoClient
from cryptography.fernet import Fernet
from dotenv import load_dotenv
import redis
import os
load_dotenv()
REDIS_HOST = os.getenv('REDIS_HOST', 'localhost')
REDIS_PORT = int(os.getenv('REDIS_PORT', 6379))
REDIS_PASSWORD = os.getenv('REDIS_PASSWORD', None)
FERNET_SECRET_KEY = os.getenv('FERNET_SECRET_KEY')
REDIS_USERNAME=os.getenv('REDIS_USERNAME')
fernet = Fernet(FERNET_SECRET_KEY)
r = redis.StrictRedis(
host=REDIS_HOST,
port=REDIS_PORT,
password=REDIS_PASSWORD,
username=REDIS_USERNAME,
db=0,
decode_responses=True
)
# Function to store an access token in Redis with an expiration time
def store_access_token(user_id: str, access_token: str, expiration_time_seconds: int = 4400):
"""Store the access token in Redis after encrypting it."""
# Store the encrypted token in Redis with expiration time
r.setex(f"{user_id}.{access_token}", expiration_time_seconds,value=access_token)
# Function to check if an access token is valid
def check_cache_for_accesstokens(user_id: str, access_token: str):
"""Check if the access token is valid."""
token_value = r.get(f"{user_id}.{access_token}")
if token_value:
return True
else:
return False
def isexpired(previous_date):
# Get the current date and time
current_date =datetime.datetime.now()
# Convert the previous date (which is a string) to a datetime object
# Compare the two dates
if current_date > previous_date:
return True
else:
return False
def create_accessToken(db_uri: str, user_id: str, refresh_token: str) -> str:
from pymongo import MongoClient
current_time = datetime.datetime.now()
expire_at = current_time + datetime.timedelta(minutes=130)
"""
Inserts a new document into the specified MongoDB collection.
Parameters:
db_uri (str): MongoDB connection URI.
db_name (str): Name of the database.
collection_name (str): Name of the collection.
document (dict): The document to insert.
Returns:
str: The ID of the inserted document.
"""
client = MongoClient(db_uri)
db = client["crayonics"]
collection = db["AccessToken"]
collection.find_one_and_delete({"refresh_token":refresh_token})
result = collection.insert_one({"user_id":user_id,"refresh_token":refresh_token,"current_time":current_time,"expire_at":expire_at})
store_access_token(user_id=user_id,access_token=str(result.inserted_id))
client.close()
return str(result.inserted_id)
def create_refreshToken(db_uri: str, user_id: str) -> str:
from pymongo import MongoClient
current_time = datetime.datetime.now()
expire_at = current_time + datetime.timedelta(days=30)
"""
Inserts a new document into the specified MongoDB collection.
Parameters:
db_uri (str): MongoDB connection URI.
user_id (str): id of user .
Returns:
str: The ID of the inserted document.
"""
client = MongoClient(db_uri)
db = client["crayonics"]
collection = db["RefreshToken"]
result = collection.insert_one({"user_id":user_id,"current_time":current_time,"expire_at":expire_at,"previous_access_token":"None"})
streaks_doc={}
streaks_doc['user_id'] = str(user_id)
# executor.submit(streaks_manager,db_uri=db_uri,document=streaks_doc)
streaks_manager(db_uri=db_uri,document=streaks_doc)
client.close()
return str(result.inserted_id)
# Close the connection
def update_refreshTokenWithPreviouslyUsedAccessToken(db_uri: str, refresh_token: str,access_token:str) -> bool:
from pymongo import MongoClient
"""
"""
# Connect to MongoDB
client = MongoClient(db_uri)
db = client["crayonics"]
collection = db["RefreshToken"]
# Insert the document
try:
collection.update_one(
{"_id":ObjectId(oid=refresh_token) }, # Filter (find the document by user_id)
{"$set": {"previous_access_token": access_token}} # Add or update the field
)
client.close()
return True
except:
return False
def verify_access_token(db_uri: str, user_id: str, access_token: str) -> bool:
is_valid = check_cache_for_accesstokens(user_id=user_id,access_token=access_token)
if is_valid==True:
streaks_doc={}
streaks_doc['user_id'] = str(user_id)
executor.submit(streaks_manager,db_uri=db_uri,document=streaks_doc)
return True
# Connect to MongoDB
else:
return False
def verify_refresh_access_token(db_uri: str, user_id: str, access_token: str,refresh_token:str) -> bool:
current_time = datetime.datetime.now()
"""
"""
# Connect to MongoDB
client = MongoClient(db_uri)
db = client["crayonics"]
collection = db["RefreshToken"]
docs = collection.find({"_id":ObjectId(refresh_token),"user_id":user_id,"previous_access_token":access_token})
for doc in docs:
if doc==None:
return False
else:
if str(doc['previous_access_token']) == access_token:
streaks_doc={}
streaks_doc['user_id'] = str(user_id)
# executor.submit(streaks_manager,db_uri=db_uri,document=streaks_doc)
streaks_manager(db_uri=db_uri,document=streaks_doc)
return True
else:
streaks_doc={}
streaks_doc['user_id'] = str(user_id)
# executor.submit(streaks_manager,db_uri=db_uri,document=streaks_doc)
streaks_manager(db_uri=db_uri,document=streaks_doc)
pass
return False
def logout_func(db_uri: str, refresh_token: str) -> str:
from pymongo import MongoClient
current_time = datetime.datetime.now()
expire_at = current_time + datetime.timedelta(days=30)
"""
Inserts a new document into the specified MongoDB collection.
Parameters:
db_uri (str): MongoDB connection URI.
user_id (str): id of user .
Returns:
str: The ID of the inserted document.
"""
# Connect to MongoDB
client = MongoClient(db_uri)
db = client["crayonics"]
collection = db["RefreshToken"]
# Insert the document
result = collection.find_one_and_delete(filter={"_id":ObjectId(refresh_token)})
print(result)
if result==None:
return result
return True
# Close the connection
|