def post(self):
        """ Method to login a user and obtain a token """
        parser = reqparse.RequestParser()
        parser.add_argument('email',
                            type=str,
                            required=True,
                            help='Email must be a valid email')
        parser.add_argument('password',
                            type=str,
                            required=True,
                            help='Password must be a valid string')
        data = parser.parse_args()

        usr = User(None, None, data['email'], data['password'])
        row = usr.login_user(data['email'], data['password'])
        if row:
            expires = timedelta(minutes=60)
            user_id = row[0]
            token = create_access_token(identity=user_id,
                                        expires_delta=expires)

            return make_response(
                jsonify({
                    'status': "success",
                    'message': "Successfully logged in",
                    'token': token
                }), 200)
        return make_response(
            jsonify({
                'status': "failed",
                'message': "Invalid username or password."
            }), 401)
Beispiel #2
0
 def test_get_user_by_id(self):
     self.create_test_user()
     obj = User(None, None, None, None)
     Found = False
     result = obj.get_user_by_id(1)
     if result:
         Found = True
     self.assertEqual(Found, True)
Beispiel #3
0
 def test_get_user_by_email(self):
     self.create_test_user()
     obj = User(None, None, None, None)
     Found = False
     usr = obj.get_user_by_email("*****@*****.**")
     if usr:
         Found = True
     self.assertEqual(Found, True)
Beispiel #4
0
def update_password():
    """Update user password"""
    try:
        data = request.get_json()
        email = data['email']
        password = data['password']

    except KeyError:
        abort(
            override_make_response("error", "Keys should be email & password",
                                   400))

    # check if any field is empty
    check_for_details_whitespace(data, ["email", "password"])
    # then check if email is valid
    is_email_valid(email)
    # then check if password is valid
    is_valid_password(password)
    # then check if user exists
    user = User.get_user_by_email(email)
    if not user:
        abort(
            override_make_response(
                "error", "No account associated with that email was found !",
                404))
    # if all is ok update user password.
    User.update_password(email, password)

    token = jwt.encode({"email": email}, KEY, algorithm="HS256")

    # send email on sign up
    subject = """Password changed successfully."""
    content = f"""
    Hey,
    <br/>
    <br/>
    Your password has been updated successfully.<br/>
    If you did not initialize this action <br/>
    please change your password
    <a href="{link}?in={token.decode('utf-8')}">here</a> 
    <br/>
    <br/>
    Regards Antony,<br/>
    Kabucketlist. 
    """
    send_mail(email, subject, content)

    return override_make_response("data",
                                  "You have set a new password successfully.",
                                  200)
Beispiel #5
0
def user_login():
    """Authorize the user to access the system"""
    try:
        data = request.get_json()
        email = data["email"]
        entered_password = data["password"]
    except KeyError:
        abort(
            override_make_response("error", "Keys should be email,password",
                                   400))

    # check if any field is empty
    check_for_details_whitespace(data, ["email", "password"])
    # then check if email is valid
    is_email_valid(email)

    try:
        # see if user exists
        user = User.get_user_by_email(email)
        if not user:
            abort(
                override_make_response("error",
                                       "User not found, please check email.",
                                       404))

        # format the returned user
        user_id = user[0][0]
        email = user[0][2]
        returned_password = user[0][3]
        password_check = User.compare_password(returned_password,
                                               entered_password)
        if not password_check:
            abort(
                override_make_response(
                    "error", "Password is incorrect, please try again", 401))

        # check if user has confirmed their email
        if User.is_email_verified(email)[0][0] == 'False':
            abort(
                override_make_response("error",
                                       "please confirm your email to sign in",
                                       401))

        token = jwt.encode({"email": email}, KEY, algorithm="HS256")

        return override_make_response("data", token.decode('utf-8'), 200)
    except psycopg2.DatabaseError as _error:
        abort(
            override_make_response("error", "Server error, contact admin.",
                                   500))
Beispiel #6
0
def user_signup():
    """Signs a  new user up"""
    try:
        data = request.get_json()
        firstname = data["firstname"]
        email = data["email"]
        password = data["password"]
    except:
        abort(
            override_make_response(
                "error", "Keys should be 'firstname','email','password'", 400))

    # check if any field is empty
    check_for_details_whitespace(data, ["firstname", "email", "password"])
    # first check if email is valid
    is_email_valid(email)
    # is the email already in use or not
    if User.get_user_by_email(email):
        abort(
            override_make_response(
                "error", "The email is already in use, choose another one",
                409))
    # check if password meets expectations
    is_valid_password(password)
    new_user = User(firstname=firstname, email=email, password=password)
    new_user.create_user()
    token = jwt.encode({"email": email}, KEY, algorithm="HS256")

    # send email on sign up
    subject = """Welcome to Kabucketlist"""
    content = f"""
    Hey {firstname},
    <br/>
    <br/>
    Welcome to kabucketlist, to activate your account<br/>
    please verify your email by clicking on this
    <a href="{url}?in={token.decode('utf-8')}">link</a>.
    <br/>
    <br/>
    Regards Antony,<br/>
    Kabucketlist. 
    """
    send_mail(email, subject, content)
    return override_make_response("data", [{
        "firstname": firstname,
        "email": email,
        "token": token.decode('utf-8')
    }], 201)
    def post(self):
        """
        Allows users(admins and customers) to create accounts
        """

        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, required=True)
        parser.add_argument('email', type=str, required=True)
        parser.add_argument('password', type=str, required=True)

        args = parser.parse_args()
        username = args['username']
        email = args['email']
        password = args['password']

        if username.strip() == "" or len(username.strip()) < 2:
            return make_response(
                jsonify({"message": "invalid, Enter name please"}), 400)

        if re.compile('[!@#$%^&*:;?><.0-9]').match(username):
            return make_response(
                jsonify({"message": "Invalid characters not allowed"}), 400)

        if not re.match(r"([\w\.-]+)@([\w\.-]+)(\.[\w\.]+$)", email):
            return make_response(jsonify({"message": "Enter valid email"}),
                                 400)

        if password.strip() == "":
            return make_response(jsonify({"message": "Enter password"}), 400)

        if len(password) < 5:
            return make_response(
                jsonify({"message": "Password is too short, < 5"}), 400)

        new_user = User(username, email, password)

        for user in users_list:
            if email == user['email']:
                return make_response(
                    jsonify({"message": "email already in use"}), 400)

        users_list.append(json.loads(new_user.json()))
        return make_response(
            jsonify({
                'message': 'User successfully created',
                'email': new_user.email
            }), 201)
 def get(self):
     """ Method to retrieve all exisiting users """
     usr = User(None, None, None, None)
     users = usr.get_all_users()
     if not users:
         return make_response(
             jsonify({
                 'message': 'No users subscribed as yet',
             }), 200)
     user_lst = []
     for u in users:
         user = {
             "user_id": u[0],
             "first_name": u[1],
             "last_name": u[2],
             "email": u[3],
             "password": u[4]
         }
         user_lst.append(user)
     return make_response(jsonify({
         'status': 'success',
         'users': user_lst
     }), 200)
 def get(self):
     """ Method to get a user's details """
     usr = User(None, None, None, None)
     user_id = get_jwt_identity()
     user = usr.get_user_by_id(user_id)
     if user:
         ent = Entry(None, None, None)
         result = ent.get_all_entries(user_id)
         count = len(result)
         user_profile = {
             "user_id": user[0],
             "first_name": user[1],
             "last_name": user[2],
             "email": user[3],
             "entries_count": count
         }
         return make_response(
             jsonify({
                 'status': 'success',
                 'profile': user_profile
             }), 200)
     return make_response(jsonify({
         'message': 'User not found',
     }), 404)
Beispiel #10
0
def send_reset():
    """This sends the email instructions on how to reset password """
    try:
        data = request.get_json()
        email = data['email']

    except KeyError:
        abort(override_make_response("error", "Key should be email", 400))

    # check if any field is empty
    check_for_details_whitespace(data, ["email"])
    # then check if email is valid
    is_email_valid(email)
    # then check if user exists
    user = User.get_user_by_email(email)
    if not user:
        abort(
            override_make_response(
                "error", "No account associated with that email was found !",
                404))

    token = jwt.encode({"email": email}, KEY, algorithm="HS256")

    # send email on sign up
    subject = """Password reset instructions"""
    content = f"""
    Hey,
    <br/>
    <br/>
    You have requested to reset your password<br/>
    please  click on the following 
    <a href="{link}?in={token.decode('utf-8')}">link</a><br/>
    If you wish to continue with reset, ignore if you did<br/> 
    not initialize the action.
    <br/>
    <br/>
    Regards Antony,<br/>
    Kabucketlist. 
    """
    send_mail(email, subject, content)

    return override_make_response(
        "data", f"Password reset instructions sent to {email} successfully",
        202)
 def post(self):
     """ Method to signup a user """
     parser = reqparse.RequestParser()
     parser.add_argument('first_name',
                         type=str,
                         required=True,
                         help='First name must be a valid string')
     parser.add_argument('last_name',
                         type=str,
                         required=True,
                         help='Last name must be a valid string')
     parser.add_argument('email',
                         type=str,
                         required=True,
                         help='Email must be a valid email')
     parser.add_argument('password',
                         type=str,
                         required=True,
                         help='Password must be a valid string')
     data = parser.parse_args()
     if (data['first_name'].strip()
             == "") or (data['last_name'].strip()
                        == "") or (data['email'].strip()
                                   == '') or (data['password'].strip()
                                              == ''):
         return make_response(
             jsonify({
                 'status':
                 'failed',
                 'message':
                 'The fistname or lastname or email or password can not be empty.'
             }), 400)
     if (not data['first_name'].isalpha()) or (
             not data['last_name'].isalpha()):
         return make_response(
             jsonify({
                 'status': 'failed',
                 'message': 'Firstname or Lastname is invalid'
             }), 400)
     if not re.match("[^@]+@[^@]+\.[^@]+", data['email']):
         return make_response(
             jsonify({
                 'status':
                 'failed',
                 'message':
                 'Provided email is not a valid email address.'
             }), 400)
     if len(data['password']) < 4:
         return make_response(
             jsonify({
                 'status':
                 'failed',
                 'message':
                 'Password must be atleast 4 characters in length.'
             }), 400)
     user = User(data['first_name'], data['last_name'], data['email'],
                 data['password'])
     result = user.get_user_by_email(data['email'])
     if result != 0:
         return make_response(
             jsonify({
                 'status': "failed",
                 'message': 'This email is already used',
             }), 400)
     user.add_user()
     return make_response(
         jsonify({
             'status': "success",
             'message': 'Account successfully created',
         }), 201)
Beispiel #12
0
def verify_email(user):
    """verifies signed up user email"""
    email = user[0][1]
    User.verify_email(email)
    return render_template('verify.html')
Beispiel #13
0
def get_specific_user(user_id):
    """Get a specific user"""
    return check_return(User.get_user_by_id(user_id))
Beispiel #14
0
def get_all_users():
    """List all system users"""
    return check_return(User.get_all_users())