Exemplo n.º 1
0
 def post(self):
     post_data = request.get_json()
     try:
         user = User.query.filter_by(email=post_data.get('email')).first()
         if user and bcrypt.check_password_hash(user.password,
                                                post_data.get('password')):
             auth_token = user.encode_auth_token(user.id)
             if auth_token:
                 responseObject = {
                     'status': 'success',
                     'message': 'Successfully logged in.',
                     'auth_token': auth_token.decode()
                 }
                 return make_response(jsonify(responseObject)), 200
         elif user and not bcrypt.check_password_hash(
                 user.password, post_data.get('password')):
             responseObject = {
                 'status': 'fail',
                 'message': 'Wrong credentials.',
             }
             return make_response(jsonify(responseObject)), 401
         else:
             responseObject = {
                 'status': 'fail',
                 'message': 'User does not exist.'
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         print(e)
         responseObject = {'status': 'fail', 'message': 'Try again.'}
         return make_response(jsonify(responseObject)), 500
Exemplo n.º 2
0
 def test_check_password(self):
     # Ensure given password is correct after unhashing.
     user = User.query.filter_by(email="*****@*****.**").first()
     self.assertTrue(
         bcrypt.check_password_hash(user.password, "admin_user")
     )
     self.assertFalse(bcrypt.check_password_hash(user.password, "foobar"))
Exemplo n.º 3
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         username = post_data.get('username')
         user = User.find_one_by_username(username)
         print(user)
         if user and bcrypt.check_password_hash(user["password"],
                                                post_data.get('password')):
             auth_token = User.encode_auth_token(user["_id"])
             auth_token_decoded = auth_token.decode()
             if auth_token:
                 responseObject = {
                     'status': 'success',
                     'message': 'Successfully logged in.',
                     'auth_token': auth_token_decoded
                 }
                 return make_response(jsonify(responseObject)), 200
         else:
             responseObject = {
                 'status': 'fail',
                 'message': 'User does not exist.'
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         print(e)
         responseObject = {'status': 'fail', 'message': 'Try again'}
         return make_response(jsonify(responseObject)), 500
Exemplo n.º 4
0
def login():
    # get the post data
    post_data = request.get_json()
    print(post_data)
    try:
        registration = Registration.query.filter_by(
            email=post_data.get('email')).first()
        if registration:
            print(registration.id)
            user = User.query.filter_by(id=registration.id).first()
            if user:
                if bcrypt.check_password_hash(user.password,
                                              post_data.get('password')):
                    auth_token = user.encode_auth_token(user.id)
                    print(auth_token)
                    return make_response(
                        jsonify({
                            'message': 'Successfully logged in.',
                            'auth_token': auth_token.decode(),
                            'status': 'success',
                        })), 200
        else:
            return make_response(
                jsonify({
                    'status': 'fail',
                    'message': 'User does not exist.'
                })), 400

    except Exception as e:
        print(e)
        return make_response(
            jsonify({
                'message': 'Unknown error logging in.',
                'status': 'fail'
            })), 500
Exemplo n.º 5
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(
             email=post_data.get('email')
         ).first()
         if user and bcrypt.check_password_hash(
             user.password, post_data.get('password')
         ):
             auth_token = user.encode_auth_token(user.id)
             if auth_token:
                 response_object = {
                     'status': 'success',
                     'message': 'Successfully logged in.',
                     'auth_token': auth_token.decode(),
                     'status_code': 200
                 }
                 return make_response(jsonify(response_object)), 200
         else:
             response_object = {
                 'status': 'fail',
                 'message': 'There is a problem with your email and/or password.',
                 'status_code': 404
             }
             return make_response(jsonify(response_object)), 404
     except Exception as e:
         print(e)
         response_object = {
             'status': 'fail',
             'message': 'Try again',
             'status_code': 500
         }
         return make_response(jsonify(response_object)), 500
Exemplo n.º 6
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(email=post_data.get('email')).first()
         if user and bcrypt.check_password_hash(user.password,
                                                post_data.get('password')):
             auth_token = user.encode_auth_token(user.id)
             if auth_token:
                 responseObject = {
                     'status': 'success',
                     'message': 'Successfully logged in.',
                     'email': user.email,
                     'auth_token': auth_token
                 }
                 return make_response(jsonify(responseObject)), 200
         else:
             responseObject = {
                 'status': 'fail',
                 # I keep User does not exist instead of wrong password to not allow hackers
                 # to validate which emails have an account.
                 'message': 'User does not exist.'
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         print(e)
         responseObject = {'status': 'fail', 'message': 'Try again'}
         return make_response(jsonify(responseObject)), 500
Exemplo n.º 7
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(
             username=post_data.get('username')).first()
         if user and bcrypt.check_password_hash(user.password,
                                                post_data.get('password')):
             token = user.encode_token(user.id)
             responseObject = {
                 'status': 'success',
                 'message': 'Successfully logged in.',
                 'username': user.username,
                 'token': token.decode()
             }
             return make_response(jsonify(responseObject)), 200
         else:
             responseObject = {
                 'status': 'fail',
                 'message': 'User does not exist.'
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         WARN(e)
         responseObject = {'status': 'fail', 'message': 'Try again'}
         return make_response(jsonify(responseObject)), 500
Exemplo n.º 8
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     if post_data is None:
         return CommonResponseObject.fail_response(
             'Please provide required data', status.HTTP_404_NOT_FOUND)
     try:
         # fetch the user data
         user = User.get_user_by_email(post_data.get('email'))
         if user and not user.is_confirmed:
             return CommonResponseObject.fail_response(
                 'Please confirm your email address which is sent to your email',
                 status.HTTP_403_FORBIDDEN)
         mac_address = post_data.get('mac_address')
         if not mac_address:
             return CommonResponseObject.fail_response(
                 'Please provide your MAC address',
                 status.HTTP_412_PRECONDITION_FAILED)
         if user and bcrypt.check_password_hash(user.password,
                                                post_data.get('password')):
             device = DeviceList.get_device_by_user_id_and_mac(
                 user.id, mac_address)
             root = DeviceList.get_root_device(user.id)
             auth_token = DatabaseCheck.prepare_auth_token(
                 user.id, mac_address,
                 None if not device else device.main_key,
                 True if root else False)
             if auth_token:
                 return CommonResponseObject.login_success(auth_token)
         else:
             return CommonResponseObject.login_user_not_exist()
     except Exception as e:
         print(e)
         return CommonResponseObject.login_exception()
Exemplo n.º 9
0
 def post(self):
     # Get the post data
     post_data = request.get_json()
     try:
         
         # Fetch the user data
         user = User.query.filter_by(
             email = post_data.get('email')
         ).first()
         
         if user and bcrypt.check_password_hash(
                 user.password, post_data.get('password')
         ):
             auth_token = user.encode_auth_token(user.id)
             if auth_token:
                 responseObject = {
                     'status': 'success',
                     'message': 'Successfully logged in.',
                     'auth_token': auth_token.decode()
                 }
                 return make_response(jsonify(responseObject)), 200
         else:
             responseObject = {
                 'status': 'fail',
                 'message': 'The username and password combination do not match our records.'
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         responseObject = {
             'status': 'fail',
             'message': 'Try again'
         }
         print(e)
         return make_response(jsonify(responseObject)), 500
Exemplo n.º 10
0
    def post(self):
        # get the post data
        post_data = request.get_json()
        try:
            # fetch the user data
            user = User.query.filter_by(email=post_data.get('email')).first()

            if user and bcrypt.check_password_hash(user.password,
                                                   post_data.get('password')):
                auth_token = user.encode_auth_token(user.id)
                if auth_token:
                    # update user lastlogin
                    user.lastlogin_on = datetime.datetime.now()
                    db.session.commit()
                    responseObject = {
                        'status': 'success',
                        'message': 'Successfully logged in.',
                        'auth_token': auth_token
                    }
                    return make_response(jsonify(responseObject)), 200
            else:
                responseObject = {
                    'status': 'fail',
                    'message': 'User does not exist.'
                }
                return make_response(jsonify(responseObject)), 401
        except Exception as e:
            print(e)
            responseObject = {'status': 'fail', 'message': 'Try again'}
            return make_response(jsonify(responseObject)), 500
Exemplo n.º 11
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(
             email=post_data.get('email')
         ).first()
         if user and bcrypt.check_password_hash(
             user.password, post_data.get('password')
         ):
             auth_token = user.encode_auth_token(user.id)
             if auth_token:
                 responseObject = {
                     'status': 'success',
                     'message': 'Successfully logged in.',
                     'auth_token': auth_token.decode()
                 }
                 return make_response(jsonify(responseObject)), 200
         else:
             responseObject = {
                 'status': 'fail',
                 'message': 'User does not exist.'
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         print(e)
         responseObject = {
             'status': 'fail',
             'message': 'Try again'
         }
         return make_response(jsonify(responseObject)), 500
Exemplo n.º 12
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(email=post_data.get('email')).first()
         if user and bcrypt.check_password_hash(user.password,
                                                post_data.get('password')):
             auth_token = user.encode_auth_token(user.id)
             if auth_token:
                 responseObject = {
                     'status': 'success',
                     'message': 'Successfully logged in.',
                     'auth_token': auth_token.decode()
                 }
                 return make_response(jsonify(responseObject)), 200  #Ok
         else:
             responseObject = {
                 'status': 'fail',
                 'message': 'User does not exist.'
             }
             return make_response(jsonify(responseObject)), 404  #Not Found
     except Exception as e:
         print(e)
         responseObject = {'status': 'fail', 'message': 'Try again'}
         return make_response(
             jsonify(responseObject)), 500  #Internal Server Error
Exemplo n.º 13
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(email=post_data.get("email")).first()
         if user and bcrypt.check_password_hash(user.password,
                                                post_data.get("password")):
             auth_token = user.encode_auth_token(user.id)
             if auth_token:
                 responseObject = {
                     "status": "success",
                     "message": "Successfully logged in.",
                     "auth_token": auth_token.decode(),
                 }
                 return make_response(jsonify(responseObject)), 200
         else:
             responseObject = {
                 "status": "fail",
                 "message": "User does not exist."
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         print(e)
         responseObject = {"status": "fail", "message": "Try again"}
         return make_response(jsonify(responseObject)), 500
Exemplo n.º 14
0
def login():
    """View function for login view."""
    logging.info('usre login start')

    params = request.get_json()
    email = params.get('email', None)
    password = params.get('password', None)
    client_ip = params.get('client_ip', None)
    logging.info('usre login start db call')
    user = Users.query.filter_by(email=email).first()
    logging.info('usre login start db call success')
    if not user:
        return wrapper.wrapper(None, "User not found.", 200), 200
    if user:
        if user.confirmed is True:
            logging.info('usre login start validation user call')
            compare = bcrypt.check_password_hash(user.password, password)
            # TODO Check from DB here
            if compare is False:
                return wrapper.wrapper(None, "Bad email or password", 201), 201
            else:
                user_type = user.user_type
                user_group = user.user_group
                # sesson = User_Session.query.filter_by(user_id=user.id).first()

                # if sesson is not None:
                #   return wrapper.wrapper(None, "Already Loged In To Ip:" + sesson.client_ip, 201), 201

                # else:
                #   model_session = User_Session(client_ip=client_ip, user_id=user.id, user_name=user.name, user_type=user.user_type,
                #                          status='LogedIn')

                # db.session.add(model_session)
                # db.session.commit()
                # user_type = user.user_type
                # user_group = user.user_group

                ret = {
                    'jwt': create_jwt(identity=user_group),
                    'role': user_type,
                    'user_id': user.id,
                    'exp':
                    datetime.utcnow() + current_app.config['JWT_EXPIRES']
                }
                return wrapper.wrapper(ret, None, 200), 200
        else:
            logging.info('usre login success')
            return wrapper.wrapper(
                None, "Email not validated. Please validate and try again.",
                200), 200

    if not email:
        return wrapper.wrapper(None, "Missing email parameter", 201), 201
    if not password:
        return wrapper.wrapper(None, "Missing password parameter", 201), 201
Exemplo n.º 15
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(email=post_data.get('email')).first()
         # Check if user exists and provided password matches one stored
         if user and bcrypt.check_password_hash(user.password,
                                                post_data.get('password')):
             auth_token = user.encode_auth_token(user.id)
             if auth_token:
                 response_object = {
                     'status': 'success',
                     'message': 'Successfully logged in.',
                     'auth_token': auth_token.decode()
                 }
                 return make_response(jsonify(response_object)), 200
         else:
             if user is None:
                 response_object = {
                     'status': 'fail',
                     'message': 'User does not exist.'
                 }
             elif not bcrypt.check_password_hash(user.password,
                                                 post_data.get('password')):
                 response_object = {
                     'status': 'fail',
                     'message': 'Wrong credentials, please try again.'
                 }
             return make_response(jsonify(response_object)), 404
         auth_token = user.encode_auth_token(user.id)
         if auth_token:
             response_object = {
                 'status': 'success',
                 'message': 'Successfully logged in.',
                 'auth_token': auth_token.decode()
             }
             return make_response(jsonify(response_object)), 200
     except Exception as e:
         # print(e)
         response_object = {'status': 'fail', 'message': 'Try again'}
         return make_response(jsonify(response_object)), 500
Exemplo n.º 16
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            login_user(user)
            flash('You are logged in. Welcome!', 'success')
            return redirect(url_for('user.account', id=user.id))
        else:
            flash('Invalid email and/or password.', 'danger')
    return render_template('user/login.html', form=form)
Exemplo n.º 17
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               request.form['password']):
            login_user(user)
            flash('You are logged in. Welcome!', 'success')
            return redirect(url_for('user.account', id=user.id))
        else:
            flash('Invalid email and/or password.', 'danger')
    return render_template('user/login.html', form=form)
Exemplo n.º 18
0
    def post(self):
        post_data = request.get_json()
        response_msg = []
        if post_data.get('email') == '':
            response_msg.append('email must be non-empty')
        if post_data.get('password') == '':
            response_msg.append('password must be non-empty')

        if len(response_msg) > 0:
            responseObject = {
                'status': 'failed',
                'message': response_msg
            }
            return make_response(jsonify(responseObject)), 403

        if not validators.email(post_data.get('email')):
            print('hello')
            responseObject = {
                    'status': 'fail',
                    'message': 'Provide a valid e-mail.'
                }
            return make_response(jsonify(responseObject)), 403
        try:
            user = DashboardUser.query.filter_by(
                email=post_data.get('email')
            ).first()
            if user and bcrypt.check_password_hash(
                user.password, post_data.get('password')
            ):
                auth_token = user.encode_auth_token(user.id)
                current_app.logger.info(auth_token)
                current_app.logger.info(type(auth_token))
                if auth_token:
                    responseObject = {
                        'status': 'success',
                        'message': 'Successfully logged in.',
                        'auth_token': auth_token.decode(),
                    }
                    return make_response(jsonify(responseObject)), 200
            else:
                responseObject = {
                    'status': 'fail',
                    'message': 'E-mail/Password is wrong.'
                }
                return make_response(jsonify(responseObject)), 400
        except Exception as e:
            print(e)
            responseObject = {
                'status': 'fail',
                'message': 'User Login Failed because of wrong email/password.'
            }
            return make_response(jsonify(responseObject)), 400
Exemplo n.º 19
0
    def post(self):
        # check the grant_type
        if ('grant_type' not in request.form) or (request.form['grant_type'] !=
                                                  'password'):

            responseObject = {
                'status': 'fail',
                'message': 'unsupported_grant_type'
            }

            return make_response(jsonify(responseObject)), 400

        try:
            username = request.form['username']
            password = request.form['password']

            # try to fetch the user data by screen_name
            user = User.query.filter_by(screen_name=username).first()

            # if that fails, try email
            if not user:
                user = User.query.filter_by(email=username).first()

            if user and bcrypt.check_password_hash(user.password, password):
                auth_token, exp = user.encode_auth_token(user.id)
                if auth_token:
                    responseObject = {
                        'status': 'success',
                        'message': 'Successfully logged in.',
                        'auth_token': auth_token.decode(),
                        'expires': exp
                    }
                    return make_response(jsonify(responseObject)), 200

            elif user:
                responseObject = {
                    'status': 'fail',
                    'message': 'Incorrect email or password.'
                }
                return make_response(jsonify(responseObject)), 405

            else:
                responseObject = {
                    'status': 'fail',
                    'message': 'User does not exist.'
                }
                return make_response(jsonify(responseObject)), 404

        except Exception as e:
            print(e)
            responseObject = {'status': 'fail', 'message': 'Try again'}
            return make_response(jsonify(responseObject)), 500
Exemplo n.º 20
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               request.form["password"]):
            login_user(user)
            flash("You are logged in. Welcome!", "success")
            return redirect(url_for("user.members"))
        else:
            flash("Invalid email and/or password.", "danger")
            return render_template("user/login.html", form=form)
    return render_template("user/login.html", title="Please Login", form=form)
Exemplo n.º 21
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            login_user(user)
            flash('Bienvenido', 'success')
            return redirect(url_for('main.home'))
        else:
            flash('Password o usuario incorrectos', 'danger')
            return render_template('user/login.html', form=form)
    return render_template('user/login.html', title='Please Login', form=form)
Exemplo n.º 22
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            login_user(user)
            user.last_login = datetime.datetime.now()
            db.session.commit()
            flash('You are logged in. Welcome!', 'success')
            return redirect(url_for('user.members'))
        else:
            flash('Invalid email and/or password.', 'danger')
            return render_template('user/login.html', form=form)
    return render_template('user/login.html', title='Please Login', form=form)
Exemplo n.º 23
0
    def post(self):
        # get the post data
        post_data = request.get_json()
        if iroha_health_check():
            try:
                print(post_data)
                user = User.query.filter_by(
                    account_id=post_data["account_id"]).first()
                # write login tx to iroha
                print(f"user {user}")
                account_id = user.account_id
                transaction = post_data.get("transaction")
                # print(transaction)
                transaction["payload"]["reducedPayload"][
                    "commands"] = transaction["payload"]["reducedPayload"].pop(
                        "commandsList")
                transaction["signatures"] = transaction.pop("signaturesList")

                if user and bcrypt.check_password_hash(
                        user.password, post_data.get("password")):
                    auth_token = user.encode_auth_token(user.id)
                    if auth_token:
                        submit_tx_to_iroha(account_id, transaction)
                        responseObject = {
                            "status": "success",
                            "email": user.email,
                            "message": "Successfully logged in.",
                            "auth_token": auth_token.decode(),
                        }
                        return make_response(jsonify(responseObject)), 200
                else:
                    responseObject = {
                        "status": "fail",
                        "message": "User does not exist.",
                    }
                    return make_response(jsonify(responseObject)), 404
            except Exception as e:
                print(e)
                responseObject = {"status": "fail", "message": "Try again"}
                return make_response(jsonify(responseObject)), 500
        else:
            responseObject = {
                "status":
                "fail",
                "message":
                "Blockchain Service is offline. Please Contact Support or wait a few minutes and try again",
            }
            return make_response(jsonify(responseObject)), 405
Exemplo n.º 24
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            login_user(user)
            user.last_login = datetime.datetime.utcnow()
            db.session.commit()

            flash('You are logged in. Welcome!', 'success')
            return redirect(url_for('user_model.members'))
        else:
            flash('Invalid username and/or password.', 'danger')
            return render_template('user/login.html', form=form)
    return render_template('user/login.html', title='Please Login', form=form)
Exemplo n.º 25
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(
             email=post_data.get('email')
         ).first()
         if user:
             if bcrypt.check_password_hash(
                 user.password, post_data.get('password')
             ):
                 if user.confirmed:
                     auth_token = user.encode_auth_token(user.id)
                     if auth_token:
                         responseObject = {
                             'status': 'success',
                             'message': 'Successfully logged in.',
                             'auth_token': auth_token.decode(),
                             'confirmed': user.confirmed
                         }
                         return make_response(jsonify(responseObject)), 200
                 else:
                     responseObject = {
                         'status': 'fail',
                         'message': 'Please confirm your email before logging in.'
                     }
                     return make_response(jsonify(responseObject)), 500
             else:
                 responseObject = {
                     'status': 'fail',
                     'message': 'Incorrect password. Please try again.'
                 }
                 return make_response(jsonify(responseObject)), 500
         else:
             responseObject = {
                 'status': 'fail',
                 'message': 'User does not exist. Please Register.'
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         print(e)
         responseObject = {
             'status': 'fail',
             'message': 'Try again'
         }
         return make_response(jsonify(responseObject)), 500
Exemplo n.º 26
0
    def post(self):
        response_msg = []
        email = request.json.get('email', None)
        password = request.json.get('password', None)

        if not email:
            response_msg.append('email must be non-empty')
        if not password:
            response_msg.append('password must be non-empty')

        if len(response_msg) > 0:
            responseObject = {
                'status': 'failed',
                'message': response_msg
            }
            return make_response(jsonify(responseObject)), 400
            
        try:
            user = User.query.filter_by(email=email).first()
            if user and bcrypt.check_password_hash(
                user.password, password
            ):
                auth_token = user.encode_auth_token(user.id, user.is_admin)
                # app.logger.debug(auth_token)
                if auth_token:
                    # app.logger.debug(user.first_name + ' successfully logged in')
                    responseObject = {
                        'status': 'success',
                        'message': 'Successfully logged in.',
                        'auth_token': auth_token.decode(),
                    }
                    return make_response(jsonify(responseObject)), 200
            else:
                responseObject = {
                    'status': 'fail',
                    'message': 'User does not exist.'
                }
                return make_response(jsonify(responseObject)), 404
        except Exception as e:
            app.logger.debug(e)
            responseObject = {
                'status': 'fail',
                'message': 'Try again'
            }
            return make_response(jsonify(responseObject)), 500
Exemplo n.º 27
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():

        user = User.query.filter_by(email=form.email.data).first()

        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            # Flask allows use of global variables
            # here I store the user email for further queries
            session["user"] = user.__dict__["email"]
            login_user(user)
            flash('You are logged in. Welcome!', 'success')
            return redirect(url_for('user.members'))
        else:
            flash('Invalid email and/or password.', 'danger')
            return render_template('user/login.html', form=form)
    return render_template('user/login.html', title='Please Login', form=form)
Exemplo n.º 28
0
    def post(self):
        try:
            check_request_body_keys(request.json, ['username', 'system_name', 'system_token', 'password'])
            post_data = request.json

            system = System.query.filter_by(name=post_data['system_name']).first()
            if system is None or system.token != post_data['system_token']:
                raise UnauthorizedError("Invalid system/token pair.")

            user = User.query.filter_by(username=post_data['username'], system_name=post_data['system_name']).first()
            if not user or not bcrypt.check_password_hash(user.password, post_data['password']):
                raise UnauthorizedError('Incorrect user credentials.')

            return make_response(jsonify(user.encode_auth_token())), 200
        except BadRequestError as e:
            return make_response(jsonify({'message': str(e)})), 400
        except UnauthorizedError as e:
            return make_response(jsonify({'message': str(e)})), 401
Exemplo n.º 29
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               request.form['password']):
            login_user(user)
            flash('You are logged in. Welcome!', 'success')
            return redirect(url_for('imagery.my_pictures'))
        else:
            flash('Invalid email and/or password.', 'danger')
            return render_template(
                'user/login.html',
                form=form,
                is_authenticated=current_user.is_authenticated)
    return render_template('user/login.html',
                           title='Please Login',
                           form=form,
                           is_authenticated=current_user.is_authenticated)
Exemplo n.º 30
0
    def post(self):
        # Needed to add this check due to change in request type.
        # When running unit tests, requests come in as a dict
        # However, in server mode, requests come in as ImmutableMultiDict
        if type(request.get_json()) is dict:
            post_data = request.get_json()
            user = User.query.filter_by(email=post_data.get('email')).first()
            email = post_data.get('email')
            password = post_data.get('password')

        else:
            # get the post data
            post_data = (request.get_json()
                         or request.form).to_dict(flat=False)
            # check if user already exists
            user = User.query.filter_by(
                email=post_data.get('email')[0]).first()
            email = post_data.get('email')[0],
            password = post_data.get('password')[0]

        try:
            # fetch the user data
            user = User.query.filter_by(email=email).first()
            if user and bcrypt.check_password_hash(user.password, password):
                auth_token = user.encode_auth_token(user.id)
                if auth_token:
                    responseObject = {
                        'status': 'success',
                        'message': 'Successfully logged in.',
                        'auth_token': auth_token.decode()
                    }
                    return make_response(jsonify(responseObject)), 200
            else:
                responseObject = {
                    'status': 'fail',
                    'message': 'User does not exist.'
                }
                return make_response(jsonify(responseObject)), 404
        except Exception as e:
            print(e)
            responseObject = {'status': 'fail', 'message': 'Try again'}
            return make_response(jsonify(responseObject)), 500
Exemplo n.º 31
0
 def post(self):
     post_data = request.get_json()
     if not post_data:
         return make_bad_request_response(APIError.NOT_JSON)
     data = post_data.get('data')
     if not data:
         return make_bad_request_response(APIError.WRONG_API)
     the_type = data.get('type')
     if not the_type or the_type != 'auth':
         return make_bad_request_response(APIError.WRONG_API)
     attributes = data.get('attributes')
     if not attributes:
         return make_bad_request_response(APIError.WRONG_API)
     email = attributes.get('email')
     password = attributes.get('password')
     if not email or not password:
         return make_bad_request_response(APIError.WRONG_API)
     try:
         user = User.query.filter_by(email=email).first()
         if not user:
             return make_not_found_response(APIError.USER_DOES_NOT_EXIST)
         if not bcrypt.check_password_hash(user.password, password):
             return make_forbidden_response(APIError.WRONG_PASSWORD)
         auth_token = User.encode_auth_token(user.id)
         if auth_token:
             token = Token(auth_token.decode(), user.id)
             db.session.add(token)
             db.session.commit()
             response_object = default_response_object()
             response_object['data'] = {
                 'type': 'auth',
                 'attributes': {
                     'token': auth_token.decode()
                 },
                 'links': {
                     'self': url_for('auth.login_api')
                 }
             }
             return make_success_response(response_object, 200)
     except Exception:
         return make_internal_server_error_response(
             APIError.UNKNOWN_EXCEPTION)
Exemplo n.º 32
0
    def post(self):
        # get the post data
        post_data = request.get_json()
        try:
            # fetch the user data
            if post_data.get('Email') == '':
                user = User.query.filter_by(
                    screen_name=post_data.get('ScreenName')).first()
            else:
                user = User.query.filter_by(
                    email=post_data.get('Email')).first()

            if user and bcrypt.check_password_hash(user.password,
                                                   post_data.get('Password')):
                auth_token, exp = user.encode_auth_token(user.id)
                if auth_token:
                    responseObject = {
                        'status': 'success',
                        'message': 'Successfully logged in.',
                        'auth_token': auth_token.decode()
                    }
                    return make_response(jsonify(responseObject)), 200

            elif user:
                responseObject = {
                    'status': 'fail',
                    'message': 'Incorrect email or password.'
                }
                return make_response(jsonify(responseObject)), 405

            else:
                responseObject = {
                    'status': 'fail',
                    'message': 'User does not exist.'
                }
                return make_response(jsonify(responseObject)), 404
        except Exception as e:
            print(e)
            responseObject = {'status': 'fail', 'message': 'Try again'}
            return make_response(jsonify(responseObject)), 500
 def check_password(self, value):
     """Check password."""
     return bcrypt.check_password_hash(self.password, value)
Exemplo n.º 34
0
    def post(self):
        try:
            # Get the post data
            post_data = request.get_json()

            if not post_data:  # Request isn't JSON type
                raise BadRequest

            # Check if data is incorrect
            if not post_data.get('email') or not isinstance(
                    post_data.get('email'), str):
                raise ValueError(
                    {
                        'status':
                        1,
                        'message':
                        'You have forgotten to specify email or its type is incorrect!'
                    }, 400)
            if not post_data.get('password') or not isinstance(
                    post_data.get('password'), str):
                raise ValueError(
                    {
                        'status':
                        1,
                        'message':
                        'You have forgotten to specify password or its type is incorrect!'
                    }, 400)
            if (post_data.get('body') != {}):
                raise ValueError(
                    {
                        'status': 1,
                        'message': 'You have forgotten to specify body!'
                    }, 400)
            if len(post_data) != 3:
                raise ValueError(
                    {
                        'status': 1,
                        'message': 'Too many arguments!'
                    }, 400)

            # Fetch the user data
            user = User.query.filter_by(email=post_data.get('email')).first()
            if user and bcrypt.check_password_hash(user.password,
                                                   post_data.get('password')):
                auth_token = user.encode_auth_token(user.id)
                if auth_token:
                    responseObject = {
                        'status': 0,
                        'message': 'Successfully logged in.',
                        'email': post_data.get('email'),
                        'auth_token': auth_token.decode()
                    }
                    return make_response(jsonify(responseObject)), 200
            elif user and not bcrypt.check_password_hash(  # If incorrect password
                    user.password, post_data.get('password')):
                return make_response(
                    jsonify({
                        'status': 1,
                        'message': 'Incorrect password.'
                    })), 404
            else:
                return make_response(
                    jsonify({
                        'status': 1,
                        'message': 'User does not exist.'
                    })), 404

        except ValueError as responseObject:
            return make_response(jsonify(
                responseObject.args[0])), responseObject.args[1]

        except BadRequest:
            return make_response(
                jsonify({
                    'status': 1,
                    'message': 'Request should be JSON type!'
                })), 400

        except Exception as e:
            return make_response(jsonify({
                'status': 1,
                'message': 'Try again'
            })), 500
Exemplo n.º 35
0
 def test_check_password(self):
     # Ensure given password is correct after unhashing.
     admin = User.query.filter_by(email='*****@*****.**').first()
     self.assertTrue(
         bcrypt.check_password_hash(admin.password, 'admin_user'))
     self.assertFalse(bcrypt.check_password_hash(admin.password, 'foobar'))
Exemplo n.º 36
0
 def test_check_password(self):
     # Ensure given password is correct after unhashing.
     user = User.query.filter_by(username='******').first()
     self.assertTrue(bcrypt.check_password_hash(user.password, 'admin_user'))
     self.assertFalse(bcrypt.check_password_hash(user.password, 'foobar'))