Esempio n. 1
0
def get_user_data_by_email():
    token = get_param_or_default("token")
    email = get_param_or_default("email")
    if db.is_connected(token):
        if db.find_user(email) != None:
            user_data = db.find_user(email)
            user_data = json.loads(user_data)
            user_data.pop("password",None)
            success(SUC_GET_USER_DATA,user_data)
        else:
            err(ERR_USER_NOT_FOUND)
    else:
        err(ERR_USER_NOT_CONNECTED)
    return json.dumps(output)
def changePW():
    data = request.get_json()  #have to send in token as json string for now
    oldPW = data['password']
    newPW = data['newPW']

    userToken = request.headers.get(
        'token')  # Got THROUGH request.header() instead

    if (oldPW == newPW):
        return jsonify(success=False, message="dont use same password")
    if not validatePW(newPW):
        return jsonify(success=False, message="use a longer password")

    email = database_helper.get_email_by_token(userToken)
    if email is None:
        return jsonify(success=False, message="Cant find logged in user")

    if database_helper.find_user(email, oldPW):
        if database_helper.change_user_PW(email, newPW):
            return jsonify(success=True, message="successfully changed pw")
        else:
            return jsonify(success=False, message="Couldnt change pw")
    else:
        return jsonify(success=False,
                       message="Password is wrong for that email")
Esempio n. 3
0
def message_by_email(token, email):
    if database_helper.find_inlogged(token) is not None:
        if database_helper.find_user(email) is not None:
            messages = database_helper.get_messages(email)
            if messages is not None:
                sum = ""
                for message in messages:
                    #do we have to add the senders email?
                    sum += message[0] + "\n"
                return json.dumps({
                    "success": True,
                    "message": "User messages retrieved",
                    "data": sum
                })
            return json.dumps({
                "success": True,
                "message": "No messages on this users profile",
                "data": ""
            })
        else:
            return json.dumps({"success": False, "message": "No such user"})
    else:
        return json.dumps({
            "success": False,
            "message": "You are not signed in"
        })
Esempio n. 4
0
def get_user_data_by_email(token = None, email=None):
	if token is None or email is None:
		return json.dumps({"success": False, "message":"Key error."}),400

	# Check if the token exists (current user)
	if not token:
		return json.dumps({"success": False, "message":"You are not signed in."}),403

	# Check if the current user exists
	currentUser = database_helper.get_emailByToken(token)
	if not currentUser:
		return json.dumps({"success": False, "message":"No such user."}),404
	
	# Return the user profile
	data = database_helper.find_user(email)
	if data:
		# Update the no. of views
		email = str(email)
		if email in view_table:
			view_table[email] += 1
		else:
			view_table[email] = 1

		send_num_view(email)

		return json.dumps({"success": True, "message": "User data retrieved.", "data": [dict(x) for x in data]}),200
	else:
		return json.dumps({"success": False, "message":"No such user."}),404
Esempio n. 5
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!")
Esempio n. 6
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)
Esempio n. 7
0
def get_user_data_by_token():
    body = json.loads(request.data.decode("utf-8"))
    token = body['token']
    user = database_helper.email_from_token(token)
    result = database_helper.find_user(user['email'])
    if result != None:
        return _return_json_message(True, "Successfully found user", result)
    else:
        return _return_json_message(False, "No such user")
Esempio n. 8
0
def data_by_email(token, email):
    if database_helper.find_inlogged(token) is not None:
        if database_helper.find_user(email) is not None:
            user = database_helper.find_user(email)

            del user['password']
            return json.dumps({
                "success": True,
                "message": "User data retrieved.",
                "data": user
            })
        else:
            return json.dumps({"success": False, "message": "No such user."})
    else:
        return json.dumps({
            "success": False,
            "message": "You are not signed in."
        })
Esempio n. 9
0
def find_user(email=None):
    if email is not None:
        result = database_helper.find_user(email)
    else:
        result = False
    if not result:
        return False
    else:
        return jsonify(result)
Esempio n. 10
0
def get_user_data_by_email():
    token = request.args.get('token')   # Get the token from the URL
    email = request.args.get('email')   # Get the token from the URL
    result = database_helper.find_sign_in_user(token)   # Make sure the current user has logged in
    if result:
        result = database_helper.find_user(email)
        return jsonify(result=result)
    else:
        return jsonify({"status": 400})
Esempio n. 11
0
def sign_in():
    data = request.get_json()
    email = data["email"]
    password = data['password']
    found_user = database_helper.find_user(email)
    user = database_helper.match_email_to_password(data['email'], data['password'])
    if (user["success"]):
        return jsonify({"success":True, "message":"User signed in successfully", "token":user["token"]})
    else:
        return jsonify({"success":False, "Message":user})
Esempio n. 12
0
def post_message():
    data = request.get_json()
    token = get_token()
    if database_helper.find_user(data["email"]) != data["email"]:
        return jsonify({"success": False, "msg": "could not find user"})
    if not database_helper.validate_user(data["email"], token):
        return jsonify({"success": False, "msg": "Unauthorized"})
    if not database_helper.create_post(data, token):
        return jsonify({"success": False, "msg": "could not send msg"})
    return jsonify({"success": True, "msg": "message sent"})
Esempio n. 13
0
def get_user_data_by_email():
    body = json.loads(request.data.decode("utf-8"))
    token = body['token']
    if database_helper.email_from_token(token) == None:
        return _return_json_message(False, "User not signed in")
    email = body['email']
    result = database_helper.find_user(email)
    if result != None:
        return _return_json_message(True, "Successfully found user", result)
    else:
        return _return_json_message(False, "No such user")
Esempio n. 14
0
def reset_password():
    data = request.get_json()
    resetEmail = data['email']
    oldPwd = data['oldPwd']
    url = '/reset_password'
    key = make_key()
    token = database_helper.get_token_from_email(resetEmail)

    hashed_old_password = bcrypt.generate_password_hash(oldPwd).decode('utf-8')
    hashed_password = database_helper.get_hashed_password(resetEmail)
    print('hashed_password for this email is: ', hashed_password)
    correct_password = bcrypt.check_password_hash(hashed_password, oldPwd)
    hashed_new_password = bcrypt.generate_password_hash(
        str(key)).decode('utf-8')
    print('correct_password: '******'utf-8')).hexdigest()
    print('RESETPASSWORD: server_hash is:', server_hash,
          ' and hashed_token is: ', hashed_token)
    email = database_helper.find_user(resetEmail)
    if (email) and correct_password and server_hash == hashed_token:
        try:
            #print('success! hashed_new_password: '******'reset user password from: ',str(hashed_password), ' to: ',  str(hashed_new_password) )
            print('result is: ', result)
            if (result):
                print('trying to set up SMTP connection...')
                yag = yagmail.SMTP(user=resetEmail)
                print('setting contents...')
                contents = [
                    "You've requested to reset your Twidder password.",
                    'Your new password is: ',
                    str(key)
                ]
                print(contents)
                print('creating recipients')
                recipients = {resetEmail: 'Twidder user'}
                print(recipients)
                print('trying to send email...')
                yag.send(to=recipients,
                         subject='Your temporary Twidder password',
                         contents=contents)
                print("Email sent successfully")
                res = jsonify({'message': 'Email sent successfully'})
                return res
        except:
            print("Error, email was not sent")

    return ''
Esempio n. 15
0
def get_user_messages_by_email():
    token = get_param_or_default("token")
    email = get_param_or_default("email")
    if db.is_connected(token):
        if db.find_user(email) != None:
            success(SUC_GET_USER_DATA,
                    db.get_user_messages_by_email(token, email))
        else:
            err(ERR_USER_NOT_FOUND)
    else:
        err(ERR_USER_NOT_CONNECTED)
    return json.dumps(output)
Esempio n. 16
0
def post_message():
    data = request.json
    token = data["token"]
    message = data["messages"]
    receiver = data["receiver"]
    #print(receiver)
    if database_helper.find_inlogged(token) is not None:
        sender = database_helper.find_inlogged(token)
        if receiver is None:
            receiver = sender
        if database_helper.find_user(receiver) is not None:
            recipient = database_helper.find_user(receiver)['email']
            print(recipient)
            print(database_helper.create_post(sender, message, recipient))
            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."
        })
Esempio n. 17
0
def sign_in():
    ''' Return; A text string containing a randomly generated access token if the authentication is successful. '''
    email = request.form['email']
    password = request.form['password']
    result = database_helper.find_user(email, password=password, status='LOGIN')
    if result:
        letters = "abcdefghiklmnopqrstuvwwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
        token = ""
        for i in range(0, 36):
            token += letters[random.randint(0, 61)]
        database_helper.add_sign_in_user(result[0],email,token)
        return jsonify({"status": 200, "token": token})
    else:
        return jsonify({"status": 404})
Esempio n. 18
0
def get_user_messages_by_email():
    token = get_param_or_default("token")
    email = get_param_or_default("email")
    if db.is_connected(token):
        if db.find_user(email) != None:
            messages = []
            for message_id, message, sender in db.get_user_messages_by_email(token,email):
                messageObject = {"id": message_id, "content": message, "writer": sender}
                messages.append(messageObject)
            success(SUC_GET_USER_DATA, messages)
        else:
            err(ERR_USER_NOT_FOUND)
    else:
        err(ERR_USER_NOT_CONNECTED)
    return json.dumps(output)
Esempio n. 19
0
def sign_in():
    data = request.json
    email = data["email"]
    password = data["password"]
    print(password)

    database_helper.delete_logged_in_by_email(email)

    if database_helper.find_user(
            email) is not None and database_helper.find_user(
                email)["password"] == password:
        token = str(uuid.uuid4())
        database_helper.insert_token(token, email)
        return json.dumps({
            "Success": True,
            "message": "Successfully signed in",
            "data": token
        })

    else:
        return json.dumps({
            "Success": False,
            "message": "Wrong username or password"
        })
def sign_in():
    data = request.get_json()

    if (database_helper.find_user(
            data['email'], data['password'])):  #verify with database password,
        userToken = secrets.token_hex(12)  #CREATE TOKEN
        if database_helper.login_user(data['email'], userToken):
            return jsonify(success="true",
                           message="Login checks out B)",
                           token=userToken)  #SAVE TOKEN
        else:
            return jsonify(success=False,
                           message="couldnt add a user with that email")
    else:
        return 'wrong credentials', 400
Esempio n. 21
0
def sign_in(email, password):
    res = dh.find_user(email, password)
    if not res:
        # Not logged in
        return json.dumps({"message": "Invalid email or password"}), 501
    else:
        # Logged in
        letters = "abcdefghiklmnopqrstuvwwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
        token = ""
        for i in range(36):
            token += letters[int(math.floor(random.random() * len(letters)))]
        dh.sign_in(email, token)
        return json.dumps({
            "message": "You are now signed in",
            "data": token
        }), 200
Esempio n. 22
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)
Esempio n. 23
0
def signin():
    req = request.get_json(force=True)
    email = req['email']
    password = req['password']
    # See if user exists in database
    if database_helper.find_user(email, password):
        token = uuid.uuid4().hex
        # Add user to logged in users
        if database_helper.login_user(email, token):
            # Send stats to all users
            send_stats(True)
            return jsonify(success=True, message="Login successful!", data=token)
        else:
            # Shouldn't happen
            return jsonify(success=False, message="Failed to login user!")
    else:
        return jsonify(success=False, message="Username or password incorrect!")
Esempio n. 24
0
def sign_up():
    body = json.loads(request.data.decode("utf-8"))
    data = body['data']
    password = _password_hasher(data['password'])
    result = database_helper.find_user(data['email'])
    if result != None:
        return _return_json_message(False, "User already exists")
    if (len(data["email"]) == 0 or len(data["password"]) < 4
            or len(data['firstname']) == 0 or len(data['familyname']) == 0
            or len(data['gender']) == 0 or len(data['city']) == 0
            or len(data['country']) == 0):
        return _return_json_message(False, "Error in provided data")
    else:
        database_helper.signup(data['email'], data['firstname'],
                               data['familyname'], data['city'],
                               data['gender'], password, data['country'])
        return _return_json_message(True, "Successfully created user")
Esempio n. 25
0
def signin():
    email = request.form['email']
    password = request.form['password']

    # See if user exists in database
    if database_helper.find_user(email, password):
        token = uuid.uuid4().hex
        # Add user to logged in users
        if database_helper.login_user(email, token):
            return jsonify(success="true",
                           message="Login successful!",
                           data=token)
        else:
            # Shouldn't happen
            return jsonify(success=False, message="Failed to login user!")
    else:
        return jsonify(success=False,
                       message="Username or password incorrect!")
Esempio n. 26
0
def get_user_data_by_token(token = None):
	
	if token is None:
		return json.dumps({"success": False, "message":"Key error."}),400

	# Check if the token exists
	if not token:
		return json.dumps({"success": False, "message":"You are not signed in."}),403

	# Check if the current user exists
	email = database_helper.get_emailByToken(token)
	if not email:
		return json.dumps({"success": False, "message":"No such user."}),404
	
	# Return the user profile
	data = database_helper.find_user(email)
	numOfPost = database_helper.get_num_post(email)
	totalOfPost = database_helper.get_totalnum_post()
	return json.dumps({"success": True, "message": "User data retrieved.", "data": [dict(x) for x in data], "NumOfPost":str(numOfPost), "TotalOfPost":str(totalOfPost)}),200
Esempio n. 27
0
def sign_up():



    user = {"email" : get_param_or_default("email"), \
            "password" : get_param_or_default("password"), \
            "firstname" : get_param_or_default("firstname"), \
            "familyname" : get_param_or_default("familyname"), \
            "gender" : get_param_or_default("gender"), \
            "city" : get_param_or_default("city"), \
            "country" : get_param_or_default("country") \
            }


    if emailRegex.match(user["email"]):
        if user["firstname"] != "":
            if user["familyname"] != "":
                if user["city"] != "":
                    if user["country"] != "":
                        if db.find_user(user["email"]) == None:
                            if len(user["password"]) > 5:
                                if user["gender"] == "male" or user["gender"] == "female":
                                    db.sign_up(user)
                                    success(SUC_USER_SIGNED_UP)
                                else:
                                    err(ERR_GENDER_IS_NOT_CORRECT)
                            else:
                                err(ERR_PASSWORD_TOO_SHORT)
                        else:
                            err(ERR_USER_ALREADY_EXISTS)
                    else:
                        err(ERR_EMPTY_COUNTRY)
                else:
                    err(ERR_EMPTY_CITY)
            else:
                err(ERR_EMPTY_FAMILY_NAME)
        else:
            err(ERR_EMPTY_FIRST_NAME)
    else:
        err(ERR_INVALID_EMAIL)

    return json.dumps(output)
Esempio n. 28
0
def Change_password():
    data = request.json
    token = data["token"]
    oldPassword = data["oldpassword"]
    newPassword = data["newpassword"]
    if database_helper.find_inlogged(token) is not None:
        email = database_helper.find_inlogged(token)
        if oldPassword == database_helper.find_user(email)["password"]:
            database_helper.update_password(email, newPassword)
            return json.dumps({
                "success": True,
                "message": "Password changed."
            })
        else:
            return json.dumps({"success": False, "message": "Wrong password."})
    else:
        return Json.dumps({
            "success": False,
            "message": "You are not logged in."
        })
Esempio n. 29
0
def sign_in():
    """Sign in
	Gets email and password from JSON form and searches for user in database
    If user exists, log in user
    """
    data = request.get_json()
    email = data['email']
    pwd = data['pwd']

    if not (database_helper.find_user(email, pwd)):
        res = jsonify({'success': False, 'message': 'Wrong email or password'})
        return res
    token = database_helper.login_user(email)

    if(token):
        res = jsonify(
            {'success': True, 'message': 'Signed in!', 'token': token})
        return res
    else:
        res = jsonify({'success': False, 'message': 'Something went wrong!'})
        return res
Esempio n. 30
0
def get_user_messages_by_email(token = None, toEmail = None):
	
	if token is None or toEmail is None:
		return json.dumps({"success": False, "message":"Key error."}),400

	# Check if the token exists (current user)
	if not token:
		return json.dumps({"success": False, "message":"You are not signed in."}),403

	# Check if the current user exists
	email = database_helper.get_emailByToken(token)
	if not email:
		return json.dumps({"success": False, "message":"No such user."}),404
	
	# Check if the target user exists
	if not database_helper.find_user(toEmail):
		return json.dumps({"success": False, "message":"No such user."}),404
		
	# Return all messages of target user
	message = database_helper.get_msglist(toEmail)
	return json.dumps({"success": True, "message": "User data retrieved.", "data": [dict(x) for x in message]}),200