def login(): if current_user.is_authenticated: print('Logged In') if current_user.user_type == 'Lawyer': return jsonify({'login_status': '1', 'user_type': user.user_type, 'nameofuser': user.name, 'due_amt': current_user.due_amount}) return jsonify({'login_status': '1', 'user_type': user.user_type, 'nameofuser': user.name}) if(flask.request.method == 'POST'): print('POST method') print(flask.request.values) print(flask.request.get_json()) req = flask.request.get_json() username_data = req.get('username') print(username_data) password = req.get('password') print(password) user = User.query.filter_by(username=username_data).first() print(user) # print(user.password) if user and bcrypt.check_password_hash(user.password, password): login_user(user) next_page = request.args.get('next') print('Login Successful') print('Current User ', current_user) if current_user.user_type == 'Lawyer': return jsonify({'login_status': '1', 'user_type': user.user_type, 'nameofuser': user.name, 'due_amt': current_user.due_amount}) return jsonify({'login_status': '1', 'user_type': user.user_type, 'nameofuser': user.name}) else: print('Login Unsuccessful. Please check username and password') # login_user(user, remember=form.remember.data) return jsonify({'login_status': "0"})
def post(): post_data = request.form 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: response = { 'status': 'success', 'message': 'Successfully logged in.', 'auth_token': auth_token.decode(), 'user_id': str(user.id) } return json.dumps(response), 200 else: response = { 'status': 'fail', 'message': 'User does not exist.' } return json.dumps(response), 404 except Exception as e: print(e) response = {'status': 'fail', 'message': 'Try again'} # return json.dumps(response), 500 return jsonify(status='fail', message='Try again'), 500
def login(): auth = request.authorization if not auth or not auth.username or not auth.password: return make_response( 'Could not verify', 401, {'WWW.Authenticate': 'Basic realm="Login required!"'}) user = User.query.filter_by(name=auth.username).first() if not user: return make_response( 'Could not verify', 401, {'WWW.Authenticate': 'Basic realm="Login required!"'}) if bcrypt.check_password_hash(user.password, auth.password): token = jwt.encode( { 'public_id': user.public_id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) }, current_app.config['SECRET_KEY']) return jsonify({'token': token.decode('UTF-8')}) return make_response('Could not verify', 401, {'WWW.Authenticate': 'Basic realm="Login required!"'})
def login(): auth = request.authorization if(auth and auth.username and auth.password): user = User.query.filter_by(username = auth.username).first() if(user and bcrypt.check_password_hash(user.password, auth.password)): access_token = generate_access_token(user.public_id) refresh_token = generate_refresh_token(user.public_id) if(not refresh_token): return { 'message' : 'There was an issue loggin in!' }, 401 res = make_response({ 'message' : 'User successfully logged in!' }) res.set_cookie('x-access-token', value = access_token, httponly = True, samesite = \ None, expires = datetime.utcnow() + timedelta(minutes = 30)) res.set_cookie('x-refresh-token', value = refresh_token, httponly = True, samesite = \ None, expires = datetime.utcnow() + timedelta(weeks = 2), path = '/user/login/') user.is_logged_in = True db.session.commit() return res, 200 return { 'message' : 'Invalid username or password!' }, 401
def get(self): if not request.args.get('email'): # return the list of users users = User.query.all() users = users_schema.dump(users).data return {'status': 'success', 'data': users}, 200 else: json_data = {} json_data['email'] = request.args.get('email') json_data['password'] = request.args.get('password') users = User.query.filter_by(email=json_data['email']).first() if users: if users and bcrypt.check_password_hash( users.password, json_data['password']): # login user login_user(users) users = user_schema.dump(users).data return {'status': 'success', 'data': users}, 200 else: return { 'status': 'error', 'message': "Email address or password is incorrect." }, 200 else: return { 'status': 'error', 'message': "The user with this email address does not exist." }, 200
def post(self, current_user): # get post data data = request.get_json(force=True) try: # fetching user data user = User.query.filter_by(email=data['email']).first() if user: if bcrypt.check_password_hash(user.password, data['old_password']): user.password = user.change_password( data['old_password'], data['new_password']) user.update() responseObject = { 'status': 'success', 'message': 'Password has been reset' } return make_response(jsonify(responseObject)), 200 else: responseObject = { 'status': 'fail', 'message': 'Incorrect password, try again', } return make_response(jsonify(responseObject)), 200 else: responseObject = { 'status': 'fail', 'message': 'Wrong email provided, please try again!', } return make_response(jsonify(responseObject)), 200 except Exception as e: responseObject = { 'status': 'fail', 'message': 'Try again', } return make_response(jsonify(responseObject)), 500
def post(self): """Route for application login. Sends back a JSON with an access and a refresh token""" validators = { 'username': valid.validate_string, 'password': valid.validate_string } data = valid.validate(valid.read_form_data(request), validators) if not data: return ANSWERS[400], 400 username = data['username'] password = data['password'] user = User.query.filter_by(username=username).first() if not (user and bcrypt.check_password_hash(user.password, password)): return ANSWERS[403], 403 # Use create_access_token() and create_refresh_token() # to create our access and refresh tokens ret = { 'access_token': create_access_token(identity=username, fresh=True), 'refresh_token': create_refresh_token(identity=username) } return ret, 200
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
def login(): """POST users/login Desc: Logs in a user Checks if any fields are blank Checks if an account exists at all Checks if an account exists and the password was incorrect Returns: 200: authentication token 401: password was incorrect, unauthorized access 404: no account was found or field was empty """ req = request.get_json() is_valid, errors = valid_login(req) if not is_valid: return errors, 404 user = User.objects(email=req['email']).first() if not user: return { 'email': 'No account with this email exists.', 'password': '' }, 404 if not bcrypt.check_password_hash(user.password, req['password']): return {'email': '', 'password': '******'}, 401 access_token = create_access_token(identity=user) return {'token': access_token}, 200
def login(): # Get authentication credentials auth = request.authorization # Check for authentication data # the username in this case is the user's email if not auth or not auth.username or not auth.password: return make_response( 'Could not verify', 401, {'WWW-Authenticate': 'Basic releam="Login required!"'}) # Get user data from database user = User.query.filter_by(email=auth.username).first() # Check for empty result if not user: return make_response( 'Could not verify', 401, {'WWW-Authenticate': 'Basic releam="Login required!"'}) # Check the user's password if bcrypt.check_password_hash(user.password, auth.password): return jsonify({ 'message': 'Succesfully login!', 'public_id': str(user.public_id) }) return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required!"'})
def login(): auth = request.authorization if(auth and auth.username and auth.password): user = User.query.filter_by(username = auth.username).first() if(user and bcrypt.check_password_hash(user.password, auth.password)): access_token = generate_access_token(user.public_id) return { 'token' : access_token }, 200 return { 'message' : 'Invalid username or password' }, 401
def verify_password(self, password): """ Verifies a user password, with a supplied password Parameters ---------- password: string """ return bcrypt.check_password_hash(self.password, password)
def test_create_user(init_db): """Test creation of a new user instance in the database.""" User.create_user(username='******', password='******') user = User.query.filter_by(username='******').first() assert user is not None assert user.id == 2 assert user.username == 'test' assert bcrypt.check_password_hash(user.password, 'test')
def wrapper(*args, **kwargs): if not getattr(func, 'authenticated', True): return func(*args, **kwargs) if request.authorization: if bcrypt.check_password_hash(ALLOWED_CLIENTS[request.authorization['username']], request.authorization['password']): return func(*args, **kwargs) abort(401, message="Authorization is required")
def post(self): args = auth_parser.parse_args() id_no = args['username'] password = args['password'] individual = Individual.objects(id_no=id_no).first() if individual: if bcrypt.check_password_hash(individual.password, password): return {'Success': 'Individual has been successfully authenticated.'} return {'Error': 'Invalid username or password.'}, 401
def post(self): args = auth_parser.parse_args() name = args['username'] password = args['password'] group = Group.objects(name__iexact=name).first() if group: if bcrypt.check_password_hash(group.password, password): return {'Success': 'Group has been successfully authenticated.'} return {'Error': 'Invalid username or password.'}, 401
def post(self): args = auth_parser.parse_args() username = args['username'] password = args['password'] user = User.objects(username__iexact=username).first() if user: if bcrypt.check_password_hash(user.password, password): return {'Success': 'User authenticated.'} return {'Error': 'Invalid username or password.'}, 401
def validate_user(email, password): # get the user user = UserModel.query.filter_by(email=email).first() if not user: return False, {'message': f"no account associated with {email}"}, 404 # check if passwords match if not bcrypt.check_password_hash(user.password, password): return False, {'message': f"incorrect password for {email}"}, 401 return True, user, 201
def login(): auth = request.authorization if not auth or not auth.username or not auth.password: return make_response("Could not verify", 401) user = User.query.filter_by(username=auth.username).first() if user and bcrypt.check_password_hash(user.password, auth.password): token = jwt.encode({"username" : user.username, "exp" : datetime.utcnow()+timedelta(minutes=120)}, key=app.config['SECRET_KEY']) user.last_seen = datetime.utcnow() db.session.commit() return jsonify({"token" : token.decode("UTF-8")}) return make_response("Could not verify", 401)
def login(): if current_user.is_authenticated: return redirect(url_for('set_entry')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user, remember=form.remember.data) next_page = get_redirect_target() return redirect(next_page or url_for('login')) else: flash('Login Unsuccessful. Please check email and password', 'danger') return render_template('login.html', title='Login', form=form)
def post(self): # get post data if not request.get_json(force=True): abort(400) data = request.get_json(force=True) if data: login_key_missing_in_body(data) if key_is_not_string(data): response_object = { 'error': 'Bad request, body field must be of type string' } return jsonify(response_object), 400 try: # fetching user data user = User.query.filter_by(email=data['email']).first() if user: if bcrypt.check_password_hash(user.password, data['password']): auth_token = user.encode_auth_token( user.id, user.public_id, user.email, user.first_name, user.last_name) if auth_token: responseObject = { 'status': 'success', 'message': 'Successfully logged in', 'auth_token': auth_token.decode('UTF-8') } return make_response(jsonify(responseObject)), 200 else: responseObject = { 'status': 'fail', 'message': 'Try again', } return make_response(jsonify(responseObject)), 500 else: responseObject = { 'status': 'fail', 'message': 'Incorrect password, try again', } return make_response(jsonify(responseObject)), 401 else: responseObject = { 'status': 'fail', 'message': 'User does not exist, please register', } return make_response(jsonify(responseObject)), 403 except Exception as e: responseObject = { 'status': 'fail', 'message': 'Try again', } return make_response(jsonify(responseObject)), 500
def login(): form = LoginForm() if form.validate_on_submit(): user = get_user(form.name.data) if user: if bcrypt.check_password_hash(user.password, form.password.data): user.authenticated = True db.session.add(user) db.session.commit() login_user(user, remember=True) return redirect("/") else: flash("Неверное имя пользователя или пароль") return render_template("login_user.html", form=form)
def authenticate(identifier, password, method='email'): if method == 'email': user = User.query.filter_by(email=identifier).first() elif method == 'username': user = User.query.filter_by(username=identifier).first() else: return "Internal Error. Invalid identification method" if user: if bcrypt.check_password_hash(user.password, password): return user else: return "Invalid credentials" else: return "User '{}' does not exist".format(identifier)
def login(): form = LoginForm() if current_user.is_authenticated: return redirect(url_for("main.home")) if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if (user and bcrypt.check_password_hash(user.password, form.password.data)): login_user(user) flash("Logged into your account!", 'success') next = request.args.get('next') return redirect(next or url_for("main.home")) flash("Login unsuccessful!", 'error') return redirect(url_for("user.login")) return render_template("login.html", title="Login", form=form)
def login(): """Login POST Data: email : user email password : new password of the user Returns: 201 -- success 401 -- fail (either email or password is incorrect) 402 -- fail (user not confirmed) 403 -- forbidden (user banned) """ auth = request.get_json(silent=True) if not auth or not auth.get("email") or not auth.get("password"): return make_response("Could not verify", 401) user = User.query.filter_by(email=auth.get("email")).first() if not user: return make_response("Could not verify", 401) if bcrypt.check_password_hash(user.password, auth.get("password")): if not user.confirmed: return make_response( jsonify({ "status": "fail", "message": "Confirm your email!!" }), 402) if user.BANNED: return make_response({ "status": "fail", "message": "USER BANNED!!" }, 403) token = jwt.encode( { "public_id": user.public_id, "name": user.first_name, "email": user.email, "exp": datetime.datetime.utcnow() + datetime.timedelta(days=1), }, app.config["SECRET_KEY"], ) return make_response({"token": token.decode("UTF-8")}, 201) return make_response("Could not verify", 401)
def user_login(): email = request.json.get('email') password = request.json.get('password') user = Users.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 = { 'email': user.email, 'status': 'success', 'message': 'Successfully logged in.', 'auth_token': auth_token.decode() } return jsonify(responseObject), 200 else: responseObject = {'status': 'error', 'message': 'Invalid login.'} return jsonify(responseObject), 404
def post(self): print(request.json) if request.json is None: return jsonify(message='Missing parameters') loginData = { 'username': request.json['username'], 'password': request.json['password'] } if loginData['username'] is None or loginData['password'] is None: return jsonify(message='Missing parameters') user = User.objects(username=loginData['username']).first() if user and bcrypt.check_password_hash(user.password, loginData['password']): login_user(user) return jsonify(access_token=create_access_token( identity=user.username, expires_delta=timedelta(minutes=30)), message='Succesfull log in!') return jsonify(message='Bad username or password!')
def login(): post_data = request.get_json() if (not post_data or "email" not in post_data or "password" not in post_data): return jsonify({"message": "Invalid payload", "status": "fail"}), 400 email = post_data.get("email") password = post_data.get("password") try: user = User.query.filter_by(email=email).first() if user: if bcrypt.check_password_hash(user.password_hash, password): auth_token = user.encode_auth_token() return ( jsonify({ "status": "success", "message": "Successfully logged in", "auth_token": auth_token.decode(), }), 200, ) else: return ( jsonify({ "status": "fail", "message": "Check password" }), 400, ) else: return ( jsonify({ "status": "fail", "message": "User doesn't exist" }), 404, ) except Exception: return jsonify({"status": "fail", "message": "Try again"}), 500
def get_token(public_id): # Get authentication credentials auth = request.authorization # Check for authentication data # the username in this case is the user's email if not auth or not auth.username or not auth.password: return make_response( 'Could not verify', 401, {'WWW-Authenticate': 'Basic releam="Login required!"'}) # Get the user's details from database user = User.query.filter_by(email=auth.username).first() # Check for empty result if not user: return make_response( 'Could not verify', 401, {'WWW-Authenticate': 'Basic releam="Login required!"'}) # Check to see if the public id of the user match with the one passed through the URL if user.public_id != public_id: return jsonify({'message': 'Invalid public id!'}) # Check the user's password if bcrypt.check_password_hash(user.password, auth.password): # Create token by using the user's public id address and the app secret key token = jwt.encode({'public_id': user.public_id}, app.config['SECRET KEY']) return jsonify({ 'message': 'Succesfully authenticate!', 'token': str(token.decode('UTF-8')), 'name': str(user.first_name) + ' ' + str(user.last_name[0]) + '.' }) return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required!"'})
def login(): print("in login") data = request.get_json() # Authorization information missing if not data or not data['email'] or not data['password']: return {'message': 'Missing login information'}, 400 user = User.query.filter_by(email=data['email'].lower()).first() # Email already in DB if not user: return {'message': 'Can not find existing user with this email'}, 400 # Incorrect Password if bcrypt.check_password_hash(user.password, data['password']): token = jwt.encode( { 'public_id': user.public_id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=300) }, app.config['SECRET_KEY'], algorithm='HS256') return {'token': token}, 200 return {'message': 'Password incorrect'}, 400
def login(): # If there is a current_user authenticated, returns "already-login" status if current_user.is_authenticated: return json.dumps({"status": "already-login"}) if request.method == 'POST': # Get data back from posted form form_email = request.form.get('email') form_password = request.form.get('password') form_remember = request.form.get('remember') # Look for user in database user = User.query.filter_by(email=form_email.lower()).first() # if user exists, and password match with encrypted password in database if user and bcrypt.check_password_hash(user.password, form_password): # Log user and remember user (or not) login_user(user, remember=form_remember) # returns success status return json.dumps({"status": "login-success"}) # if user does not exist or password mismatch, returns failed status else: return json.dumps({"status": "login-failed"}) # if endpoint requested through get method, returns error return json.dumps({"status": "error-get-request"})
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')): auth_token = user.encode_auth_token(user.id) if auth_token: return { 'status': 'success', 'message': 'Successfully logged in.', 'auth_token': auth_token.decode() } else: return { 'status': 'fail', 'message': 'Login credentials is incorrect.' } except Exception as e: return {'status': 'fail', 'message': 'Try again'}
def post(self): """Route to get a fresh access token by entering credentials again Returns a json with a fresh access token""" validators = { 'username': valid.validate_string, 'password': valid.validate_string } data = valid.validate(valid.read_form_data(request), validators) if not data: return ANSWERS[400], 400 username = data['username'] password = data['password'] user = User.query.filter_by(username=username).first() if not (user and bcrypt.check_password_hash(user.password, password)): return ANSWERS[403], 403 new_token = create_access_token(identity=username, fresh=True) ret = {'access_token': new_token} return ret, 200
def verify_password(self, password): pw_hash = self.password_hash return bcrypt.check_password_hash(pw_hash, password)