Moved permissions checking to a function
Permissions checking now happens in another function, code is now much cleaner
This commit is contained in:
167
main.py
167
main.py
@@ -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,44 +55,61 @@ 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"]:
|
||||||
# Get the request details
|
return True, userId
|
||||||
details = request.json['details']
|
elif (permission == True):
|
||||||
# If the user is trying to GET data
|
return True, userId
|
||||||
if (request.method == 'GET'):
|
|
||||||
# Get the chat from the chatId
|
|
||||||
returnedChat = chatCollection.find_one({'_id': ObjectId(_id)})
|
|
||||||
# Convert chatId into string
|
|
||||||
returnedChat['_id'] = str(returnedChat['_id'])
|
|
||||||
try:
|
|
||||||
returnedChat["permissions"][userId].index("view")
|
|
||||||
print("Chat " + _id + " has been found with token " + token)
|
|
||||||
# Check for detail type and return correct value from db
|
|
||||||
if (details == "history"):
|
|
||||||
return jsonify(returnedChat["messages"])
|
|
||||||
elif (details == "users"):
|
|
||||||
return jsonify(returnedChat["permissions"])
|
|
||||||
elif (details == "model"):
|
|
||||||
return jsonify(returnedChat["model"])
|
|
||||||
elif (details == "name"):
|
|
||||||
return jsonify(returnedChat["name"])
|
|
||||||
except:
|
|
||||||
return jsonify("Invalid Permissions")
|
|
||||||
else:
|
else:
|
||||||
try:
|
return False, "Incorrect permissions"
|
||||||
returnedChat["permissions"][userId].index("edit")
|
|
||||||
# Check for the detail type and add data to db
|
|
||||||
if (details == "model"):
|
|
||||||
model = request.json['model']
|
|
||||||
chatCollection.update_one({'_id': ObjectId(_id)}, { "$set": { "model": model } })
|
|
||||||
if (details == "name"):
|
|
||||||
name = request.json['name']
|
|
||||||
chatCollection.update_one({'_id': ObjectId(_id)}, { "$set": { "name": name } })
|
|
||||||
return jsonify("Success")
|
|
||||||
except:
|
|
||||||
return jsonify("Invalid Permissions")
|
|
||||||
else:
|
else:
|
||||||
return jsonify("User token is invalid")
|
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
|
||||||
|
details = request.json['details']
|
||||||
|
# If the user is trying to GET data
|
||||||
|
if (request.method == 'GET'):
|
||||||
|
# Get the chat from the chatId
|
||||||
|
returnedChat = chatCollection.find_one({'_id': ObjectId(_id)})
|
||||||
|
# Convert chatId into string
|
||||||
|
returnedChat['_id'] = str(returnedChat['_id'])
|
||||||
|
try:
|
||||||
|
returnedChat["permissions"][userId].index("view")
|
||||||
|
print("Chat " + _id + " has been found with token " + token)
|
||||||
|
# Check for detail type and return correct value from db
|
||||||
|
if (details == "history"):
|
||||||
|
return jsonify(returnedChat["messages"])
|
||||||
|
elif (details == "users"):
|
||||||
|
return jsonify(returnedChat["permissions"])
|
||||||
|
elif (details == "model"):
|
||||||
|
return jsonify(returnedChat["model"])
|
||||||
|
elif (details == "name"):
|
||||||
|
return jsonify(returnedChat["name"])
|
||||||
|
except:
|
||||||
|
return jsonify("Invalid Permissions")
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
returnedChat["permissions"][userId].index("edit")
|
||||||
|
# Check for the detail type and add data to db
|
||||||
|
if (details == "model"):
|
||||||
|
model = request.json['model']
|
||||||
|
chatCollection.update_one({'_id': ObjectId(_id)}, { "$set": { "model": model } })
|
||||||
|
if (details == "name"):
|
||||||
|
name = request.json['name']
|
||||||
|
chatCollection.update_one({'_id': ObjectId(_id)}, { "$set": { "name": name } })
|
||||||
|
return jsonify("Success")
|
||||||
|
except:
|
||||||
|
return jsonify("Invalid Permissions")
|
||||||
else:
|
else:
|
||||||
return jsonify("User token is invalid")
|
return jsonify("User token is invalid")
|
||||||
|
|
||||||
@@ -109,44 +120,28 @@ 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
|
name = request.json['name']
|
||||||
if (user):
|
model = request.json['model']
|
||||||
# Convert _id to a string, python doesn't like ObjectId()
|
chatCollection.insert_one(
|
||||||
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)
|
"name":name,
|
||||||
if (user['tokens'][0]['expiry'] > int(datetime.now().timestamp())):
|
"model":model,
|
||||||
# Store the userId
|
"permissions": {
|
||||||
userId = user['_id']
|
userId:[
|
||||||
print(user)
|
"owner",
|
||||||
print(user['permissions'])
|
"view",
|
||||||
if ("createChat" in user['permissions']):
|
"message",
|
||||||
print(userId)
|
"edit"
|
||||||
name = request.json['name']
|
]
|
||||||
model = request.json['model']
|
},
|
||||||
chatCollection.insert_one(
|
"messages": [
|
||||||
{
|
|
||||||
"name":name,
|
]
|
||||||
"model":model,
|
}
|
||||||
"permissions": {
|
)
|
||||||
userId:[
|
return jsonify("Success")
|
||||||
"owner",
|
|
||||||
"view",
|
|
||||||
"message",
|
|
||||||
"edit"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"messages": [
|
|
||||||
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
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,13 +162,9 @@ 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:
|
|
||||||
render_template('logout.html', appName=appName)
|
|
||||||
else:
|
else:
|
||||||
render_template('logout.html', appName=appName)
|
render_template('logout.html', appName=appName)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user