Exemplo n.º 1
0
def socket():
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        while True:
            try:
                message = ws.receive()
                if message is not None:
                    try:
                        message = json.loads(message)
                        if message["type"] == "login":
                            token = message["data"]
                            user = database_helper.get_email(token)
                            # We want to log out any previous sessions
                            if user is not None:
                                if user in clients:
                                    print("Telling previous user to leave")
                                    msg = {"type": "signout"}
                                    clients[user].send(json.dumps(msg))

                                clients[user] = ws
                            # User is None, sign them out anyways
                            else:
                                msg = {"type": "signout"}
                                ws.send(json.dumps(msg))

                            print(">> Active clients:")
                            for client in clients:
                                print(client)

                        if message["type"] == "get-stats":
                            token = message["data"]
                            email = database_helper.get_email(token)
                            send_stats(False, email)

                    except TypeError as te:
                        print te
                        return ""
                else:
                    # Message is None
                    break

            except WebSocketError, e:
                print "Connection closed..."
                print e
                for user, s in clients.items():
                    if ws == s:
                        # Remove socket
                        del clients[user]

        print("Closing socket...")
        for user, s in clients.items():
            if ws == s:
                # Remove socket
                del clients[user]
        return ""
Exemplo n.º 2
0
def is_signed_in():
    print "checking if signed in..."
    token = request.args.get('token')
    email = database_helper.get_email(token)
    if email is None:
        return jsonify(success=False, message="Not logged in!")
    return jsonify(success=True, message="User logged in")
Exemplo n.º 3
0
def open_socket():
    token = get_param_or_default('token')
    email = db.get_email(token)[0]
    if (db.is_connected_mail(email)):
        db.update_token(email, token)
    success("Socket opened")
    return json.dumps(output)
Exemplo n.º 4
0
def get_user_data_by_token():
    token = request.args.get("token")
    time_stamp = request.args.get("time")
    email = database_helper.get_email(token)
    if check_hash("", email, request.args.get("hash"), time_stamp):
        return json.dumps({
            'success':
            False,
            'message':
            'You are trying to hack a user. You should be ashamed of yourself!'
        })
    if email is None:
        return json.dumps({
            'success': False,
            'message': 'User is not logged in'
        })
    else:
        data = database_helper.get_user(email)
        retData = {
            'firstname': data[0],
            'familyname': data[1],
            'email': data[2],
            'gender': data[3],
            'city': data[4],
            'country': data[5]
        }
        return json.dumps({
            'success': True,
            'message': 'Data retrieval successful',
            "data": retData
        })
Exemplo n.º 5
0
def changePass():
    token = request.form['token']
    token = verify_token(token)
    old_Password = request.form['old_password']
    new_Password = request.form['new_password']
    email = database_helper.get_email(token)
    email = email[0]

    print email
    curr_pw = database_helper.get_password(email)
    curr_pw = curr_pw[0]
    print curr_pw

    if len(new_Password) < 7:
        return jsonify(success=False, message="Too short password")

    if not email:
        return jsonify(success=False, message="Invalid token")

    #pw_hash = database_helper.get_password(email)
    if (bcrypt.check_password_hash(curr_pw, old_Password)):
    #if curr_pw == old_Password:
        new_pw_hash = bcrypt.generate_password_hash(new_Password)
        database_helper.set_password(email, new_pw_hash)
        return jsonify(success=True, message="Password changed successfully")
    else:
        return jsonify(success=False, message="Wrong password")
Exemplo n.º 6
0
def delete_media():
    print "Deleting media"
    req = request.get_json(force=True)
    token = req['token']
    pic_id = req['id']
    email = database_helper.get_email(token)
    if email is None:
        return jsonify(success=False, message='User not signed in')

    # Get path of file with specific media id
    filename = database_helper.retrieve_media(email, pic_id)
    if filename is None:
        return jsonify(success=False, message='Media file does not exist')
    if not database_helper.delete_media(pic_id, email):
        return jsonify(success=False, message='Failed to delete media file')

    os.remove(filename['path'])

    # Successfully deleted media, now download what remains
    media_data = database_helper.retrieve_media(email)
    if media_data is None:
        return jsonify(success=False, message='Failed to download media')

    data = create_media(media_data)
    return jsonify(success=True, message='Media file deleted!', data=data)
Exemplo n.º 7
0
def change_password():
    req = request.get_json(force=True)
    token = req['token']
    old_password = req['old_password']
    new_password = req['new_password']

    # First see if passwords differ
    if old_password == new_password:
        return jsonify(success=False, message="Can't use the same password!")
    # Is the new password long enough?
    if not validate(new_password):
        return jsonify(success=False, message="Password has to be at least 5 characters!")

    # Use token to get email (also makes sure token is valid and that they are logged in)
    email = database_helper.get_email(token)
    if email is None:
        return jsonify(success=False, message="User is not logged in!")
    # Make sure old password is correct
    if not database_helper.find_user(email, old_password):
        return jsonify(success=False, message="Incorrect password!")
    # Try changing the password
    if not database_helper.change_password(new_password, email):
        return jsonify(success=False, message="Failed to change password!")

    return jsonify(success=True, message="Password successfully changed!")
Exemplo n.º 8
0
def socket():
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        while True:
            try:
                message = ws.receive()
                try:
                    message = json.loads(message)

                    if message["type"] == "login":
                        token = message["data"]
                        user = database_helper.get_email(token)
                        # if user already has a connection, send 'signout'
                        if user in clients:
                            data = {"type": "signout"}
                            clients[user].send(json.dumps(data))
                    # update clients with new user
                        clients[user] = ws

                        print "new client logged in..."
                        for client in clients:
                            print(client)
                    if message["type"] == "stats":

                        # Send data to client
                        print "Client requested data"

                except TypeError:
                    print("didn't get a JSON")
                    return ""

            except WebSocketError:
                print("failed I guess")
                break
    return ""
Exemplo n.º 9
0
def change_password():
    
    token = get_param_or_default("token")
    
    userMail = db.get_email(token)
    if userMail != None:
        userMail = userMail[0]
        oldPassword = get_param_or_default("oldPassword")
        newPassword = get_param_or_default("newPassword")
        user = db.find_user(userMail)
        if user != None:
            user = json.loads(user)
            if user["password"] == oldPassword:
                if len(newPassword) > 5:
                    db.change_password(userMail, newPassword)
                    success(SUC_PASSWORD_CHANGED)
                else:
                    err(ERR_PASSWORD_TOO_SHORT)
            else:
                err(ERR_INVALID_PASSWORD)
        else:
            err(ERR_USER_NOT_FOUND)
    else:
        err(ERR_USER_NOT_CONNECTED)
    return json.dumps(output)
Exemplo n.º 10
0
def close_socket():
    email = db.get_email(get_param_or_default('token'))
    if email != None:
        email = email[0]
        socket_dict[email].close()
        socket_dict.pop(email)
        success("Socket closed")
    return json.dumps(output)
Exemplo n.º 11
0
def checkLogin(token):
    email = database_helper.get_email(token)
    email = email[0]
    result = database_helper.get_loggedInUsers(email)
    if not result:
        return False
    else:
        return True
Exemplo n.º 12
0
def autologout():
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        while True:
            message = ws.receive()
            connection.append([ws, database_helper.get_email(message)])
            print(connection)
            ws.send(message)
    return
Exemplo n.º 13
0
def postMessage():
    token = request.form['token']
    message = request.form['message']
    recepient = request.form['email']
    sender = database_helper.get_email(token)
    sender = sender[0]

    if checkLogin(token):
        database_helper.add_message(sender, recepient, message)
        return jsonify(success=True, message="Message sent")
Exemplo n.º 14
0
def getUserDataByToken():
    token = request.form['token']
    email = database_helper.get_email(token)
    email = email[0]
    if database_helper.get_loggedInUsers(email):
        user = database_helper.get_user(email)
    if user is None:
        return jsonify(success=False, message="User not signed in!")
    else:
        return jsonify(success=True, message="User data retrieved.", data=user)
Exemplo n.º 15
0
def remove_user():
    token = get_param_or_default("token")
    if db.is_connected(token):
        email = db.get_email(token)[0]
        db.logout_user(token)
        db.remove_user(email)
        success(SUC_USER_DELETED)
    else:
        err(ERR_USER_NOT_CONNECTED)
    return json.dumps(output)
Exemplo n.º 16
0
def get_user_data_by_token():
    token = get_param_or_default("token")
    if db.is_connected(token):
        user_data = db.find_user(db.get_email(token)[0])
        user_data = json.loads(user_data)
        user_data.pop("password",None)
        success(SUC_GET_USER_DATA,user_data)
    else:
        err(ERR_USER_NOT_CONNECTED)
    return json.dumps(output)
Exemplo n.º 17
0
def getUserDataByEmail():
    token = request.form['token']
    email = request.form['email']
    checkuser = database_helper.get_email(token)
    checklogin = database_helper.get_loggedInUsers(checkuser[0])
    if checklogin:
        user = database_helper.get_user(email)
        if not user:
            return jsonify(success=False, message="User not signed in!")
        else:
            return jsonify(success=True, message="User data retrieved.", data=user)
Exemplo n.º 18
0
def change_profile_pic():
    req = request.get_json(force=True)
    token = req['token']
    pic_id = req['id']

    email = database_helper.get_email(token)
    if email is None:
        return jsonify(success=False, message='User not signed in')
    if not database_helper.change_profile_pic(pic_id, email):
        return jsonify(success=False, message='Failed to change picture')

    return jsonify(success=True, message='Profile picture changed!')
Exemplo n.º 19
0
def getUserMessageByToken():
    token = request.form['token']
    email = database_helper.get_email(token)
    email = email[0]
    if not email:
        return jsonify(success=False, message="Error!")
    else:
        messages = database_helper.get_messages(email)
        if not messages:
            return jsonify(success=True, message="No messages for user")
        else:
            return jsonify(success=True, message="User messages retrieved.", data=messages)
Exemplo n.º 20
0
def get_user_messages_by_email():
    # Gets the parsed contents of query string
    token = request.args.get('token')
    email = request.args.get('email')

    if database_helper.get_email(token) is None:
        return jsonify(success=False, message="You are not logged in!")
    user_data = database_helper.get_user_messages_by_email(email)

    if user_data is None:
        return jsonify(success=False, message="Failed to retrieve messages!")
    return jsonify(success=True, message="Messages retrieved!", data=user_data)
Exemplo n.º 21
0
def download_media_token():
    req = request.get_json(force=True)
    token = req['token']
    email = database_helper.get_email(token)
    if email is None:
        return jsonify(success=False, message='User not signed in')
    media_data = database_helper.retrieve_media(email)
    if media_data is None:
        return jsonify(success=False, message='Failed to download media')

    data = create_media(media_data)

    return jsonify(success=True, message='User media retrieved', data=data)
Exemplo n.º 22
0
def post_message():
    message = request.form['message']
    token = request.form['token']
    email = request.form['email']
    sender = database_helper.get_email(token)[0]
    if database_helper.get_logged_in(token):
        if database_helper.in_users(email):
            database_helper.post_message(message, token, sender, email)
            return json.dumps({"success": True, "message": "Message posted."})
        else:
            return json.dumps({"success": False, "message": "No such user."})
    else:
        return json.dumps({"success": False, "message": "You are not signed in."})
Exemplo n.º 23
0
def getUserDataByToken():
    token = request.form['token']
    token = verify_token(token)
    print "token i getuserfan: ", token
    email = database_helper.get_email(token)
    email = email[0]
    print "EMAIL 0: ", email

    if database_helper.get_loggedInUsers(email):
        user = database_helper.get_user(email)
    if user is None:
        return jsonify(success=False, message="User not signed in!")
    else:
        return jsonify(success=True, message="User data retrieved.", data=user)
Exemplo n.º 24
0
def postMessage():
    token = request.form['token']
    token = verify_token(token)
    check = request.form['check']
    check = json.loads(check)
    message = request.form['message']
    recepient = request.form['email']
    sender = database_helper.get_email(token)
    sender = sender[0]

    if checksum(message, token, check):
        if checkLogin(token):
            database_helper.add_message(sender, recepient, message)
            return jsonify(success=True, message="Message sent")
    return jsonify(success=False, message="Message ERROR!")
Exemplo n.º 25
0
def connect():
    #send message to client with the token
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        while True:
            user_token = ws.receive()
            if user_token != None:
                if (db.is_connected(user_token)):
                    email = db.get_email(user_token)[0]
                    if email in socket_dict:
                        db.update_token(email, user_token)
                        socket_dict[email].close()
                    socket_dict[email] = ws
    success("Socket closed")
    return json.dumps(output)
Exemplo n.º 26
0
def change_password():
    token = request.form['token']
    pwd = request.form['pwd']
    chgpwd = request.form['chgPwd']
    if not database_helper.get_logged_in(token):
        return json.dumps({'success': False, 'message': "You are not logged in."})
    else:
        if len(chgpwd) < 6:
            return json.dumps({"success": False, "message": "Error: password must be at least 6 characters long"})
        email = database_helper.get_email(token)
        validlog = database_helper.check_pwd(email, pwd)
        if not validlog:
            return json.dumps({'success': False, 'message': "Wrong password."})
        database_helper.modify_pwd(email[0], pwd, chgpwd)
        return json.dumps({'success': True, 'message': "Password changed."})
Exemplo n.º 27
0
def get_user_messages_by_token():
    token = request.args.get("token")
    time_stamp = request.args.get("time")
    if check_hash("", database_helper.get_email(token),
                  request.args.get("hash"), time_stamp):
        return json.dumps({
            'success':
            False,
            'message':
            'You are trying to hack a user. You should be ashamed of yourself!'
        })
    email = database_helper.get_email(token)
    if email is None:
        return json.dumps({
            'success': False,
            'message': 'User is not logged in'
        })
    else:
        data = database_helper.get_messages(email)
        return json.dumps({
            'success': True,
            'message': 'Data retrieval successful',
            "data": data
        })
Exemplo n.º 28
0
def getUserMessageByToken():
    token = request.form['token']
    print "TOKEN I getUserMessagebyToken: ", token
    token = verify_token(token)
    print "token efter verify: ", token
    email = database_helper.get_email(token)
    email = email[0]
    print "EMAIL I GETUSERMESSSAGEBYTOKEN: ", email
    if not email:
        return jsonify(success=False, message="Error!")
    else:
        messages = database_helper.get_messages(email)
        if not messages:
            return jsonify(success=True, message="No messages for user")
        else:
            return jsonify(success=True, message="User messages retrieved.", data=messages)
Exemplo n.º 29
0
def post_message():
    req = request.get_json(force=True)
    token = req['token']
    # Make sure token is valid
    from_user = database_helper.get_email(token)
    if from_user is None:
        return jsonify(success=False, message="Log in to post a message!")

    if not database_helper.post_message(req['message'], from_user, req['email']):
        return jsonify(success=False, message="Failed to post message!")

    if from_user == req['email']:
        send_stats(False, from_user)
    else:
        send_stats(False, from_user, req['email'])

    return jsonify(success=True, message="Message posted!")
Exemplo n.º 30
0
def signout():
    token = request.form['token']
    # Get the email associated with the token, and delete
    user = database_helper.get_email(token)

    if user is not None:
        if clients.get(user) is not None:
            del clients[user]
            print "removed client..."
            for client in clients:
                print(client)

    if database_helper.signout_user(token):

        return jsonify(success=True, message="Logout successful!")
    else:
        return jsonify(success=False, message="Failed to log out user!")
Exemplo n.º 31
0
def post_message():
    token = get_param_or_default("token")
    receiver = get_param_or_default("email")
    message = get_param_or_default("message")
    if db.is_connected(token):
        sender = db.get_email(token)[0]
        if db.find_user(receiver) != None:
            if message != "":
                db.post_message(sender, receiver, message)
                success(SUC_MESSAGE_POSTED)
            else:
                err(ERR_EMPTY_MESSAGE)
        else:
            err(ERR_USER_NOT_FOUND)
    else:
        err(ERR_USER_NOT_CONNECTED)
    return json.dumps(output)
Exemplo n.º 32
0
def sign_out():
    if request.method == 'POST':
        token = request.form['token']
        i = 0
        for user in connection:
            if database_helper.get_email(token) == user[1]:
                del connection[i]
                print(connection)
            i = i + 1
        if database_helper.remove_token(token):
            return json.dumps({
                'success': True,
                'message': 'signed out successfully!'
            })
        return json.dumps({
            'success': False,
            'message': '''token doesn't exist'''
        })
Exemplo n.º 33
0
def post_message():

    token = request.form['token']
    # Make sure token is valid
    from_user = database_helper.get_email(token)
    if from_user is None:
        return jsonify(success=False, message="Log in to post a message!")

    message_info = {
        'message': request.form['message'],
        'from_user': from_user,
        'to_user': request.form['email']
    }

    if not database_helper.post_message(message_info):
        return jsonify(success=False, message="Failed to post message!")

    return jsonify(success=True, message="Message posted!")
Exemplo n.º 34
0
def get_user_data_by_email():
    # Gets the parsed contents of query string
    token = request.args.get('token')
    email = request.args.get('email')

    if database_helper.get_email(token) is None:
        return jsonify(success=False, message="You are not logged in!")
    user_data = database_helper.get_user_data_by_email(email)
    if user_data is None:
        return jsonify(success=False, message="No such user!")

    media = []
    path = user_data['profile_pic']
    media_extension = path.rsplit('.', 1)[1]
    with open(path) as m:
        media.append([base64.b64encode(m.read()), media_extension])

    user_data['profile_pic'] = media
    return jsonify(success=True, message="User data retrieved!", data=user_data)
Exemplo n.º 35
0
def get_user_data_by_email():
    # Gets the parsed contents of query string
    token = request.args.get('token')
    email = request.args.get('email')

    if database_helper.get_email(token) is None:
        return jsonify(success=False, message="You are not logged in!")
    user_data = database_helper.get_user_data_by_email(email)
    if user_data is None:
        return jsonify(success=False, message="Failed to retrieve user data!")
    data = {
        'email': user_data[0],
        'firstname': user_data[1],
        'familyname': user_data[2],
        'gender': user_data[3],
        'city': user_data[4],
        'country': user_data[5]
    }
    return jsonify(success=True, message="User data retrieved!", data=data)
Exemplo n.º 36
0
def change_password():
    if request.method == 'POST':
        token = request.form['token']
        old_password = request.form['old_password']
        new_password = request.form['new_password']
        email = database_helper.get_email(token)
        if email == False:
            return json.dumps({'success': False, 'message': "Invalid token"})
        if len(new_password) < 7:
            return json.dumps({
                'success': False,
                'message': '''Password is too short'''
            })
        db_current_hashed_password = database_helper.get_password(email)
        hashed_old_password = hashlib.sha256(old_password).hexdigest()
        if hashed_old_password == db_current_hashed_password:
            hashed_new_password = hashlib.sha256(new_password).hexdigest()
            database_helper.change_password(email, hashed_new_password)
            return json.dumps({'success': True, 'message': "Password changed"})
        return json.dumps({'success': False, 'message': "Wrong password"})
Exemplo n.º 37
0
def signout():
    req = request.get_json(force=True)
    token = req['token']
    # Get the email associated with the token, and delete
    user = database_helper.get_email(token)
    print ("signing out user..")

    if user is not None:
        if users.get(user) is not None:
            del users[user]
            print("3: Current users:")
            for user in users:
                print(user)

    if database_helper.sign_out_user(token):
        # Send stats to all users
        send_stats(True)
        return jsonify(success=True, message="Logout successful!")
    else:
        return jsonify(success=False, message="Failed to log out user!")
Exemplo n.º 38
0
def signOut():
    token = request.form['token']
    print "TOKEN I SIGNOUT: ", token
    token = verify_token(token)
    print "TOKEN EFTER SIGNOUT: ", token

    email = database_helper.get_email(token)[0]

    #global session

    if token:
        response = database_helper.signOut(token)
        del session[email]
        if response:
            return jsonify(success=True, message="User signed out successfully")
        else:
            return jsonify(success=False, message="Already logged out")
    else:
        print "fel i signout", token
        return jsonify(success=False, message="No token!")
Exemplo n.º 39
0
def post_message():
    if request.method == 'POST':
        token = request.form['token']
        message = request.form['message']
        email = request.form['email']
        sender = database_helper.get_email(token)
        if sender == False:
            return json.dumps({
                'success': False,
                'message': '''Token doesn't exists'''
            })
        if database_helper.user_exists(email) == False:
            return json.dumps({
                'success': False,
                'message': '''Receiver does not exists'''
            })
        result = database_helper.post_message(sender, message, email)
        if result:
            return json.dumps({
                'success': True,
                'message': '''Message posted successfully'''
            })
        return json.dumps({'success': False, 'message': '''Invalid message'''})
Exemplo n.º 40
0
def changePass():
    token = request.form['token']
    old_Password = request.form['old_password']
    new_Password = request.form['new_password']
    email = database_helper.get_email(token)
    email = email[0]

    print email
    curr_pw = database_helper.get_password(email)
    curr_pw = curr_pw[0]
    print curr_pw

    if len(new_Password) < 7:
        return jsonify(success=False, message="Too short password")

    if not email:
        return jsonify(success=False, message="Invalid token")

    if curr_pw == old_Password:
        database_helper.set_password(email, new_Password)
        return jsonify(sucess=True, message="Password changed successfully")
    else:
        return jsonify(sucess=False, message="Wrong password")
Exemplo n.º 41
0
def upload_media():
    print("Uploading media file...")
    token = request.form['token']
    mfile = request.files['file']

    email = database_helper.get_email(token)
    if email is None:
        return jsonify(success=False, message='User not signed in')

    if mfile and allowed_format(mfile.filename):
        if not os.path.exists(app.config['UPLOAD_FOLDER'] + "/" + email):
            os.makedirs(app.config['UPLOAD_FOLDER'] + "/" + email)
        filename = secure_filename(mfile.filename)
        path = os.path.join(app.config['UPLOAD_FOLDER'] + '/' + email, filename)

        errcode = database_helper.store_media(email, path)
        if not errcode:
            return jsonify(success=False, message='Failed to upload file')
        if errcode is 'duplicate':
            return jsonify(success=False, message='Filename already exists: ' + filename)
        mfile.save(path)
        return jsonify(success=True, message='Successfully uploaded file')

    return jsonify(success=False, message='Unsupported file format')
Exemplo n.º 42
0
def socket():
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        while True:
            try:
                message = ws.receive()
                if message is not None:
                    try:
                        message = json.loads(message)
                        if message["type"] == "login":
                            token = message["data"]
                            user = database_helper.get_email(token)
                            # We want to log out any previous sessions
                            if user is not None:
                                if user in users:
                                    print("Telling previous user to leave")
                                    msg = {"type": "signout"}
                                    users[user].send(json.dumps(msg))

                                users[user] = ws
                            # User is None, sign them out anyways
                            else:
                                msg = {"type": "signout"}
                                ws.send(json.dumps(msg))

                            print(">> Active users:")
                            for user in users:
                                print(user)

                        if message["type"] == "get-stats":
                            token = message['token']
                            user = message.get('email')
                            visitor = database_helper.get_email(token)

                            print user
                            if visitor is not None:
                                if user is None:
                                    # send to us
                                    send_stats(False, visitor)
                                else:
                                    # send to both visitor and user
                                    send_stats(False, visitor, user)
                            else:
                                print "user logged out"

                    except TypeError as te:
                        print te
                        return ""
                else:
                    # Message is None
                    break

            except WebSocketError, e:
                print "Connection closed..."
                print e
                break

        print("Closing socket...")
        for user, s in users.items():
            if ws == s:
                # Remove socket
                del users[user]
        return ""