def test_friendship_manager_make_friends(self): user1 = User( username='******', password=generate_password_hash('a'), email='*****@*****.**' ) user2 = User( username='******', password=generate_password_hash('a'), email='*****@*****.**' ) db.session.add(user1) db.session.add(user2) db.session.commit() Friend.objects.make_friends(user1.id, user2.id) are_friends = Friend.objects.are_friends(user1.id, user2.id) self.assertTrue(are_friends) requests = Friend.objects.requests(user1.id) self.assertEqual(requests, [], msg=None) requests = Friend.objects.requests(user2.id) self.assertEqual(requests, [], msg=None)
def test_friendship_manager_make_friends_are_already_friends(self): user1 = User( username='******', password=generate_password_hash('a'), email='*****@*****.**' ) user2 = User( username='******', password=generate_password_hash('a'), email='*****@*****.**' ) db.session.add(user1) db.session.add(user2) db.session.commit() Friend.objects.make_friends(user1.id, user2.id) are_friends = Friend.objects.are_friends(user1.id, user2.id) self.assertTrue(are_friends) try: Friend.objects.make_friends(user1.id, user2.id) self.assertTrue(False, "They are already friends, so...") except AlreadyFriendsError: self.assertTrue(True) are_friends = Friend.objects.are_friends(user1.id, user2.id) self.assertTrue(are_friends) friends = Friend.objects.friends(user1.id) self.assertIsNotNone(friends, msg=None) self.assertEqual(len(friends), 1, msg=None)
def signUp(): try: _name = request.form['inputName'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] # validate the received values if _name and _email and _password: # All Good, let's call MySQL conn = mysql.connect() cursor = conn.cursor() print '---' + generate_password_hash(_password) _hashed_password = generate_password_hash(_password) cursor.callproc('sp_createUser',(_name,_email,_hashed_password)) data = cursor.fetchall() if len(data) is 0: conn.commit() return json.dumps({'message':'User created successfully !'}) else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'<span>Enter the required fields</span>'}) except Exception as e: return json.dumps({'error':str(e)}) finally: cursor.close() conn.close()
def populate(): print print ("Run only once or you will get error for duplicates") print # init_db() conn = sqlite3.connect('DB/twittr.db') c = conn.cursor() users = [('*****@*****.**', generate_password_hash('abc123'),'George','Constanza', '', 1), ('*****@*****.**',generate_password_hash('mary123'), 'Mary', 'Lamb', '', 1), ('*****@*****.**',generate_password_hash('peter123'),'Peter','Piper', '', 1), ] c.executemany('INSERT INTO users VALUES (?,?,?,?,?,?)', users) tweets = [(0, '*****@*****.**',"tweet0",str(current_time),"NULL"), (1, '*****@*****.**',"tweet1",str(current_time),"NULL"), (2, '*****@*****.**',"tweet2",str(current_time),"NULL"), (3, '*****@*****.**',"tweet3",str(current_time), "NULL"),] c.executemany('INSERT INTO tweets VALUES (?,?,?,?,?)', tweets) subs = [ ('*****@*****.**', '*****@*****.**'), ('*****@*****.**', '*****@*****.**'), ('*****@*****.**', '*****@*****.**'), ] c.executemany('INSERT INTO subscriptions VALUES (?,?)', subs) # commit or there are no changes conn.commit() print ('Done.')
def test_users_account_route_account(self): """Ensure users account actually create the user""" # add user to database user = User(username='******', password=generate_password_hash('a'), email='*****@*****.**') db.session.add(user) db.session.commit() self.login(email='*****@*****.**', password='******') response = self.app.post('/users/account/', data=dict( username='******', email='*****@*****.**', password='******', confirm='aaaaaa', old_password='******' ), follow_redirects=True) self.assertTrue(response.status_code == 200) self.assertTemplateUsed('users/account.html') self.assertIn(b'The changes have been saved', response.data) updated_user = User.query.filter_by(username='******').first() self.assertTrue(updated_user is not None) self.assertTrue(updated_user.email == '*****@*****.**') self.assertTrue(check_password_hash(updated_user.password, 'aaaaaa')) old_user = User.query.filter_by(username='******').first() self.assertTrue(old_user is None) # SECOND USER - ONLY USERNAME self.logout() # add user to database second_user = User(username='******', password=generate_password_hash('a'), email='*****@*****.**') db.session.add(second_user) db.session.commit() self.login(email='*****@*****.**', password='******') response = self.app.post('/users/account/', data=dict( username='******', email='*****@*****.**', password='', confirm='', old_password='' ), follow_redirects=True) self.assertTrue(response.status_code == 200) self.assertTemplateUsed('users/account.html') self.assertIn(b'The changes have been saved', response.data) updated_user = User.query.filter_by(username='******').first() self.assertTrue(updated_user is not None) self.assertTrue(updated_user.email == '*****@*****.**') self.assertTrue(check_password_hash(updated_user.password, 'a'))
def __init__(self, name, email, password=None): self.name = name if password: self.pwdhash = generate_password_hash(password) else: print "CHECK FOR EMAIL!!!!" random_password = self.GenPasswd2() print "Made account for %s with PW=%s. Impliment emailing this!!!! See http://packages.python.org/flask-mail/" % (self.name, random_password) self.pwdhash = generate_password_hash(random_password) self.email = email self.activate = False self.created = datetime.utcnow()
def modify_password(userId): user = g.user form = ModifyPasswordForm() if request.method == "POST" and form.validate(): old_hashed_password = generate_password_hash(form.old_password.data) new_hashed_password = generate_password_hash(form.new_password.data) if check_password_hash(user.password, form.old_password.data): user = User.query.get(userId) user.password = new_hashed_password psc_db.session.commit() flash("Password has beeen changed") return redirect(url_for("users.profile", userId=userId)) return render_template("users/modify_password.html", form=form, user=user)
def test_add_user_to_database(self): user = User(username='******', password=generate_password_hash('a'), email='*****@*****.**') db.session.add(user) db.session.commit() user = User.query.filter_by(username='******').first() assert user.id == 1 assert user.username == 'john' assert check_password_hash(user.password, 'a') assert user.email == '*****@*****.**' self.assertIn("facebook$" + user.username, user.social_id) assert user.registered_on is not None assert user.confirmed is False assert user.confirmed_on is None self.assertTrue(user.first_login is None) self.assertTrue(user.last_login is None) self.assertFalse(user.is_active_login()) user.update_login_info() login_date = datetime.now() self.assertTrue(user.first_login is not None) self.assertLess(user.first_login, login_date) self.assertTrue(user.last_login is not None) self.assertLess(user.last_login, login_date) self.assertTrue(user.is_active_login()) user.last_login = datetime.now() + timedelta(days=-10) db.session.add(user) db.session.commit() self.assertFalse(user.is_active_login()) # login again user.update_login_info() self.assertTrue(user.first_login is not None) self.assertLess(user.first_login, login_date) self.assertTrue(user.last_login is not None) self.assertGreater(user.last_login, login_date) user_second = User(username='******', password=generate_password_hash('a'), email='*****@*****.**') db.session.add(user_second) db.session.commit() user_second = User.query.filter_by(username='******').first() assert user_second.id == 2 self.assertEqual(user_second.id, 2) self.assertNotEqual(user_second.username, 'john', msg=None) self.assertEqual(user_second.username, 'johner')
def test_user_social_id(self): user = User( username='******', password=generate_password_hash('a'), email='*****@*****.**' ) self.assertIn('facebook$john', user.social_id) user = User( username='******', password=generate_password_hash('a'), email='*****@*****.**', social_id='facebok$sadfaksdfjasd' ) self.assertEqual(user.social_id, 'facebok$sadfaksdfjasd')
def register(): """Registers the user.""" if g.user: return redirect(url_for('timeline')) error = None if request.method == 'POST': if not request.form['username']: error = 'You have to enter a username' elif not request.form['email'] or \ '@' not in request.form['email']: error = 'You have to enter a valid email address' elif not request.form['password']: error = 'You have to enter a password' elif request.form['password'] != request.form['password2']: error = 'The two passwords do not match' elif get_user_id(request.form['username']) is not None: error = 'The username is already taken' else: g.db.execute('''insert into user ( username, email, pw_hash) values (?, ?, ?)''', [request.form['username'], request.form['email'], generate_password_hash(request.form['password'])]) g.db.commit() flash('You were successfully registered and can login now') return redirect(url_for('login')) return render_template('register.html', error=error)
def register_user(): """포토로그 사용자 등록을 위한 함수""" form = RegisterForm(request.form) if form.validate(): username = form.username.data email = form.email.data password = form.password.data try: user = User(username, email, generate_password_hash(password)) dao.add(user) dao.commit() Log.debug(user) except Exception as e: error = "DB error occurs : " + str(e) Log.error(error) dao.rollback() raise e else: # 성공적으로 사용자 등록이 되면, 로그인 화면으로 이동. return redirect(url_for('.login', regist_username=username)) else: return render_template('regist.html', form=form)
def register(): """Provides registering for user""" # if register form is submitted form = RegisterForm(request.form) # verify the register form if form.validate_on_submit(): # create user and add to database user = User( username=form.username.data, password=generate_password_hash(form.password.data), email=form.email.data ) db.session.add(user) db.session.commit() # sending email token = generate_confirmation_token(user.email) confirm_url = url_for('users.confirm_email', token=token, _external=True) html = render_template('users/activate.html', confirm_url=confirm_url) subject = gettext(u"Please confirm your email") send_email(user.email, subject, html) #login_user(user) # everything okay so far flash(gettext(u'Confirmation email has been sent'), 'info') return redirect(url_for('users.login')) return render_template('users/register.html', form=form)
def update_user(username): """포토로그 사용자 정보 수정을 위한 함수""" current_user = __get_user(username) form = UpdateForm(request.form) if form.validate(): email = form.email.data password = form.password.data try: current_user.email = email current_user.password = generate_password_hash(password) dao.commit() except Exception as e: dao.rollback() Log.error(str(e)) raise e else: # 변경된 사용자 정보를 세션에 반영 session['user_info'].email = \ current_user.email session['user_info'].password = \ current_user.password session['user_info'].password_confirm = \ current_user.password # 성공적으로 사용자 등록이 되면, 로그인 화면으로 이동. return redirect(url_for('.login', update_username=username)) else: return render_template('regist.html', user=current_user, form=form)
def changePassword(): if g.user: try: mysql.connect() with mysql.cursor() as cursor: if request.method == "POST": oldPasswordInput = request.form['oldPassword'] newPasswordInput = request.form['newPassword'] newPasswordCheckInput = request.form['newPasswordChecker'] if check_password_hash(passwordFromDB, oldPasswordInput) and newPasswordInput == newPasswordCheckInput: newPassword = generate_password_hash(newPasswordInput) cursor.execute('UPDATE tbl_login SET password=%s WHERE password=%s', (newPassword,passwordFromDB)) flash("Lösenordet är nu ändrat") mysql.commit() else: flash("The old password is incorrect or the new password does not match.") except Exception as e: return render_template('error.html',error = str(e)) else: return ('Unauthorized Access') finally: cursor.close() mysql.close() return render_template('changePassword.html') return redirect(url_for('login'))
def signUp(): try: _name = request.form['inputName'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] # Valida os dados recebidos if _name and _email and _password: with closing(mysql.connect()) as conn: with closing(conn.cursor()) as cursor: _hashed_password = generate_password_hash(_password) cursor.callproc('sp_createUser',(_name,_email,_hashed_password)) data = cursor.fetchall() if len(data) is 0: conn.commit() return json.dumps({'message':'User criado com sucesso!'}) else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'<span>preencha os campos requeridos</span>'}) except Exception as e: return json.dumps({'error':str(e)})
def register(): # 3개의 값 입력받아 db에 넣기 # init_db() print("**** 회원 가입 ****\n") print("user id:", end="") userid = input() db = get_db() # db.isolation_level = None cur = db.cursor() cur.execute("select * from user") if cur.fetchone() != None: print("아이디가 존재합니다") return else: # 필드명 지정해주면 table원소개수만큼 꽉안차게 해도 됨 print("user name:", end="") username = input() print("user password:"******"") userpasswd = input() sql = "insert into user(userid, username,userpw) values(?,?,?)" # cur.execute(sql,[userid,username,userpasswd]) cur.execute(sql, [userid, username, userpasswd], generate_password_hash(userpasswd)) cur.execute("select * from user") print(cur.fetchall()) db.commit() # print(cur.fetchall()) db.close()
def register(): """ """ next = '' if request.method == 'GET': if 'next' in request.args: next = request.args['next'] form = RegisterForm(request.form) if form.validate_on_submit(): # create an user instance not yet stored in the database user = User(username=form.username.data, email=form.email.data, \ password=generate_password_hash(form.password.data)) # Insert the record in our database and commit it db.session.add(user) db.session.commit() # Log the user in, as he now has an id session['user_id'] = user.id flash('thanks for signing up!', 'success') if 'next' in request.form and request.form['next']: return redirect(request.form['next']) return redirect(url_for('frontends.home')) return render_template("register.html", form=form, next=next)
def user_create(username, password): user = User(username, generate_password_hash(password)) db.session.add(user) db.session.commit() # only after commiting do you have user.user_id first_tag = Tag('cats', user.user_id) db.session.add(first_tag) db.session.commit()
def _create_account_record(user): account = Account.query.filter_by(dolly_user=user).first() if account: return account, False dollyuser = dolly.DollyUser(user, _dolly_token(user)) userdata = dollyuser.get_userdata() accountname = userdata['display_name'] username = userdata['email'] or userdata['username'] postfix = 0 while True: if AccountUser.query.filter_by(username=username).count() == 0: break postfix += 1 username = userdata['email'].replace('@', '+%d@' % postfix) password = _gen_password() accountuser = AccountUser( username=username, password_hash=generate_password_hash(password), ) account = Account( dolly_user=user, dolly_token=dollyuser.token, name=accountname, users=[accountuser], ) db.session.add(account) current_app.logger.info('Created new user: %s/%s', username, password) return account, True
def register(): """ Registers the user. """ if g.user: return redirect(url_for('home')) if request.method == 'POST': if not request.form['username']: flash("You have to enter a username.") elif not request.form['email'] or '@' not in request.form['email']: flash("You have to enter a valid email.") elif not request.form['password']: flash("You have to enter a password.") elif request.form['password'] != request.form['password2']: flash("The two passwords do not match.") elif database.get_user_id(email=request.form['email']) is not None: flash("User with this email already exists.") elif database.get_user_id(username=request.form['username']) is not None: flash("User with this username already exists.") else: g.db.execute('''insert into pending_users ( username, email, pw_hash) values (?, ?, ?)''', [request.form['username'], request.form['email'], generate_password_hash(request.form['password'])]) g.db.commit() flash("Successfully requested an account"); return redirect(url_for('login')) return render_template('register.html')
def adduser(args): if len(args) == 2: name, password = args email = None uploader = None elif len(args) == 3: name, password, email = args uploader = None elif len(args) == 4: name, password, email, uploader = args else: sys.exit('''adduser requires 2 to 4 arguments: adduser NAME PASSWORD [EMAIL [UPLOADER]]''') kwargs = {'name': name, 'password': generate_password_hash(password), 'email' : email or '', 'uploader': bool(uploader)} print('Adding user \'{0}\''.format(name)) for k, v in sorted(kwargs.items()): if k == 'name': continue print('{0:<9} {1}'.format(k + ':', v)) correct = input('Data correct? [yes/NO] ') if correct.lower() == 'yes': User.create(**kwargs) print('Added', name) else: print('Aborting.')
def signUp(): try: #read the posted values from the UI _name = request.form['inputName'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] #validate the received values if _name and _email and _password: #We call the MySQL conn = mysql.connect() cursor = conn.cursor() #prepare a cursor object using cursor() method _hashed_password = generate_password_hash(_password) cursor.callproc('sp_createUser',(_name,_email,_hashed_password)) #If the procedure is executed successfully, we commit the changes and return the success message: data = cursor.fetchall() #fetch all of the rows from the query if len(data) is 0: conn.commit() return json.dumps({'message':'User created successfully !'}) else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'<span> Enter the required fields</span>'}) except Exception as e: return json.dumps({'error':str(e)}) finally: cursor.close() conn.close()
def register(): """Registers the user.""" if g.user: return redirect(url_for('timeline')) error = None if request.method == 'POST': if not request.form['username']: error = 'You have to enter a username' elif not request.form['email'] or \ '@' not in request.form['email']: error = 'You have to enter a valid email address' elif not request.form['password']: error = 'You have to enter a password' elif request.form['password'] != request.form['password2']: error = 'The two passwords do not match' elif user_model.get_id(request.form['username']) is not None: error = 'The username is already taken' else: data = dict([[k, v] for k, v in request.form.items()]) data['pw_hash'] = generate_password_hash(data['password']) del data['password'] del data['password2'] user_model.add(data['username'], data['pw_hash'], data['email']) flash('You were successfully registered and can login now') return redirect(url_for('login')) return render_template('rbac/register.html', error=error)
def validateLogin(): try: _username = request.form['inputEmail'] _password = request.form['inputPassword'] # connect to mysql con = mysql.connect() cursor = con.cursor() cursor.callproc('sp_validateLogin',(_username,)) data = cursor.fetchall() _hashed_password = generate_password_hash("redrose123") if len(data) > 0: if check_password_hash(str(data[0][2]),_password): session['user'] = data[0][1] return redirect('/userHome') else: return render_template('error.html',error = 'Wrong Email address or Password.') else: return render_template('error.html',error = 'Wrong Email address or Password.') except Exception as e: return render_template('error.html',error = str(e)) finally: cursor.close() con.close()
def login(): """ logs in the user. if the username doesn't exist creates the account """ if not request.form['username']: flash('You have to enter a username') elif not request.form['password']: flash('You have to enter a password') elif get_user_id(request.form['username']) is not None: # username already exists, fetch all of its attributes user = query_db('''select * from user where username = ?''', [request.form['username']], one=True) if check_password_hash(user['pw_hash'], request.form['password']): # password is correct, log in the user session['user_id'] = get_user_id(request.form['username']) flash('User ' + request.form['username'] + ' logged in.') else: # incorrect password flash('User ' + request.form['username'] + ' already exists, wrong password.') else: # create account and log in creation_time = int(time.time()) g.db.execute('''insert into user (username, pw_hash, creation_time) values (?, ?, ?)''', [request.form['username'], generate_password_hash(request.form['password']), creation_time]) user_id = g.db.execute('select last_insert_rowid()').fetchall()[0][0] g.db.commit() session['user_id'] = user_id flash('New account %s created' % (request.form['username'], )) return redirect(url_for('intmain'))
def _set_password(self, password): if password: self._password = generate_password_hash(password) password_descriptor = property(self._get_password, self._set_password) password = synonym('_password', descriptor=password_descriptor)
def twitter_authorized(resp): index = url_for("index") if resp is None: print 'You denied the request to sign in.' return redirect(index) try: user = User.objects.get(username=resp['screen_name']) user.date_logged_in = datetime.now() except: # the user doesn't exist in the database user = User(username=resp['screen_name'], pw_hash=generate_password_hash('password'), date_registered=datetime.now(), date_logged_in=datetime.now(), playlists=create_default_playlists()) user.save() session['oauth_token'] = resp['oauth_token'] session['oauth_token_secret'] = resp['oauth_token_secret'] usr_obj = UserLogin(user) login_user(usr_obj) return make_response(html, 200)
def create_account(): if current_user.is_authenticated(): return jsonify(result="Already logged in.") if request.method == "POST" and "username" in request.json: username = request.json["username"] password = request.json["password"] email = request.json["email"] validate_email = validators.Email().regex.search if not username or not password or not email: # already checked in Javascript return jsonify(result="Empty username or password.") elif not validate_email(email): return jsonify(result="Invalid email.") elif not 2 < len(username) < 26: return jsonify(result="Username must be 3-25 characters") elif not 3 < len(password) < 33: return jsonify(result="Password must be 4-32 characters") elif User.objects(username=username).first() is not None: return jsonify(result="The username is already taken.") elif User.objects(email=email).first() is not None: return jsonify(result="You have already registered with this email.") else: new_user = User(username=username, email=email, pw_hash=generate_password_hash(password), date_registered=datetime.now(), date_logged_in=datetime.now(), playlists=create_default_playlists()) new_user.save() # the date_logged_in is create because when the user is created is also automatically logged inself. usr_obj = UserLogin(User.objects.get(username=username)) if login_user(usr_obj): return json_response(str(usr_obj)) else: return jsonify(result="Error during login")
def facebook_authorized(resp): if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) session['oauth_token'] = (resp['access_token'], '') me = facebook.get('/me') try: user = User.objects.get(username=me.data['name']) user.date_logged_in = datetime.now() except: # the user doesn't exist in the database user = User(username=me.data['name'], email=me.data['email'], pw_hash=generate_password_hash('password'), date_registered=datetime.now(), date_logged_in=datetime.now(), playlists=create_default_playlists()) # the date_logged_in is create because when the user is created is also automatically logged inself. user.save() usr_obj = UserLogin(user) login_user(usr_obj) return make_response(html, 200)
def register(): if 'user_id' in session: return redirect(url_for('timeline')) error = None if request.method == 'POST': if not request.form['username']: error = 'Please enter your username' elif not request.form['fullname']: error = 'Please enter your fullname' elif not request.form['password']: error = 'Please enter your password' elif request.form['password'] != request.form['password2']: error = 'The two password that you entered didn\'t match' elif get_user_id(request.form['username']) is not None: error = 'The username is already taken' else: db = connect_db() db.execute('''insert into users ( username, fullname, password) values (?, ?, ?)''', (request.form['username'], request.form['fullname'], generate_password_hash(request.form['password']))) db.commit() user_id = get_user_id(request.form['username']) db.execute('insert into followers (user_id, follower_id) values (?, ?)', (user_id, user_id)) db.commit() db.close() flash('You were successfully registered') return redirect(url_for('login'))
def generate_password_hash(self, password): return generate_password_hash(password, **self.pwd_hash_args)
def set_password(self, password): self.pwdhash = generate_password_hash( password) #imported this on line 2
def __init__(self, username, password): self.username = username self.password = generate_password_hash(password)
def _set_password(self, password): if password: password = password.strip() self._password = generate_password_hash(password)
def set_password(self, password): """ Hash the user's password. """ self.password_hash = generate_password_hash(password)
def __init__(self, app): self.username = app.config['ADMIN_NAME'] self.password = generate_password_hash(app.config['ADMIN_PASSWORD'])
def set_password(self, password): self.pwdhash = generate_password_hash(password)
def set_password(self, pw): self.password = generate_password_hash(pw)
def save_password(self, password): # TODO return generate_password_hash(password)
def set_password(self, password): self.password = generate_password_hash(password) return self.password
mydb.create_collection('author') myrecord = { "author": "Duke", "title": "PyMongo 101", "tags": ["MongoDB", "PyMongo", "Tutorial"], "date": datetime.datetime.utcnow() } mydb.author.insert_one(myrecord) myco = mydb.test import datetime from bson.objectid import ObjectId from werkzeug import generate_password_hash passtest = generate_password_hash("new") passtest mydb.drop_collection('messages') mydb.create_collection('messages') mydb.drop_collection('users') mydb.create_collection('users') myrecord = { "username": "******", "email": "*****@*****.**", "password": passtest, 'avatar': 'static/img/avatar.png', "date": datetime.datetime.utcnow() } myrecord mydb.users.insert_one(myrecord) for s in mydb.users.find():
def set_password(self, password): self.password = generate_password_hash( password, # run 2000 iterations of sha1 in pkdf2 method='pbkdf2:sha1:2000')
def __init__(self, name, email, password): self.name = name self.email = email self.password = generate_password_hash(password)
def hash(passwd): """ Generate password hash code """ from werkzeug import generate_password_hash hash_ = generate_password_hash(passwd) print(hash_)
def set_password(self, secret): self.password = generate_password_hash(secret)
def set_password(self, password): self.data['password'] = generate_password_hash(password)
def password(self, password): self._pw_hash = generate_password_hash(password)
def setPassword(self, password): """ Set an hashed password from werzeugh method""" self.password = generate_password_hash(password)
def register(): # if already logged in if g.user: return redirect(url_for('index')) error = None if request.method == 'POST': user_type = request.form['accountType'] if user_type == 'Student': #assert request.form['username'] == None, 'Please, enter a username' if not request.form['username']: error = 'Please, enter a username' elif not request.form['password']: error = 'Please, enter a password' elif not request.form['password2']: error = 'Please, enter a password' elif request.form['password'] != request.form['password2']: error = 'Passwords do not match!' elif not request.form['email']: error = 'Please, enter an email' elif not request.form['firstName']: error = 'Please, enter a first name' elif not request.form['lastName']: error = 'Please, enter a last name' elif not request.form['major']: error = 'Please, enter a major' elif not request.form['minor']: error = 'Please, enter a minor' elif not request.form['phoneNumber']: error = 'Please, enter a phone number' elif len(request.form['phoneNumber']) != 10: error = 'Please, enter a 10-digit valid phone number without dash' elif not request.form['GPA']: error = 'Please, enter a GPA' else: flash('Your student account was successfully registered!') db.session.add( Student(username=request.form['username'], pw_hash=generate_password_hash( request.form['password']), email=request.form['email'], first_name=request.form['firstName'], last_name=request.form['lastName'], year=request.form['grade'], major=request.form['major'], minor=request.form['minor'], gender=request.form['gender'], gpa=request.form['GPA'], phone=request.form['phoneNumber'])) db.session.commit() return redirect(url_for('login')) elif user_type == 'Organization': if not request.form['username']: error = 'Please, enter a username' elif not request.form['password']: error = 'Please, enter a password' elif not request.form['password2']: error = 'Please, enter a password' elif request.form['password'] != request.form['password2']: error = 'Passwords do not match!' elif not request.form['email']: error = 'Please, enter an email' elif not request.form['orgname']: error = 'Please, enter an organization name' else: flash( 'Your student organization account was successfully registered!' ) db.session.add( Organization(username=request.form['username'], pw_hash=generate_password_hash( request.form['password']), email=request.form['email'], name=request.form['orgname'])) db.session.commit() return redirect(url_for('login')) elif user_type == 'Company': if not request.form['username']: error = 'Please, enter a username' elif not request.form['password']: error = 'Please, enter a password' elif not request.form['password2']: error = 'Please, enter a password' elif request.form['password'] != request.form['password2']: error = 'Passwords do not match!' elif not request.form['email']: error = 'Please, enter an email' elif not request.form['companyname']: error = 'Please, enter a company name' else: flash('Your company account was successfully registered!') db.session.add( Company(username=request.form['username'], pw_hash=generate_password_hash( request.form['password']), email=request.form['email'], name=request.form['companyname'])) db.session.commit() return redirect(url_for('login')) # if request.method == 'GET' return render_template('register.html', YEAR=Year, GENDER=Gender, error=error)
def initdb_command(): # Drop the database and create the new one db.drop_all() db.create_all() # Hardcode the admin account db.session.add( Admin(username='******', pw_hash=generate_password_hash('admin'), email='*****@*****.**', description='I am an admin ;)')) # Hardcode `Human` student db.session.add( Student(username='******', pw_hash=generate_password_hash('123456'), email='*****@*****.**', description='I am a student', first_name='Human', last_name='Namuh', year=Year.SENIOR, major='CS', minor='LIFE', gender=Gender.OTHER, gpa=4.0, work_status=WorkStatus.USCITIZEN, clearance=Clearance.NONE, search_status=SearchStatus.OPEN, phone='4128933928')) # Hardcode `Ariana` student db.session.add( Student(username='******', pw_hash=generate_password_hash('ariana'), email='*****@*****.**', description='I am a student in CS', first_name='ariana', last_name='grande', year=Year.JUNIOR, major='CS', minor='IS', gender=Gender.OTHER, gpa=3.88, work_status=WorkStatus.USCITIZEN, clearance=Clearance.NONE, search_status=SearchStatus.OPEN, phone='4129339992')) # hardcode organization(s) db.session.add( Organization(username='******', pw_hash=generate_password_hash('fresa'), email='*****@*****.**', description='Dance together!', name='Fresa')) db.session.add( Organization(username='******', pw_hash=generate_password_hash('ksa'), email='*****@*****.**', description='Koreans squads!', name='KSA')) db.session.add( Organization(username='******', pw_hash=generate_password_hash('asa'), email='*****@*****.**', description='Asian squads!', name='ASA')) db.session.add( Organization(username='******', pw_hash=generate_password_hash('wics'), email='*****@*****.**', description='Women in CS!', name='WiCS')) db.session.add( Organization(username='******', pw_hash=generate_password_hash('globaltie'), email='*****@*****.**', description='Global Tie!', name='GlobalTie')) # Hardcode company(s) db.session.add( Company(username='******', pw_hash=generate_password_hash('google'), email='*****@*****.**', description='OH YESSSSS', name='GOOGLE')) db.session.commit() print('Initialized the database')
def test_user(): user = User(name='Test User', email='*****@*****.**', password=generate_password_hash('secret')) user.put() return user
def set_password(self, password): self.password = werkzeug.generate_password_hash(password)
def getDigest(password): """ Generate a digest for the salted hash of a password. """ return werkzeug.generate_password_hash(password)
def set_password(self, password): self.account_password = generate_password_hash(password)
def initdb_command(): db.create_all() db.session.add(User(user_type='1', username='******', name='Owner', pw=generate_password_hash('pass'))) db.session.commit() print('Initialized the database.')
from werkzeug import generate_password_hash print(generate_password_hash('Sujith'))
def _set_password(self, password): self._password = generate_password_hash(password)
def _set_password(self, password): if password: password = password.strip() self._password = generate_password_hash(password) password_descriptor = property(self._get_password, self._set_password) password = synonym('_password', descriptor=password_descriptor)
def _password_set(self, v): self.password_hash = generate_password_hash(v)
def acc_register_(message): error = None success = None namespace = 'test' log.info('Register User: %s' % str(message)) if not message['username']: error = 'You have to enter a blockchain id' elif get_blockchain_id(message['username']) is not None: error = 'The blockchain id is already taken' elif not message['email'] or \ '@' not in message['email']: error = 'You have to enter a valid email address' elif not message['pwd1']: error = 'You have to enter a password' elif message['pwd1'] != message['pwd2']: error = 'The two passwords do not match' elif get_user_id(message['username']) is not None: error = 'The username is already taken' else: db = get_db() db.execute( '''insert into user ( username, email, pw_hash) values (?, ?, ?)''', [ message['username'], message['email'], generate_password_hash(message['pwd1']) ]) username = message['username'] + '.' + namespace log.info(username) preorder_result = json.dumps(client.preorder(username, config.PRIV_KEY)) preorder_result = json.loads(preorder_result) preorder_result['operation'] = 'preorder' log.info('Blockchain result: %s' % str(preorder_result)) if 'success' in preorder_result: db.commit() success = 'You successfully pre-ordered blockchain userid: ' + message[ 'username'] emit('preorder_tx', preorder_result) ## send a register request register_result = json.dumps( client.register(username, config.PRIV_KEY, preorder_result['register_address'])) register_result = json.loads(register_result) register_result['operation'] = 'register' log.info('Register Response = %s' % str(register_result)) if 'success' in register_result: emit('register_tx', register_result) elif 'error' in preorder_result: ## need to do some conditional retries here eg indexing blockchain error = preorder_result['error'] emit('my_response', { 'data': 'Register a user', 'error': error, 'success': success })