def addUserToDB(body): """ Add users to the Database, by providing the body {email, password} and Register method {Def "Default", Non-Def "Registered manually" """ registered_users = Users.query.all() registered_users = [u.display() for u in registered_users] registered_emails = [u['email'].lower() for u in registered_users] # Check if the email is not already in the Database, and # if not, adding the user credentials to the Database. if body['email'].lower() not in registered_emails: hashed_password = bcrypt.generate_password_hash( body['password']).decode('utf-8') new_user = Users( email=body['email'], password=hashed_password, type=body['type'], ) new_user.insert() return True return Exception("User With Same Email is Already Registered!")
def createsuperuser(name): """Create a superuser admin""" try: app = create_app() app.app_context().push() with app.app_context(): user = User.query.filter(User.username == name).first() if user: raise Exception(f'The {user} already exists.') else: password_crypt = bcrypt.generate_password_hash( 'admin', 10).decode('utf-8') user = User(name, password_crypt, True, False, False, False) session.add(user) session.commit() serializer = UserSchema().dump(user) response = dict() response['user'] = serializer response[ 'password'] = '******' click.echo(Created(f'{response}')) except Exception as e: click.echo( Aborted(f'Create superuser produce the followings errors: {e}.'))
def update_users(user_id): user = Users.query.get(user_id) # Check if user exists if not user: abort(404, f'No User Found with ID #{user_id}') req = request.get_json() # Check if request is valid if not req: abort(400, 'Please Provide a New Password!') updated_password = req.get('password') try: if updated_password: hashed_password = bcrypt.generate_password_hash(updated_password) user.password = hashed_password user.update() except Exception as e: print(e) abort(500, e) return jsonify({ 'user': f'User #{user.email} has been updated!', 'success': True })
def create_instance(self): user = User(**self.data) password_crypt = bcrypt.generate_password_hash( user.password, 10).decode('utf-8') user.password = password_crypt return user
def add_user_to_db(email, password): registered_users = Users.query.all() registered_users = [u.display() for u in registered_users] registered_emails = [u['email'] for u in registered_users] # Check to see if the email is not already in the DataBase, and # if not adding both email and hashed password to the DataBase if email not in registered_emails: hashed_password = bcrypt.generate_password_hash(password).decode( 'utf-8') new_user = Users(email=email, password=hashed_password) new_user.insert()
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 register(): form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() flash(f'Account created for {form.username.data}!', 'success') return redirect(url_for('index')) return render_template('register.html', title='Register', form=form)
def register(): if (current_user.is_authenticated): return redirect(url_for('home')) form = RegistrationForm() if form.validate_on_submit(): hashed_pwd = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hashed_pwd) db.session.add(user) db.session.commit() flash("Your Account has been created successfully!", 'success') return redirect(url_for('login')) return render_template("register.html", title='Register', form=form)
def edit_user(current_user): data = request.get_json() if data: if "fname" in data and len(data["fname"]) > 0: current_user.fname = data['fname'] if "mname" in data and len(data["mname"]) > 0: current_user.mname = data['mname'] if "lname" in data and len(data["lname"]) > 0: current_user.lname = data['lname'] if "dob" in data: try: current_user.dob = datetime.strptime(data['dob'], "%d/%m/%Y").date() except: return make_response("invalid date of birth format try 'DD/MM/YYYY!", 401, {'nothing': 'nothing'}) if "email" in data: if data['email'] != current_user.email: if Users.query.filter_by(email=current_user.email).first(): return make_response("email address already present.!", 401, {'nothing': 'nothing'}) current_user.email = data['email'] current_user.email_conformation = 0 if "phone" in data: current_user.phone = data['phone'] if "password" in data: current_user.password = bcrypt.generate_password_hash(data['password']).decode('utf-8') if "sex_id" in data: current_user.sex_id = data['sex_id'] if "picture" in data: current_user.picture = data['picture'] db.session.commit() return jsonify({"message": "user edited"})
def addUserToDB(body): registered_users = Users.query.all() registered_users = [u.display() for u in registered_users] registered_usernames = [u['username'].lower() for u in registered_users] registered_emails = [u['email'].lower() for u in registered_users] # Check if the username & email are not already registered in the Database, and # if not, adding the user Credentials to the Database. if body['email'].lower() not in registered_emails and body['username'].lower() not in registered_usernames: hashed_passw = bcrypt.generate_password_hash(body['password']).decode('utf-8') new_user = Users( usename=body['username'], email=body['email'], password=hashed_passw ) new_user.insert() return True raise Exception("User With Same Credentials is Already Registered!")
def password(self, password): self.password_hash = bcrypt.generate_password_hash( password).decode('utf8')
def add_user(): data = request.get_json() if data: if "fname" in data and len(data["fname"]) > 0: fname = data['fname'] else: return make_response("first name not found.!", 401, {'nothing': 'nothing'}) if "mname" in data: mname = data['mname'] else: mname = None if "lname" in data and len(data["lname"]) > 0: lname = data['lname'] else: return make_response("last name not found.!", 401, {'nothing': 'nothing'}) if "picture" in data: picture = data['picture'] else: picture = None if "dob" in data: dob = datetime.strptime(data['dob'], "%d/%m/%Y").date() else: dob = None if "email" in data: email = data['email'] if Users.query.filter_by(email=email).first(): return make_response("email address already present.!", 401, {'nothing': 'nothing'}) else: return make_response("email not found.!", 401, {'nothing': 'nothing'}) if "email_conformation" in data: email_conformation = data['email_conformation'] else: email_conformation = 0 if "phone" in data: phone = data['phone'] else: phone = None if ("external_auth" in data) and (data['external_auth'] == "1"): password = "******" else: if "password" in data: password = bcrypt.generate_password_hash(data['password']).decode('utf-8') else: return make_response("password not found.!", 401, {'nothing': 'nothing'}) if "sex_id" in data: sex_id = data['sex_id'] else: sex_id = 4 send_conformation_mail_before_login(email) new_user = Users(email=email, fname=fname, mname=mname, lname=lname, dob=dob, password=password, phone=phone, sex=sex_id, email_conformation=email_conformation, picture=picture) db.session.add(new_user) db.session.commit() return jsonify({"message": "Account created!"}) return make_response("No data found!.", 401, {'nothing': 'nothing'})
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)
def sign_up(self): self.username = request.args.get('username') self.password = bcrypt.generate_password_hash(request.args.get('password')).decode('utf-8')
def set_password(self, password): self.pw_hash = bcrypt.generate_password_hash(password)