def register(): ''' Registration controller. Checks and validates registration form. When accepting registration, the user is redirected from JS frontend when 'Success' is returned.''' form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): # Code to support if invite registration mode is enabled. if config.REGISTRATION_LEVEL == 'invite': c = InviteCode() # Check if invite code is valid if c.is_valid(form.invite_code.data) == False: error = {"code": ["Invitation code invalid"]} return jsonify(errors=error) else: pass # Check or create if user does not exist #user, created = User.objects.get_or_create(username__exact=form.username.data) try: user = User.objects.get(username__iexact=form.username.data) created = False except: user = User(username=form.username.data) created = True # if created == True, then create a password, save and login session if created: # Set password and save user.password = generate_password_hash(form.password.data) user.save() # If invite-mode on, use invite code if config.REGISTRATION_LEVEL == 'invite': c = InviteCode() # Use code c.use_code(form.invite_code.data, form.username.data) # Log in user and flash message session['username'] = form.username.data flash('Thanks for registering!') return 'Success' else: error = {"duplicate": ["Please choose another username"]} return jsonify(errors=error) # Go home if called via GET request directly. elif request.method == 'GET': return redirect(url_for('home')) # Return POST errors in json return jsonify(errors=form.errors)
def create_user(username, email, password): """Takes a bcrypt object for password encoding.""" password_hash = generate_password_hash(password, rounds=10) try: new_user = User(username=username, email=email, password=password_hash) db.session.add(new_user) db.session.commit() except Exception as e: app.logger.debug('%s - %s' %(type(e), str(e)))
def test_check_hash_unicode(self): password = u"\u2603" x = generate_password_hash(password) # check a correct password a = check_password_hash(x, password) self.assertTrue(a) # check a wrong password b = check_password_hash(x, "test") self.assertFalse(b)
def create_user(username, email, password): """Takes a bcrypt object for password encoding.""" password_hash = generate_password_hash(password, rounds=10) try: new_user = User(username=username, email=email, password=password_hash) db.session.add(new_user) db.session.commit() except Exception as e: app.logger.debug('%s - %s' % (type(e), str(e)))
def test_check_hash_unicode(self): password = u'\u2603' x = generate_password_hash(password) # check a correct password a = check_password_hash(x, password) self.assertTrue(a) # check a wrong password b = check_password_hash(x, 'test') self.assertFalse(b)
def register_user(username, password): """Register new user. Returns user database row. If fails, returns None. """ try: user = g.db.users.insert(username=username, password=generate_password_hash(password)) g.db.commit() return user except Exception as ex: return None
def add_user(): #render registeration form form = RegisterationForm(request.form) #if posted and email is non empty and password is non empty if request.method == 'POST' and form.validate(): #need to hash password password_hash = generate_password_hash(form.password.data) new_user = User(form.email.data,password_hash) db.session.add(new_user) db.session.commit() #bug fixed: if VCS_Password is not empty then hash otherwise not if not (form.VCS_Password.data == ''): #need to hash VCS password VCS_Password_hash = generate_password_hash(form.VCS_Password.data) new_user_data = UserData(form.Name.data, form.Nickname.data, \ form.VCS_Username.data,VCS_Password_hash) else: new_user_data= UserData(form.Name.data, form.Nickname.data, \ form.VCS_Username.data,form.VCS_Password.data) db.session.add(new_user_data) db.session.commit() #simple check to see if the user has been registered access_user = User.query.filter_by(email = form.email.data).first() if not access_user is None: flash('The User details have been registered. ') #func.send_activation(form.email.data) #status of registeration registeration_status="Sent email to user for activation" return redirect(url_for('login'), registered=registeration_status) else: flash("The User doesn't seem to be in our Database yet, please try again") return render_template('add_user.html',form=form)
def __init__(self, username, email, password, first_name=None,\ last_name=None, gender=None, date_of_birth=None, summary=None): self.uuid = str(uuid.uuid1()) self.username = username self.email = email.lower() self.password_hash = generate_password_hash(password) self.first_name = first_name self.last_name = last_name self.gender = gender self.date_of_birth = date_of_birth self.summary = summary
def register(cls, email, password): if session.query(cls.query.filter_by(email=email).exists()).scalar(): return None pwdhash = generate_password_hash(password) u = cls(email=email, pwdhash=pwdhash) session.add(u) session.commit() return u
def test_check_hash(self): pw_hash = self.bcrypt.generate_password_hash('secret') # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret')) # check an incorrect password self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2')) # check unicode pw_hash = self.bcrypt.generate_password_hash(u'\u2603') self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603')) # check helpers pw_hash = generate_password_hash('hunter2') self.assertTrue(check_password_hash(pw_hash, 'hunter2'))
def user(): user = request.args["id"] user = User.query.filter_by(username=user).first_or_404() form = EditUser(request.form, obj=user) if request.method == "POST" and form.validate(): form.populate_obj(user) user.pw_hash = generate_password_hash(form.newpass.data) user.email = form.email.data db.session.add(user) db.session.commit() flash("Your account was successfully updated") return render_template("user.html", user=user, form=form)
def register(): if flask.request.method == 'GET': if 'logged_in' in flask.session and flask.session['logged_in']: return flask.render_template('register.html', alreadyRegistered=True) else: return flask.render_template('register.html') if flask.request.method == 'POST': # credential check? if not flask.request.form['userName'] \ or not flask.request.form['emailAddress'] \ or not flask.request.form['password'] \ or not flask.request.form['retypePassword'] \ or not flask.request.form['bio']: return flask.render_template('register.html', error='we\'re missing some info') if flask.request.form['password'] != flask.request.form['retypePassword']: return flask.render_template('register.html', error='passwords do not match') if len(flask.request.form['password']) < 6: return flask.render_template('register.html', error='passwords must be at least six characters') salt = mongo._create_random_string(34) passwordHash = generate_password_hash(flask.request.form['password'] + salt) # def register_user(self, userName, emailAddress, password, retypePassword, languages, bio, picture): (success, message) = mongo.register_user( flask.request.form['userName'] , flask.request.form['emailAddress'] , salt , passwordHash , flask.request.form.getlist('languages') , flask.request.form['bio'] , None) # picture if success: # log them in flask.session['logged_in'] = True flask.session['emailAddress'] = flask.request.form['emailAddress'] flask.session['userName'] = flask.request.form['userName'] flask.session['adminRights'] = False flask.session['verified'] = False return flask.redirect(flask.url_for('show_new_cases')) else: return flask.render_template('register.html', error=message)
def init_admin(): ''' adds a default admin to the database usage: $ /path/to/virtualenv/bin/python >> from initialize import init_admin >> init_admin() inserting "thebat" ''' initial_user = app.config['INITIAL_USER'] # make sure the values are unique query = {'emailAddress': initial_user['emailAddress']} emails = list(mongo.db['users'].find(query)) query = {'userName': initial_user['userName']} names = list(mongo.db['users'].find(query)) if emails: print 'failed, email exists' elif names: print 'failed, username exists' else: print 'inserting "%s"' % initial_user['userName'] salt = mongo._create_random_string(34) volunteer = { 'userName': initial_user['userName'] , 'emailAddress': initial_user['emailAddress'] , 'bio': '' , 'languages': [] , 'picture': None , 'salt': salt , 'passwordHash': generate_password_hash(initial_user['password'] + salt) , 'cases': [] , 'lastLogin': int(time.time()) , 'created': int(time.time()) , 'adminRights': True , 'verified': True } mongo.db['users'].insert(volunteer)
def init(): db = sqlite3.connect('carson.db') cursor = db.cursor() with open('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) email = raw_input("email: ") name = raw_input("name: ") password = raw_input("password: ") pw = generate_password_hash(password) token = token = sha.new(os.urandom(64)).hexdigest() cursor.execute('INSERT INTO users(email, name, password, token, role)' 'VALUES (?, ?, ?, ?, ?)', (email, name, pw, token, 'admin')) db.commit() secret_key = os.urandom(24) conf = get_conf() conf['carson']['secret_key'] = secret_key conf.write()
def register(): if session.get('logged_in'): flash('You\'re already registered') return redirect(url_for('user', id=session.get('username'))) error = None form = Registration(request.form) if request.method == 'POST' and form.validate(): user = User.query.filter_by(username=form.username.data).first() if user: error = 'That username is already in use' else: user = User( username = form.username.data.lower(), pwhash = generate_password_hash(form.pass_one.data), email = form.email.data, ) db.session.add(user) db.session.commit() auth_user(user) flash('You were successfully registered and are logged in') return redirect(url_for('index')) return render_template('register.html', form=form, error=error)
def register(): if session.get("logged_in"): flash("You're already registered") return redirect(url_for("user", id=session.get("username"))) error = None form = Registration(request.form) if request.method == "POST" and form.validate(): user = User.query.filter_by(username=form.username.data).first() if user: error = "User exists already" else: user = User( username=form.username.data.lower(), pwhash=generate_password_hash(form.pass_one.data), email=form.email.data, ) db.session.add(user) db.session.commit() auth_user(user) flash("You were successfully registered and are logged in") return redirect(url_for("index")) return render_template("register.html", form=form, error=error)
def setUp(self): app = flask.Flask(__name__) app.config["BCRYPT_LOG_ROUNDS"] = 6 bcrypt_init(app) self.password = "******" self.pw_hash = generate_password_hash(self.password)
def test_check_hash_unicode_is_utf8(self): password = u"\u2603" x = generate_password_hash(password) # check a correct password a = check_password_hash(x, "\xe2\x98\x83") self.assertTrue(a)
def set_password(self, password): BCRYPT_COMPLEXITY = 12 self.pw_hash = generate_password_hash(password, BCRYPT_COMPLEXITY)
def test_custom_rounds(self): pw_hash = generate_password_hash(self.password, 5) # high values will be slow! self.assertTrue(isinstance(pw_hash, str))
def test_not_string(self): pw_hash = generate_password_hash(42) self.assertTrue(isinstance(pw_hash, str))
def secure_ip(): ip = get_ip() if is_tor(): ip = 'anonymous_user' return generate_password_hash(ip)
def edit_profile(userName): ''' admin users can edit errybody, logged in users can edit themselves ''' if flask.request.method == 'GET': if 'logged_in' not in flask.session or not flask.session['logged_in']: # not defined or is false return flask.redirect(flask.url_for('login')) if ('adminRights' in flask.session and flask.session['adminRights']) or userName == flask.session['userName']: user = mongo.retrieve_users(userName=userName) if user: user = user[0] return flask.render_template('edit_profile.html', user=user) else: return flask.render_template('profile.html', notFound=True) else: # stranger return flask.redirect(flask.url_for('login')) elif flask.request.method == 'POST': if 'logged_in' not in flask.session or not flask.session['logged_in']: return flask.redirect(flask.url_for('login')) if ('adminRights' in flask.session and flask.session['adminRights']) or userName == flask.session['userName']: ''' do an update no matter what, use defaults if nothing in the form is specified ''' user = mongo.retrieve_users(userName=userName) if user: user = user[0] else: # what is this, I don't even.. return flask.redirect(flask.url_for('login')) # bio is currently the only mutable required change if not flask.request.form['bio']: return flask.render_template('edit_profile.html', user=user, error='please write something about yourself') else: bio = flask.request.form['bio'] # any of the password fields are specified.. if flask.request.form['newPassword'] or flask.request.form['retypeNewPassword'] or flask.request.form['oldPassword']: # but not /all/ of them if not flask.request.form['newPassword'] or not flask.request.form['retypeNewPassword'] or not flask.request.form['oldPassword']: return flask.render_template('edit_profile.html', user=user, error='we are missing some password info') # if a new password is specified, verify some things.. if flask.request.form['newPassword']: if not check_password_hash(user['passwordHash'], flask.request.form['oldPassword'] + user['salt']): return flask.render_template('edit_profile.html', user=user, error='old password is incorrect') if flask.request.form['newPassword'] != flask.request.form['retypeNewPassword']: return flask.render_template('edit_profile.html', user=user, error='new passwords do not match') if len(flask.request.form['newPassword']) < 6: return flask.render_template('edit_profile.html', user=user, error='new password must be at least six characters in length') passwordHash = generate_password_hash(flask.request.form['newPassword'] + user['salt']) else: passwordHash = user['passwordHash'] # new pass not specified, keeping with the old one.. languages = flask.request.form.getlist('languages') if 'adminRights' in flask.session and flask.session['adminRights']: # have to do some type conversions from what comes in on the form verified = True if flask.request.form['verifiedOptions'] == 'True' else False adminRights = True if flask.request.form['adminOptions'] == 'True' else False else: verified = user['verified'] adminRights = user['adminRights'] (success, message) = mongo.update_user( flask.request.form['userName'] , bio , passwordHash , languages , verified , adminRights) if success: success = message error = None # update the user object and pass to the template user['bio'] = bio user['languages'] = languages user['verified'] = verified user['adminRights'] = adminRights if userName == flask.session['userName']: # update session state, only if the logged in user is modifying hisself if adminRights: flask.session['adminRights'] = True else: flask.session.pop('adminRights', None) if verified: flask.session['verified'] = True else: flask.session.pop('verified', None) else: success = None error = message return flask.render_template('edit_profile.html', user=user, error=error, success=success)
def setUp(self): app = flask.Flask(__name__) app.config['BCRYPT_LOG_ROUNDS'] = 6 bcrypt_init(app) self.password = '******' self.pw_hash = generate_password_hash(self.password)
def hashPassword(passwd): return unicode(Bcrypt.generate_password_hash(passwd))
def hash_password(self, password): return generate_password_hash(password,rounds=app.config['BCRYPT_SALT_ROUNDS'])
def set_password(self, password): self.pw_hash = generate_password_hash(password)
print "Removed the old database first ................................." os.remove(appconf.DATABASE) init_db() #quick check if database was created if not os.path.isfile(appconf.DATABASE): print "Looks like there was some problem in creating the Database. You may want to try again" sys.exit() print "Congratulations Database was setup\n" print "Step 2. Setup the admin, checking the one time config file" print "...................................................................." if not os.path.isfile("conf/onetimeconf.py"): print "Couldn't find onetimeconf.py in the conf folder. Please create that file as per the README" else: print "Found the file, now attempting to add the admin" from conf.onetimeconf import admin_nick, admin_email, admin_password usable_password = generate_password_hash(admin_password) admin = Operators(nick=admin_nick,email=admin_email,password=usable_password) db.session.add(admin) db.session.commit() print "Attempting to check if admin was added..." check = Operators.query.filter_by(email=admin_email).first() if check: print "Congratulations the admin was setup with the email: "+ admin_email print "Now attempting to REMOVE the onetimeconf.py file. It is dangerous to keep it around" os.remove('conf/onetimeconf.py') if not os.path.isfile('conf/onetimeconf.py'): print "Successful! Perfect. Now you're good to go. Start quotr by doing python quotr.py" else: print "uh oh. Looks like the file wasn't removed. Kindly remove it manually. It is unsafe to keep that file"
def secure_ip(): return generate_password_hash(get_ip())
def add_user(self, email, password): assert(email != None and password != None) conn, cur = self.start_op() id = uuid() cur.execute("INSERT INTO users (id, email, password) VALUES (%s, %s, %s)", [str(id), email, generate_password_hash(password)]) self.close_op(conn) return id
def test_check_hash_unicode_is_utf8(self): password = u'\u2603' x = generate_password_hash(password) # check a correct password a = check_password_hash(x, '\xe2\x98\x83') self.assertTrue(a)
def __init__(self, nickname, email, password): self.nickname = nickname self.email = email if password: self.pwd_hash = generate_password_hash(password) self.generate_auth_tokens()