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

dooone

parents 58921c0f dd07b92b
No related branches found
No related tags found
No related merge requests found
No preview for this file type
......@@ -85,19 +85,36 @@ def echo(socket):
return
# sign out if I am logged in somewhere else
print("Before loop")
print("/n")
print(session)
print("/n")
for token in list(session.keys()):
if session[token][0] == myEmail and token != myToken:
if session[token][1] != "":
session[token][1].send(json.dumps({"action" : "signOut"}))
session[token][1].close()
if session[token][0] == myEmail and token != myToken and session[token][1] != "":
print("Inside first if")
#if session[token][1] != "":
print("Inside second if")
session[token][1].send(json.dumps({"action" : "signOut"}))
print(token[1])
session[token][1].close()
print("You got kicked out")
session.pop(token)
print("After loop")
print("/n")
print(session)
print("/n")
# Put socket in global dict so server knows my connection is open
session[myToken] = (myEmail, socket)
print("After insertion into dict")
print("/n")
print(session)
print("/n")
socket.send(json.dumps({"action" : "signIn"}))
......@@ -123,7 +140,7 @@ def sign_in():
return jsonify({}), 404 #"No user found by your email"
if password != rows[1]:
return jsonify({}), 401 #"Incorrect password")
return jsonify({}), 401 #"Incorrect password") x
# Generate a random token
token = str(uuid.uuid4())
......
......@@ -17,7 +17,6 @@ function connectWithSocket() {
displayView();
setUserDetails("home");
// Establish web socket
socket = new WebSocket('ws://' + document.domain + ':5000/myServer/api');
......@@ -37,7 +36,7 @@ function connectWithSocket() {
case "signOut":
// If old socket open, close it.
socket.close();
//socket.close();
console.log(response);
// Reset token in the localStorage
......
"""Server"""
from flask import Flask, jsonify, request, make_response
from gevent.pywsgi import WSGIServer
......@@ -9,8 +10,6 @@ import threading
from gevent import monkey
monkey.patch_all()
#Remember:
#PUT for updating data, POST for adding new data
#save token on client and server (lab 3)
......@@ -19,15 +18,11 @@ monkey.patch_all()
# python3 server.py
# http://127.0.0.1:5000/myServer
# sqlite3 database.db ".read schema.sql"
#Questions:
#Why does localhost in URL not work?
app = Flask(__name__, static_url_path = '/static')#in case flask does not recognize folder
sock = Sock(app)
app.debug = True
session = {'token': ("email", "wsObj")}
lock = threading.Lock()
......@@ -36,11 +31,9 @@ lock = threading.Lock()
@app.route('/')
def root():
return app.send_static_file('client.html')
@app.route('/myServer')
def myServer():
return app.send_static_file('client.html')
def token_has_error(token):
"""All token standard error checks"""
if token is None:
......@@ -53,7 +46,6 @@ def token_has_error(token):
#"User not signed in or invalid access token"
return True, 401
return False, 0
def input_has_error(input):
"""All standard input error checks"""
try:
......@@ -66,14 +58,12 @@ def input_has_error(input):
return True, 400, ""
return False, 0, str
@sock.route('/myServer/api')
def echo(socket):
while True:
# Making sure we have a valid socket
if not socket:
return
# Making sure message format is OK and store email & token in string
data = socket.receive()
try:
......@@ -108,7 +98,6 @@ def echo(socket):
socket.close()
lock.release()
@app.route("/myServer/sign_in", methods=['POST'])
def sign_in():
"""Sign in user"""
......@@ -118,21 +107,17 @@ def sign_in():
if tmp[0]:
return jsonify({}), tmp[1]
email = tmp[2]
# Validate Password
tmp = input_has_error('password')
if tmp[0]:
return jsonify({}), tmp[1]
password = tmp[2]
# Do the user have an account?
rows = database_helper.find_user(email)
if rows is None or rows == []:
return jsonify({}), 404 #"No user found by your email"
if password != rows[1]:
return jsonify({}), 401 #"Incorrect password")
# Generate a random token
token = str(uuid.uuid4())
lock.acquire()
......@@ -145,17 +130,14 @@ def sign_in():
response.headers["Authorization"] = token
return response, 204
@app.route("/myServer/sign_up", methods=['POST'])
def sign_up():
"""Sign up a user"""
tmp = input_has_error('email')
if tmp[0]:
print(tmp[1])
# print(tmp[1])
return jsonify({}), tmp[1]
email = tmp[2]
# Checking that the user does not already exist
if database_helper.find_user(email) is not None:
return jsonify({}), 409 #"Error: User already exists"
......@@ -186,14 +168,12 @@ def sign_up():
if tmp[0]:
return jsonify({}), tmp[1]
country = tmp[2]
# Attempts to insert the user data to the database
if database_helper.create_user(email, password, firstname, familyname, gender, city, country):
return jsonify({}), 204 #"Server inserted user data into database"
else:
return jsonify({}), 500 #"General Error: Server failed to insert user data into database"
@app.route("/myServer/sign_out", methods=['POST'])
def sign_out():
"""Sign out user"""
......@@ -218,96 +198,79 @@ def sign_out():
return jsonify({}), 204 # "Successfully signed out")
@app.route("/myServer/change_password", methods=['PUT'])
def change_password():
"""Change password for the current user"""
token = request.headers["Authorization"]
# Validate Token
tmp = token_has_error(token)
if tmp[0]:
print("validate token")
#print("validate token")
return jsonify({}), tmp[1]
# Validate Old Password
tmp = input_has_error('old_password')
if tmp[0]:
print("validate old password")
#print("validate old password")
return jsonify({}), tmp[1]
old_password = tmp[2]
# Validate New Password
tmp = input_has_error('new_password')
if tmp[0]:
print("validate new password")
#print("validate new password")
return jsonify({}), tmp[1]
new_password = tmp[2]
# Extracting theemail of the current user
email = session[token][0]
# 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
status = database_helper.update_user(new_password, email)
if status:
print("Password changed")
# print("Password changed")
return jsonify({}), 204 # "Password has been changed!"
else:
return jsonify({}), 500 # "Password has not been changed"
else:
return jsonify({}), 400 # "Old password is incorrect"
@app.route("/myServer/getDataByToken", methods=['GET'])
def get_user_data_by_token():
"""Verify current user through token and attemp to return the data of the user"""
token = request.headers["Authorization"]
# Validate token
if token not in session:
return jsonify({}), 401 # "User not signed in or invalid access token"
# Extracting the email of the current user
email = session[token][0]
return get_user_data_by_email(email)
@app.route("/myServer/getDataByEmail/<email>", methods=['GET'])
def get_user_data_by_email(email):
"""Get user data by email"""
token = request.headers["Authorization"]
# Validate Token
tmp = token_has_error(token)
if tmp[0]:
return jsonify({}), tmp[1]
# Validate email
if email is None:
return True, 400
if len(email) > 50:
return True, 400
# Attempting to find the data of the current user in the database
data = database_helper.find_user(email)
if data is None or data == []:
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]}
return jsonify({"data" : formated_data}), 200 # "Data successfully sent to you!"
@app.route("/myServer/getUserMessageByToken", methods=['GET'])
def get_user_messages_by_token():
"""Get user's message wall thought the token of the user"""
token = request.headers["Authorization"]
# Validate Token
tmp = token_has_error(token)
if tmp[0]:
return jsonify({}), tmp[1]
# Extracting the email of the current user
email = session[token][0]
return get_user_messages_by_email(email)
......@@ -316,7 +279,6 @@ def get_user_messages_by_token():
def get_user_messages_by_email(req_email):
"""Get user's message wall thought the email of the user"""
token = request.headers["Authorization"]
# Validate Token
tmp = token_has_error(token)
if tmp[0]:
......@@ -327,36 +289,29 @@ def get_user_messages_by_email(req_email):
return True, 400
if len(req_email) > 50:
return True, 400
# Find requested user in the data base
rows = database_helper.find_user(req_email)
# Error check
if rows is None or rows == []:
return jsonify({}), 404 #"No user found by your destination email"
# Insert post-info into array
rows = database_helper.get_post(req_email)
result = []
for row in rows:
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
if result == []:
return jsonify({}), 204 #"user's wall had no messages to collect"
return jsonify({"data" : result}), 200 # User posts has been displayed"
@app.route("/myServer/post", methods=['POST'])
def post_message():
"""Post a message on sombody's wall"""
# Find out sender's email
token = request.headers["Authorization"]
tmp = token_has_error(token)
if tmp[0]:
return jsonify({}), tmp[1]
# Extracting the email of the current user
my_email = session[token][0]
......@@ -365,24 +320,20 @@ def post_message():
if tmp[0]:
return jsonify({}), tmp[1]
destination_email = tmp[2]
# Finding out if the user exist, who we wanna write a message to
rows = database_helper.find_user(destination_email)
if rows is None or rows == []:
return jsonify({}), 404 #"No user found by your destination email"
# Verify message that we want to post
tmp = input_has_error('message')
if tmp[0]:
return jsonify({}), tmp[1]
message = tmp[2]
# Calling and error checking function
if not database_helper.create_post(my_email, destination_email, message):
return jsonify({}), 500 #"Server failed to post message to database"
return jsonify({}), 204 #"Succeeded to post message")
if __name__ == '__main__':
# app.run(port=5000, 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