def validate_current_user(email, passw): user = Users.query.filter(Users.email.ilike(email)).first() # Check if entered password matches user's hashed password if user and bcrypt.check_password_hash(user.password, passw): # Logging the user as current user login_user(user) else: raise Exception("Wrong Credentials, Try Again!")
def login_and_get_token(): data = request.get_json() if data and "email" in data and "password" in data: email = data['email'] password = data['password'] user = Users.query.filter_by(email=email).first() if user and bcrypt.check_password_hash(user.password, password): print(app.config["SECRET_KEY"], type(app.config["SECRET_KEY"])) return jsonify({"token": jwt.encode({"id": user.id}, app.config["SECRET_KEY"]).decode('utf-8')}) return make_response("invalid email and password.", 401, {'nothing': 'nothing'}) return jsonify({'message': 'invalid body.!'})
def validate_current_user(email, password, remember): try: user_ = Users.query.filter_by(email=email).first() # Check if entered password matches user's hashed password if user_ and bcrypt.check_password_hash(user_.password, password): # Logging the user as current user login_user(user_, remember=remember) except Exception as e: print('Validation Error') print(e)
def validate_current_user(cred, passw): # Check whether the user logged-in with username or email user = checkUsernameOrEmail(cred) # Check if entered password matches user's hashed password if user and bcrypt.check_password_hash(user.password, passw): # Logging the user as current user login_user(user) else: raise Exception("Wrong Credentials, Try Again!")
def login(self): try: if not self.data: raise ClientException(user_err_msg="No input data provided") auth = AuthenticationSchema().dump(self.data) user = User.query.filter_by(username=auth['username']).one() check = bcrypt.check_password_hash(user.password, auth['password']) if not check: raise NotAuthorizedError( user_err_msg='Bad username or password') identity = dict() roles = { 'is_seller': user.is_seller, 'is_costumer': user.is_costumer, 'is_superuser': user.is_superuser, 'is_manager': user.is_manager } identity['username'] = user.username identity['roles'] = roles # Create our JWT access_token = create_access_token(identity=identity, expires_delta=self._EXPIRES) refresh_token = create_refresh_token( identity=identity, expires_delta=self._EXPIRES_REFRESH) # Store the tokens in our store with a status of not currently revoked. add_token_to_database(access_token, os.environ.get('JWT_IDENTITY_CLAIM')) # TODO: USE OR NOT USE ? METHOD FOR TOKEN EXPIRED ? # add_token_to_database( # refresh_token, os.environ.get('JWT_IDENTITY_CLAIM')) ret = { 'access_token': access_token, # 'refresh_token': refresh_token } return jsonify(ret), HTTPStatus.CREATED except ValidationError as e: raise NotFoundError(user_err_msg=e.messages) except NoResultFound as e: raise NotAuthorizedError(user_err_msg='Bad username or password') except Exception as e: raise e
def login(): form = LoginForm() if form.validate_on_submit(): # Check if there are any emails with the same email the we've submitted user = User.query.filter_by(username=form.username.data).first() # If user exists and password is correct if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user, remember=form.remember.data) next_page = request.args.get('next') flash(f'Hi there, {form.username.data}!', 'success') return redirect(next_page) if next_page else redirect( url_for('index')) else: flash("Incorrect username or password", 'danger') return render_template('login.html', title='Login', form=form)
def login(): if (current_user.is_authenticated): return redirect(url_for('home')) 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, form.remember.data) next_page = request.args.get('next') if next_page: return redirect(next_page) else: return redirect(url_for('home')) else: flash("login unsuccessful! please check email and password", 'danger') return render_template("login.html", title='Login', form=form)
def settings(): form_password = Reset_password() if form_password.validate_on_submit(): cpassword = request.form.get('password') if cpassword: if bcrypt.check_password_hash(current_user.password, cpassword): current_user.password = bcrypt.generate_password_hash( request.form.get('cnpassword')).decode('utf-8') db.session.commit() flash("Password Updated Successful!.", "success") else: flash("Current Password Does Not Match!", "danger") elif current_user.password == "External Website Verified.": current_user.password = bcrypt.generate_password_hash( request.form.get('cnpassword')).decode('utf-8') db.session.commit() flash("Password Updated Successful!.", "success") else: flash("Please enter your current password.", "info") return render_template("settings.html", form_password=form_password, title="Settings")
def check_password(self, password): return bcrypt.check_password_hash(self.password_hash, password)
def index(page=1): try: registerform = RegistrationForm() if registerform.validate_on_submit(): checkUsername = registerform.username.data checkEmail = registerform.email.data hashed_password = bcrypt.generate_password_hash( registerform.password.data).decode('utf-8') user = User(username=registerform.username.data, email=registerform.email.data, password=hashed_password) usernameExists = db.session.query( db.session.query(User).filter_by( username=checkUsername).exists()).scalar() emailExists = db.session.query( db.session.query(User).filter_by( email=checkEmail).exists()).scalar() if usernameExists or emailExists: message = 'That username or email is already taken' flash(str(message), 'loginError') return redirect("/") return render_template('index.html', loginError=loginError) else: db.session.add(user) db.session.commit() message = 'Registration succesfull!' flash(str(message), 'loginError') return redirect("/") return render_template('index.html', loginError=loginError) return redirect("/") return render_template('index.html', loginError=loginError) loginform = LoginForm() if loginform.validate_on_submit(): user = User.query.filter_by(email=loginform.email.data).first() if user and bcrypt.check_password_hash(user.password, loginform.password.data): login_user(user, remember=loginform.remember.data) #next_page = request.args.get('next') #return redirect(next_page) if next_page else redirect(url_for('index')) return redirect(url_for('/')) else: message = 'Invalid login, please check your login values and try again' flash(str(message), 'loginError') return redirect("/") return render_template('index.html', loginError=loginError) if current_user.is_authenticated: userfolder = current_user.username converteduserfiles = [] userfiles = [] path = f'files/{userfolder}/' if (os.path.exists(f'files/{userfolder}/converted')): pathtoconverted = f'files/{userfolder}/converted' else: if not (os.path.exists(f'files/{userfolder}')): os.mkdir(f'files/{userfolder}') os.mkdir(f'files/{userfolder}/converted') pathtoconverted = f'files/{userfolder}/converted' for filename in os.listdir(path): if os.path.isfile and filename != 'converted': userfiles.append(filename) for filename in os.listdir(pathtoconverted): if os.path.isfile: converteduserfiles.append(filename) else: filename = '' path = '' userfiles = '', '' converteduserfiles = '' pathtoconverted = '' session['filename'] = filename session['path'] = path session['userfiles[]'] = userfiles session['converteduserfiles[]'] = converteduserfiles session['pathtoconverted'] = pathtoconverted session['filename'] = filename session['path'] = path session['userfiles[]'] = userfiles session['converteduserfiles[]'] = converteduserfiles session['pathtoconverted'] = pathtoconverted postform = PostForm() if postform.validate_on_submit(): post = Post(title=postform.title.data, content=postform.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') return redirect(url_for('index')) RESULTS_PER_PAGE = 5 #posts = Post.query.all() #models.Post.query.paginate(page, per_page, error_out=False) #posts = Post.query.order_by(Post.id.title()).paginate(page,per_page,error_out=False) posts = models.Post.query.paginate(page, RESULTS_PER_PAGE, False) num = int(ceil(float(posts.total) / RESULTS_PER_PAGE)) + 1 environment = jinja2.Environment(os) environment.filters['os'] = os #{% for post in posts|sort(attribute='date_posted', reverse=true) %} return render_template( 'index.html', title='Account', loginform=loginform, registerform=registerform, postform=postform, posts=posts, number_of_pages=num, userfiles=session['userfiles[]'], path=session['path'], filename=session['filename'], pathtoconverted=session['pathtoconverted'], converteduserfiles=session['converteduserfiles[]'], os=os) #All exception catchers, most of these will never happen but they're there just to be sure. except KeyError as a: flash(str(a), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except NameError as b: flash(str(b), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except ValueError as c: flash(str(c), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except TypeError as f: flash(str(f), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except: #message = 'You broke my webapp somehow, if this is a recurring error then please contact the developer' #flash(str(message), 'error') return redirect("/") #return render_template('index.html', error=error) return render_template('index.html') session.pop('_flashes', None)