Moved permissions checking to a function

Permissions checking now happens in another function, code is now much cleaner
This commit is contained in:
2025-08-31 11:22:41 +01:00
parent 716a4c6148
commit 89f9b6d270

61
main.py
View File

@@ -44,15 +44,9 @@ except Exception as e:
app = Flask(__name__) app = Flask(__name__)
# Chat Details Endpoint: def checkUserPermission(token, permission):
# Get or change details about a chat using the chatId
# Arguments: token (required), details (required), model, name
@app.route('/api/chat/<_id>/details', methods = ['GET', 'POST'])
def getChatHistory(_id):
# Get user auth token
token = request.json['token']
# Find the correct user token in user db # Find the correct user token in user db
user = usersCollection.find_one({'tokens.token': token}, {"_id":1,"tokens":{"$elemMatch": {"token":token}}}) user = usersCollection.find_one({'tokens.token': token}, {"_id":1,"tokens":{"$elemMatch": {"token":token}}, "permissions":1})
# If the user exists, continue, otherwise return fail # If the user exists, continue, otherwise return fail
if (user): if (user):
# Convert _id to a string, python doesn't like ObjectId() # Convert _id to a string, python doesn't like ObjectId()
@@ -61,7 +55,26 @@ def getChatHistory(_id):
if (user['tokens'][0]['expiry'] > int(datetime.now().timestamp())): if (user['tokens'][0]['expiry'] > int(datetime.now().timestamp())):
# Store the userId # Store the userId
userId = user['_id'] userId = user['_id']
print(userId) if permission in user["permissions"]:
return True, userId
elif (permission == True):
return True, userId
else:
return False, "Incorrect permissions"
else:
return False, "Token is expired"
else:
return False, "Token doesn't exist"
# Chat Details Endpoint:
# Get or change details about a chat using the chatId
# Arguments: token (required), details (required), model, name
@app.route('/api/chat/<_id>/details', methods = ['GET', 'POST'])
def getChatHistory(_id):
# Get user auth token
token = request.json['token']
a, userId = checkUserPermission(token, True)
if (a == True):
# Get the request details # Get the request details
details = request.json['details'] details = request.json['details']
# If the user is trying to GET data # If the user is trying to GET data
@@ -99,8 +112,6 @@ def getChatHistory(_id):
return jsonify("Invalid Permissions") return jsonify("Invalid Permissions")
else: else:
return jsonify("User token is invalid") return jsonify("User token is invalid")
else:
return jsonify("User token is invalid")
# Chat creation endpoint # Chat creation endpoint
# Create a new chat # Create a new chat
@@ -109,20 +120,8 @@ def getChatHistory(_id):
def createChat(): def createChat():
# Get user auth token # Get user auth token
token = request.json['token'] token = request.json['token']
# Find the correct user token in user db a, userId = checkUserPermission(token, "createChat")
user = usersCollection.find_one({'tokens.token': token}, {"_id":1,"tokens":{"$elemMatch": {"token":token}}}) if (a == True):
# If the user exists, continue, otherwise return fail
if (user):
# Convert _id to a string, python doesn't like ObjectId()
user['_id'] = str(user['_id'])
# Check if the token expiry is after the current date (Using unix timestamp, other mongodb Date datatype is a pain to use in python)
if (user['tokens'][0]['expiry'] > int(datetime.now().timestamp())):
# Store the userId
userId = user['_id']
print(user)
print(user['permissions'])
if ("createChat" in user['permissions']):
print(userId)
name = request.json['name'] name = request.json['name']
model = request.json['model'] model = request.json['model']
chatCollection.insert_one( chatCollection.insert_one(
@@ -143,10 +142,6 @@ def createChat():
} }
) )
return jsonify("Success") return jsonify("Success")
else:
return jsonify("Incorrect permissions")
else:
return jsonify("User token is invalid")
else: else:
return jsonify("User token is invalid") return jsonify("User token is invalid")
@@ -167,15 +162,11 @@ def index():
if (token == 'none'): if (token == 'none'):
return render_template('login.html', appName=appName, githubUrl=github_auth_endpoint, githublogin=settings["github_oauth"]["enabled"], oauthlogin=settings["oauth_login"]) return render_template('login.html', appName=appName, githubUrl=github_auth_endpoint, githublogin=settings["github_oauth"]["enabled"], oauthlogin=settings["oauth_login"])
else: else:
user = usersCollection.find_one({'tokens.token': token}, {"_id":1,"tokens":{"$elemMatch": {"token":token}}}) a, userId = checkUserPermission(token, True)
if (user): if (a == True):
user['_id'] = str(user['_id'])
if (user['tokens'][0]['expiry'] > int(datetime.now().timestamp())):
return render_template('home.html', appName=appName) return render_template('home.html', appName=appName)
else: else:
render_template('logout.html', appName=appName) render_template('logout.html', appName=appName)
else:
render_template('logout.html', appName=appName)
# Login endpoint # Login endpoint
# Api backend for login screen, check for user and returns token # Api backend for login screen, check for user and returns token