Skip to content
Snippets Groups Projects
Commit cd7927bc authored by Johan Thörnblom's avatar Johan Thörnblom
Browse files

ddd

parents e87f4603 25bf0017
No related branches found
No related tags found
No related merge requests found
"""Server""" """Server"""
from flask import Flask, jsonify, request, make_response from flask import Flask, jsonify, request, make_response
from gevent.pywsgi import WSGIServer from gevent.pywsgi import WSGIServer
...@@ -7,8 +8,6 @@ import json ...@@ -7,8 +8,6 @@ import json
from flask_sock import Sock from flask_sock import Sock
from gevent import monkey from gevent import monkey
monkey.patch_all() monkey.patch_all()
#Remember: #Remember:
#PUT for updating data, POST for adding new data #PUT for updating data, POST for adding new data
#save token on client and server (lab 3) #save token on client and server (lab 3)
...@@ -17,28 +16,20 @@ monkey.patch_all() ...@@ -17,28 +16,20 @@ monkey.patch_all()
# python3 server.py # python3 server.py
# http://127.0.0.1:5000/myServer # http://127.0.0.1:5000/myServer
# sqlite3 database.db ".read schema.sql" # sqlite3 database.db ".read schema.sql"
#Questions: #Questions:
#Why does localhost in URL not work? #Why does localhost in URL not work?
app = Flask(__name__, static_url_path = '/static')#in case flask does not recognize folder app = Flask(__name__, static_url_path = '/static')#in case flask does not recognize folder
sock = Sock(app) sock = Sock(app)
app.debug = True app.debug = True
session = {'token': ("email", "wsObj")} session = {'token': ("email", "wsObj")}
@app.route('/') @app.route('/')
def root(): def root():
return app.send_static_file('client.html') return app.send_static_file('client.html')
@app.route('/myServer') @app.route('/myServer')
def myServer(): def myServer():
return app.send_static_file('client.html') return app.send_static_file('client.html')
def token_has_error(token): def token_has_error(token):
"""All token standard error checks""" """All token standard error checks"""
if token is None: if token is None:
...@@ -51,7 +42,6 @@ def token_has_error(token): ...@@ -51,7 +42,6 @@ def token_has_error(token):
#"User not signed in or invalid access token" #"User not signed in or invalid access token"
return True, 401 return True, 401
return False, 0 return False, 0
def input_has_error(input): def input_has_error(input):
"""All standard input error checks""" """All standard input error checks"""
try: try:
...@@ -63,16 +53,25 @@ def input_has_error(input): ...@@ -63,16 +53,25 @@ def input_has_error(input):
if len(str) > 50: # "Server received too long " + str if len(str) > 50: # "Server received too long " + str
return True, 400, "" return True, 400, ""
return False, 0, str return False, 0, str
#--------------------------------------
# # Close my socket
# print(session)
# try:
# session[token][1].close()
# except:
# pass # samma sak som ingenting
# print(session)
#
#
# set user to not logged in
#session.pop(token)
#--------------------------------------
@sock.route('/myServer/api') @sock.route('/myServer/api')
def echo(socket): def echo(socket):
while True: while True:
# Making sure we have a valid socket # Making sure we have a valid socket
if not socket: if not socket:
return return
# Making sure message format is OK and store email & token in string # Making sure message format is OK and store email & token in string
data = socket.receive() data = socket.receive()
try: try:
...@@ -83,24 +82,54 @@ def echo(socket): ...@@ -83,24 +82,54 @@ def echo(socket):
myToken = json.loads(data)["token"] myToken = json.loads(data)["token"]
except: except:
return return
try:
# sign out if I am logged in somewhere else mode = json.loads(data)["mode"]
print(session) except:
for token in list(session.keys()): return
if session[token][0] == myEmail and token != myToken:
if session[token][1] != "": #When sign_in is called
session[token][1].send(json.dumps({"action" : "signOut"})) if mode == 0:
session[token][1].close() print("/n")
print("You got kicked out") print("Inside mode 0")
session.pop(token) print("/n")
print(session) # sign out if I am logged in somewhere else
print("/n")
# Put socket in global dict so server knows my connection is open print(session)
session[myToken] = (myEmail, socket) print("/n")
print(session) for token in list(session.keys()):
socket.send(json.dumps({"action" : "signIn"})) if session[token][0] == myEmail and token != myToken:
print("after first if")
if session[token][1] != "":
print("after second if")
session[token][1].send(json.dumps({"action" : "signOut"}))
session[token][1].close()
print("You got kicked out")
session.pop(token)
print("/n")
print(session)
print("/n")
print("-------------------------------")
# Put socket in global dict so server knows my connection is open
session[myToken] = (myEmail, socket)
print(session)
socket.send(json.dumps({"action" : "signIn"}))
#When sign_out is called
else:
# Close my socket
print("/n")
print("Inside mode 1")
print("/n")
print(session)
print("/n")
session[token][1].send(json.dumps({"action" : "signOut"}))
session[token][1].close()
session.pop(token)
print("/n")
print(session)
print("/n")
#set user to not logged in
@app.route("/myServer/sign_in", methods=['POST']) @app.route("/myServer/sign_in", methods=['POST'])
def sign_in(): def sign_in():
"""Sign in user""" """Sign in user"""
...@@ -110,21 +139,17 @@ def sign_in(): ...@@ -110,21 +139,17 @@ def sign_in():
if tmp[0]: if tmp[0]:
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
email = tmp[2] email = tmp[2]
# Validate Password # Validate Password
tmp = input_has_error('password') tmp = input_has_error('password')
if tmp[0]: if tmp[0]:
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
password = tmp[2] password = tmp[2]
# Do the user have an account? # Do the user have an account?
rows = database_helper.find_user(email) rows = database_helper.find_user(email)
if rows is None or rows == []: if rows is None or rows == []:
return jsonify({}), 404 #"No user found by your email" return jsonify({}), 404 #"No user found by your email"
if password != rows[1]: if password != rows[1]:
return jsonify({}), 401 #"Incorrect password") return jsonify({}), 401 #"Incorrect password")
# Generate a random token # Generate a random token
token = str(uuid.uuid4()) token = str(uuid.uuid4())
session[token] = (email, "") session[token] = (email, "")
...@@ -134,18 +159,14 @@ def sign_in(): ...@@ -134,18 +159,14 @@ def sign_in():
response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add("Access-Control-Allow-Origin", "*")
response.headers["Authorization"] = token response.headers["Authorization"] = token
return response, 204 return response, 204
@app.route("/myServer/sign_up", methods=['POST']) @app.route("/myServer/sign_up", methods=['POST'])
def sign_up(): def sign_up():
"""Sign up a user""" """Sign up a user"""
tmp = input_has_error('email') tmp = input_has_error('email')
if tmp[0]: if tmp[0]:
print(tmp[1]) # print(tmp[1])
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
email = tmp[2] email = tmp[2]
# Checking that the user does not already exist # Checking that the user does not already exist
if database_helper.find_user(email) is not None: if database_helper.find_user(email) is not None:
return jsonify({}), 409 #"Error: User already exists" return jsonify({}), 409 #"Error: User already exists"
...@@ -176,14 +197,11 @@ def sign_up(): ...@@ -176,14 +197,11 @@ def sign_up():
if tmp[0]: if tmp[0]:
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
country = tmp[2] country = tmp[2]
# Attempts to insert the user data to the database # Attempts to insert the user data to the database
if database_helper.create_user(email, password, firstname, familyname, gender, city, country): if database_helper.create_user(email, password, firstname, familyname, gender, city, country):
return jsonify({}), 204 #"Server inserted user data into database" return jsonify({}), 204 #"Server inserted user data into database"
else: else:
return jsonify({}), 500 #"General Error: Server failed to insert user data into database" return jsonify({}), 500 #"General Error: Server failed to insert user data into database"
@app.route("/myServer/sign_out", methods=['POST']) @app.route("/myServer/sign_out", methods=['POST'])
def sign_out(): def sign_out():
"""Sign out user""" """Sign out user"""
...@@ -194,121 +212,97 @@ def sign_out(): ...@@ -194,121 +212,97 @@ def sign_out():
if tmp[0]: if tmp[0]:
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
# Close my socket #--------------------------------------
print(session) # # Close my socket
try: # print(session)
session[token][1].close() # try:
except: # session[token][1].close()
pass # samma sak som ingenting # except:
print(session) # pass # samma sak som ingenting
# print(session)
# set user to not logged in
try:
session.pop(token) # #set user to not logged in
except: # session.pop(token)
pass # samma sak som ingenting #--------------------------------------
return jsonify({}), 204 # "Successfully signed out") return jsonify({}), 204 # "Successfully signed out")
@app.route("/myServer/change_password", methods=['PUT']) @app.route("/myServer/change_password", methods=['PUT'])
def change_password(): def change_password():
"""Change password for the current user""" """Change password for the current user"""
token = request.headers["Authorization"] token = request.headers["Authorization"]
# Validate Token # Validate Token
tmp = token_has_error(token) tmp = token_has_error(token)
if tmp[0]: if tmp[0]:
print("validate token") #print("validate token")
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
# Validate Old Password # Validate Old Password
tmp = input_has_error('old_password') tmp = input_has_error('old_password')
if tmp[0]: if tmp[0]:
print("validate old password") #print("validate old password")
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
old_password = tmp[2] old_password = tmp[2]
# Validate New Password # Validate New Password
tmp = input_has_error('new_password') tmp = input_has_error('new_password')
if tmp[0]: if tmp[0]:
print("validate new password") #print("validate new password")
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
new_password = tmp[2] new_password = tmp[2]
# Extracting theemail of the current user # Extracting theemail of the current user
email = session[token][0] email = session[token][0]
# Validation of the old password and attemption to change it to the new one # Validation of the old password and attemption to change it to the new one
if old_password == database_helper.find_user(email)[1]: #checks if old_password is correct if old_password == database_helper.find_user(email)[1]: #checks if old_password is correct
status = database_helper.update_user(new_password, email) status = database_helper.update_user(new_password, email)
if status: if status:
print("Password changed") # print("Password changed")
return jsonify({}), 204 # "Password has been changed!" return jsonify({}), 204 # "Password has been changed!"
else: else:
return jsonify({}), 500 # "Password has not been changed" return jsonify({}), 500 # "Password has not been changed"
else: else:
return jsonify({}), 400 # "Old password is incorrect" return jsonify({}), 400 # "Old password is incorrect"
@app.route("/myServer/getDataByToken", methods=['GET']) @app.route("/myServer/getDataByToken", methods=['GET'])
def get_user_data_by_token(): def get_user_data_by_token():
"""Verify current user through token and attemp to return the data of the user""" """Verify current user through token and attemp to return the data of the user"""
token = request.headers["Authorization"] token = request.headers["Authorization"]
# Validate token # Validate token
if token not in session: if token not in session:
return jsonify({}), 401 # "User not signed in or invalid access token" return jsonify({}), 401 # "User not signed in or invalid access token"
# Extracting the email of the current user # Extracting the email of the current user
email = session[token][0] email = session[token][0]
return get_user_data_by_email(email) return get_user_data_by_email(email)
@app.route("/myServer/getDataByEmail/<email>", methods=['GET']) @app.route("/myServer/getDataByEmail/<email>", methods=['GET'])
def get_user_data_by_email(email): def get_user_data_by_email(email):
"""Get user data by email""" """Get user data by email"""
token = request.headers["Authorization"] token = request.headers["Authorization"]
# Validate Token # Validate Token
tmp = token_has_error(token) tmp = token_has_error(token)
if tmp[0]: if tmp[0]:
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
# Validate email # Validate email
if email is None: if email is None:
return True, 400 return True, 400
if len(email) > 50: if len(email) > 50:
return True, 400 return True, 400
# Attempting to find the data of the current user in the database # Attempting to find the data of the current user in the database
data = database_helper.find_user(email) data = database_helper.find_user(email)
if data is None or data == []: if data is None or data == []:
return jsonify({}), 404 #"No user found by your destination email" return jsonify({}), 404 #"No user found by your destination email"
formated_data = {"email": data[0], "firstname": data[2], "familyname": data[3], "gender": data[4], "city": data[5], "country": data[6]} formated_data = {"email": data[0], "firstname": data[2], "familyname": data[3], "gender": data[4], "city": data[5], "country": data[6]}
return jsonify({"data" : formated_data}), 200 # "Data successfully sent to you!" return jsonify({"data" : formated_data}), 200 # "Data successfully sent to you!"
@app.route("/myServer/getUserMessageByToken", methods=['GET']) @app.route("/myServer/getUserMessageByToken", methods=['GET'])
def get_user_messages_by_token(): def get_user_messages_by_token():
"""Get user's message wall thought the token of the user""" """Get user's message wall thought the token of the user"""
token = request.headers["Authorization"] token = request.headers["Authorization"]
# Validate Token # Validate Token
tmp = token_has_error(token) tmp = token_has_error(token)
if tmp[0]: if tmp[0]:
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
# Extracting the email of the current user # Extracting the email of the current user
email = session[token][0] email = session[token][0]
return get_user_messages_by_email(email) return get_user_messages_by_email(email)
@app.route("/myServer/getMessagesByEmail/<req_email>", methods=['GET']) @app.route("/myServer/getMessagesByEmail/<req_email>", methods=['GET'])
def get_user_messages_by_email(req_email): def get_user_messages_by_email(req_email):
"""Get user's message wall thought the email of the user""" """Get user's message wall thought the email of the user"""
token = request.headers["Authorization"] token = request.headers["Authorization"]
# Validate Token # Validate Token
tmp = token_has_error(token) tmp = token_has_error(token)
if tmp[0]: if tmp[0]:
...@@ -319,36 +313,28 @@ def get_user_messages_by_email(req_email): ...@@ -319,36 +313,28 @@ def get_user_messages_by_email(req_email):
return True, 400 return True, 400
if len(req_email) > 50: if len(req_email) > 50:
return True, 400 return True, 400
# Find requested user in the data base # Find requested user in the data base
rows = database_helper.find_user(req_email) rows = database_helper.find_user(req_email)
# Error check # Error check
if rows is None or rows == []: if rows is None or rows == []:
return jsonify({}), 404 #"No user found by your destination email" return jsonify({}), 404 #"No user found by your destination email"
# Insert post-info into array # Insert post-info into array
rows = database_helper.get_post(req_email) rows = database_helper.get_post(req_email)
result = [] result = []
for row in rows: for row in rows:
result.append({"email": row[0], "person_who_posted": row[1], "message": row[2]}) result.append({"email": row[0], "person_who_posted": row[1], "message": row[2]})
# Notify user if the wall is empty or not, and if not, return the all messages # Notify user if the wall is empty or not, and if not, return the all messages
if result == []: if result == []:
return jsonify({}), 204 #"user's wall had no messages to collect" return jsonify({}), 204 #"user's wall had no messages to collect"
return jsonify({"data" : result}), 200 # User posts has been displayed" return jsonify({"data" : result}), 200 # User posts has been displayed"
@app.route("/myServer/post", methods=['POST']) @app.route("/myServer/post", methods=['POST'])
def post_message(): def post_message():
"""Post a message on sombody's wall""" """Post a message on sombody's wall"""
# Find out sender's email # Find out sender's email
token = request.headers["Authorization"] token = request.headers["Authorization"]
tmp = token_has_error(token) tmp = token_has_error(token)
if tmp[0]: if tmp[0]:
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
# Extracting the email of the current user # Extracting the email of the current user
my_email = session[token][0] my_email = session[token][0]
...@@ -357,24 +343,19 @@ def post_message(): ...@@ -357,24 +343,19 @@ def post_message():
if tmp[0]: if tmp[0]:
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
destination_email = tmp[2] destination_email = tmp[2]
# Finding out if the user exist, who we wanna write a message to # Finding out if the user exist, who we wanna write a message to
rows = database_helper.find_user(destination_email) rows = database_helper.find_user(destination_email)
if rows is None or rows == []: if rows is None or rows == []:
return jsonify({}), 404 #"No user found by your destination email" return jsonify({}), 404 #"No user found by your destination email"
# Verify message that we want to post # Verify message that we want to post
tmp = input_has_error('message') tmp = input_has_error('message')
if tmp[0]: if tmp[0]:
return jsonify({}), tmp[1] return jsonify({}), tmp[1]
message = tmp[2] message = tmp[2]
# Calling and error checking function # Calling and error checking function
if not database_helper.create_post(my_email, destination_email, message): if not database_helper.create_post(my_email, destination_email, message):
return jsonify({}), 500 #"Server failed to post message to database" return jsonify({}), 500 #"Server failed to post message to database"
return jsonify({}), 204 #"Succeeded to post message") return jsonify({}), 204 #"Succeeded to post message")
if __name__ == '__main__': if __name__ == '__main__':
# app.run(port=5000, debug=True) # app.run(port=5000, debug=True)
app.debug = True app.debug = True
......
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment