def htpasswd(password, hash): if hash.startswith('$apr1$'): return md5crypt(password, hash[6:].split('$')[0], '$apr1$') elif hash.startswith('{SHA}'): return '{SHA}' + sha1(password).digest().encode('base64')[:-1] elif passlib_ctxt is not None and hash.startswith('$5$') and \ 'sha256_crypt' in passlib_ctxt.policy.schemes(): return passlib_ctxt.encrypt(password, scheme="sha256_crypt", rounds=5000, salt=hash[3:].split('$')[0]) elif passlib_ctxt is not None and hash.startswith('$6$') and \ 'sha512_crypt' in passlib_ctxt.policy.schemes(): return passlib_ctxt.encrypt(password, scheme="sha512_crypt", rounds=5000, salt=hash[3:].split('$')[0]) elif crypt is None: # crypt passwords are only supported on Unix-like systems raise NotImplementedError(_("""The \"crypt\" module is unavailable on this platform.""")) else: if hash.startswith('$5$') or hash.startswith('$6$'): # Import of passlib failed, now check, if crypt is capable. if not crypt(password, hash).startswith(hash): # No, so bail out. raise NotImplementedError(_( """Neither are \"sha2\" hash algorithms supported by the \"crypt\" module on this platform nor is \"passlib\" available.""")) return crypt(password, hash)
def save_admin(): if not session.get('logged_in'): abort(401) db = get_db() password = pwd_context.encrypt(request.form['password']) if 'id' in request.form.keys(): if request.form['password'] == '******': db.execute('UPDATE adminss SET name = ?, mail = ?, password = ? WHERE id = ?', [request.form['name'], request.form['mail'], password, request.form['id']]) else: db.execute('UPDATE users SET name = ?, mail = ? WHERE id = ?', [request.form['name'], request.form['mail'], request.form['id']]) else: db.execute('INSERT INTO admins (name, mail, password) VALUES (?, ?, ?)', [request.form['name'], request.form['mail'], password]) db.commit() flash(lazy_gettext('Changes to the admin where saved successfully!')) return redirect(url_for('show_admins'))
def from_data(cls, data): return cls( name=data['name'], email=data['email'], password=pwd_context.encrypt(data['password']), created=int(time()) )
def __init__(self, id, email, password, su_status, admin_status, theone_status): self.id = id self.email = email self.is_superuser = su_status self.is_admin = admin_status self.is_theone = theone_status self.password_hash = pwd_context.encrypt(password)
def setUp(self): self.db_fd, app.config['DATABASE'] = tempfile.mkstemp() app.config.update( TESTING=True, SQLALCHEMY_DATABASE_URI='sqlite:////%s' % app.config['DATABASE'], SECRET_KEY = os.urandom(24) ) # create db and populate db.create_all() user = User(username='******') user.password = pwd_context.encrypt('doe') db.session.add(user) db.session.commit() # create product store now = dt.now().strftime('%a %b %d %H:%M:%S %Y') store.set('last-update', now) for i in range(5): pid = 's%d' % i store.lpush('user:%s:products' % user.id, pid) store.hset('products:%s' % pid, 'version', 1) # create a test app every test case can use. self.test_app = app.test_client()
def encrypt(raw_password): """Encrypt a raw password into a secure hash using passlib. Setup:: >>> from mock import Mock >>> from pyramid_simpleauth import model >>> _pwd_context = model.pwd_context >>> model.pwd_context = Mock() >>> model.pwd_context.encrypt.return_value = 'digest' Returns a unicode version of the encrypted password:: >>> encrypt('Foo ') u'digest' Using a lower case, stripped version of the raw password:: >>> model.pwd_context.encrypt.call_args[0][0] 'foo' Teardown:: >>> model.pwd_context = _pwd_context """ v = raw_password.strip().lower() s = pwd_context.encrypt(v, scheme="sha512_crypt", rounds=90000) return unicode(s)
def register(): """Register user.""" if request.method == "POST": # ensure username was submitted if not request.form.get("username"): return apology("Must provide username") # ensure password was submitted elif not request.form.get("password"): return apology("Must provide password") # ensure password and verified password is the same elif request.form.get("password") != request.form.get("passwordagain"): return apology("password doesn't match") # insert the new user into users, storing the hash of the user's password result = db.execute("INSERT INTO users (username, hash) \ VALUES(:username, :hash)", \ username=request.form.get("username"), \ hash=pwd_context.encrypt(request.form.get("password"))) if not result: return apology("Username already exist") # remember which user has logged in session["user_id"] = result # redirect user to home page return redirect(url_for("index")) else: return render_template("register.html")
def create_library(self, name, callback=None): library_id = base64.b32encode( uuid.uuid4().bytes[0:8]).strip("=").lower() library_key = base64.urlsafe_b64encode(hashlib.sha512( uuid.uuid4().bytes + uuid.uuid4().bytes).digest())[:-2] library_data = { "libraryId": library_id, "name": name, "keyHash":pwd_context.encrypt(library_key) } # Check to make sure the library ID is not currently in use response = yield gen.Task(self._get_file, library_id + "/dist.json") if response.code == 200: callback({"error": 500}) # All clear, create the new library response = yield gen.Task(self._put_file, library_id + "/dist.json", json.dumps(library_data)) if response.code != 200: callback({"error": response.code}) else: # Return the unencrypted key the first time library_data["key"] = library_key callback(library_data)
def login(self): userpw = wx.GetPasswordFromUser('Enter root password', 'Root Password') loggedin = False if not isUserSet(): conf = wx.GetPasswordFromUser('Please confirm root password', 'Root Password') while conf != userpw: print 'Passwords do not match' userpw = wx.GetPasswordFromUser('Enter root password', 'Root Password') conf = wx.GetPasswordFromUser('Please confirm root password', 'Root Password') print 'Initializing user' password = pwd_context.encrypt(userpw) setUser(password) return True else: tries = 2 while not loggedin: loggedin = pwd_context.verify(userpw, getUser()) if not loggedin: print 'Wrong password' userpw = wx.GetPasswordFromUser('Enter root password', 'Root Password') tries -=1 if tries == 0: self.ResetApplication() return False return True
def hash_password(password): """ Hash the user's password :param str password: The password to hash :return: """ return pwd_context.encrypt(password)
def add_user(cls, account=None, passwd=None): app.logger.debug("add user start:[%s,%s]" % (account, passwd)) # check if account has register result_find = user_collection.find_one({'account': account}) if result_find: db_passwd_hash = result_find.get('passwd_hash') user_id = result_find.get('_id') s = Serializer(app.config['SECRET_KEY'], expires_in=6000) # 3600000=41 days token = s.dumps({'user_id': '%s' % user_id, 'passwd': db_passwd_hash}) app.logger.debug("user exsit [account:%s]:[user_id:%s]:[%s]\n" % (account, user_id, token)) return token, str(user_id) # generate token user_id = str(redis_db.incr(CURRENT_USER_ID)) s = Serializer(app.config['SECRET_KEY'], expires_in=6000) # 3600000=41 days token = s.dumps({'user_id': '%s' % user_id, 'passwd': passwd}) # save account/passwd to mongodb passwd_hash = pwd_context.encrypt(passwd) one_user = {'_id': user_id, 'account': account, 'passwd_hash': passwd_hash} # user_obj_id = user_db.user_collection.insert_one(one_user).inserted_id user_obj_id = user_db.user_collection.insert_one(one_user).inserted_id # save token to redis redis_db.set(str(user_id), token) # save user to easemob platform im_obj.register_user(user_id, user_id) app.logger.debug("add user [%s]:[%s]:[%s]:%s]" % (account, passwd_hash, token, user_id)) return token, str(user_id)
def change_password(username, old_password, new_password): user = check_login(username, old_password) if user is None: return False user.hashed = custom_app_context.encrypt(new_password) user.save() return True
def main(): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-f', '--force', action='store_true', help='Force locking even for root user') parser.add_argument('-p', '--passwd', action='store_true', help='Set/change the password') parser.add_argument('--no-hide-cursor', action='store_true', help="Don't hide the mouse pointer.") args = parser.parse_args() if args.passwd: pass1 = getpass.getpass('new password: '******'confirm new password: '******'Passwords didn\'t match') else: hash = pwd_context.encrypt(pass1) if not os.path.exists(os.path.dirname(PASSWD_FILE)): os.makedirs(os.path.dirname(PASSWD_FILE)) with open(PASSWD_FILE, 'w', encoding='ASCII') as out: out.write(hash) exit(0) else: if getpass.getuser() == 'root' and not args.force: panic("pyxtrlock: refusing to run as root. Use -f to force.") if not os.path.exists(PASSWD_FILE): panic("pyxtrlock: refusing to run, no password has been set.") lock_screen(not args.no_hide_cursor)
def register(cls, username, password, email=None, confirmed=False, roles=None): """ Create a new user account. :param email: the email address used to identify the account :type email: string :param password: the plaintext password for the account :type password: string :param confirmed: whether to confirm the account immediately :type confirmed: boolean :param roles: a list containing the names of the Roles for this User :type roles: list(string) """ new_user = cls( username=username, email=email, password=pwd_context.encrypt(password), confirmed=confirmed, ) db.session.add(new_user) db.session.commit() if confirmed: new_user.confirm() if roles: for role_name in roles: new_user.add_role(role_name) flask.current_app.logger.debug("Created user {0}".format(username)) return new_user
def route_passwd(): checklogout() uid = checksesval() if uid is None: return u"error: et ole kirjautunut sisään", 400 if request.method == 'POST': if "new" not in request.form or len(request.form["new"]) < 6: flash(u"Uusi salasana ei täyttänyt vaatimuksia") return redirect("/passwd") c.execute(("SELECT * FROM sanotut_users " "WHERE email = (%s)"), (session["email"],)) res = c.fetchone() if res == None or not pwd_context.verify(request.form.get("old", ""), res[2]): flash(u"Vanha salasana väärin") return redirect("/passwd") c.execute("UPDATE sanotut_users SET password = (%s) WHERE id = (%s)", (pwd_context.encrypt(request.form["new"]), uid)) db.commit() flash(u"Salasana vaihdettu.") return redirect("/") return render("passwd.html")
def register(): """Register user.""" if request.method == "POST": if not request.form.get("username"): return apology("must enter username") elif not request.form.get("password") or not request.form.get("Repeat Password"): return apology("must enter password") elif request.form.get("password") != request.form.get("Repeat Password"): return apology("passwords must match") # Hash the given password password_hash = pwd_context.encrypt(request.form.get("password")) # Register the user in the database username = request.form.get("username") result = DB.execute( "INSERT INTO users (username, hash) VALUES (:username, :password_hash)", (username, password_hash)) CONN.commit() if not result: return apology("username already taken") # Log in automatically # session["user_id"] return redirect(url_for("index")) else: return render_template("register.html")
def change_password(self,old,new): if pwd_context.verify(old, self.Password): self.Password=pwd_context.encrypt(new) self.save() return True else: return False
def route_register(): checklogout() if request.method == 'POST': if "email" not in request.form or not validemail(request.form["email"]): flash(u"Sähköposti ei vastaa vaadittua kaavaa!") return redirect("/register") if "password" not in request.form or len(request.form["password"]) < 6: flash(u"Salasanasi tulee olla yli viisi merkkiä!") return redirect("/register") hash = pwd_context.encrypt(request.form["password"]) try: c.execute(("INSERT INTO sanotut_users " "(email, password) " "VALUES (%s, %s)"), (request.form["email"], hash,)) except Exception: flash(u"Tuo sposti on rekisteröity jo!") return redirect("/register") db.commit() flash(u"Voit nyt kirjautua sisään!") return redirect("/login", name="login") return render("register.html", name="register")
def signup_page(): if request.method == 'POST': nameSurname=request.form['inputNameSurname'] username=request.form['inputUsername'] email=request.form['inputEmail'] password=request.form['inputPassword'] hashed = pwd_context.encrypt(password) with dbapi2.connect(app.config['dsn']) as connection: cursor = connection.cursor() query = """INSERT INTO USERS (NAME, USERNAME, MAIL, PASSWORD) VALUES ('%s', '%s', '%s', '%s')""" %(nameSurname,username,email,hashed) cursor.execute(query) user = User(nameSurname, username,email,hashed) connection.commit() with dbapi2.connect(app.config['dsn']) as connection: cursor = connection.cursor() query = """INSERT INTO INFO (USERNAME, SURNAME, AGE, COUNTRY,CITY,GENDER) VALUES ('%s','%s', '%s', '%s', '%s', '%s')""" %(username,'........','........','........','........','........') cursor.execute(query) connection.commit() login_user(user) return redirect(url_for('site.main_page')) else: return render_template('signup.html') return render_template('signup.html')
def init_table(target, connection, **kw): print("Init table User") first_user = User('admin') first_user.isroot = True first_user.password = pwd_context.encrypt("liotyph") db_session.add(first_user) db_session.commit()
def add_one_new_user( users, form ): # Validate presense of all inputs if ( 'username' in form.keys() and 'password' in form.keys() and 'role' in form.keys() ): username = form['username'] password = form['password'] role = form['role'] # Validate individual input if ( username != None and password != None and role != None ): if users.find( { 'username' : form['username'] } ).count() == 0: # Insert obj_id = users.insert_one( { 'username' : username, 'password_hash' : pwd.encrypt( password ), 'role' : role } ) return username pass else: # Error: username exists abort( 405 ) pass pass else: # Error: username, password and role, at least one None abort( 400 ) pass else: # Error: username, password and role, all three not provided abort( 400 ) pass pass
def update_existing_user( users, username, form ): if users.find( { 'username' : username } ).count() == 0: # Error: username not registered abort( 404 ) pass else: updates_performed = dict() if 'password' in form.keys(): password = form['password'] if password != None: result = users.update_one( { 'username' : username }, { '$set' : { 'password_hash' : pwd.encrypt( password ) } } ) updates_performed.update( { 'password' : 'hashed' } ) else: # Error: password field is None abort( 400 ) pass pass if 'role' in form.keys(): role = form['role'] if role != None: result = users.update_one( { 'username' : username }, { '$set' : { 'role' : role } } ) updates_performed.update( { 'role' : role } ) else: # Error: role field is None abort(400 ) pass pass return { 'Parameters Updated' : updates_performed } pass pass
def signup(): form = SignupForm() try: name = form.n_name.data username = form.n_username.data password = form.n_password.data hash_password = pwd_context.encrypt(password) # validate the received values if name and username and password: query = models.User(name=name, username=username, password=hash_password) try: db.session.add(query) db.session.commit() db.session.close() return json.dumps({"message": "user created successfully!"}) except Exception as e: return "Error: Could not create user " + str(e) else: return json.dumps({"html": "<span>Enter the required fields</span>"}) # return render_template('signup.html') except Exception as e: return json.dumps({"line 66 : error": str(e)})
def default_adminpassword(): """Return hashed and salted default administrator password. Passwords here and following functions are sha512 encrypted. """ from passlib.apps import custom_app_context as pwd_context return pwd_context.encrypt("admin", category="admin")
def POST(self): i = web.input() accountinfo = json.loads(i.data) username = accountinfo['username'] password = accountinfo['password'] passwordhash = pwd_context.encrypt(password) with connection() as conn: if not "@" in username: queryString = r.db(RDB_CONFIG['db']).table(tables['users']).filter(r.row['username'] == username) else: queryString = r.db(RDB_CONFIG['db']).table(tables['users']).filter(r.row['email'] == username) findAccount = list(queryString.run(conn)) returndata = {} if(len(findAccount) == 1): for index,item in enumerate(findAccount): ok = pwd_context.verify(password, item['password']) if(ok): returndata['userdata'] = {} returndata['userdata']['id'] = item['id'] returndata['userdata']['username'] = item['username'] returndata['userdata']['email'] = item['email'] returndata['success'] = True else: returndata['error'] = {} returndata['error']['message'] = 'There was a problem logging in, password or username didn\'t match.' returndata['success'] = False else: returndata['success'] = False returndata['message'] = {} returndata['error'] = {} returndata['error']['message'] = 'I\'m sorry, we cannot find an account with that username'; return json.dumps(returndata)
def set_password(self, password): """Encrypt the User password. Arguments: password: [String] string Representing the User password """ self.password_hash = pwd_context.encrypt(password)
def post(self): user = json.loads(self.request.body) pwd = user["pass_word"] hash = pwd_context.encrypt(pwd) select_user_name = """SELECT `user_name` FROM `User` WHERE `user_name` = "%s" """\ % (user["user_name"]) result = self.application.db.get(select_user_name) if result is not None: self.write({"success": "username"}) self.finish() return select_user_email = """SELECT `user_email` FROM `User` WHERE `user_email` = "%s" """\ % (user["user_email"]) result = self.application.db.get(select_user_email) if result is not None: self.write({"success": "useremail"}) self.finish() return if result is None: add_user_info = """INSERT INTO `User` (`user_name`, `user_email`, `first_name`, `last_name`, `password`) VALUES ("%s", "%s", "%s","%s","%s")"""\ % (user["user_name"], user["user_email"], user["first_name"], user["last_name"], hash) result = self.application.db.execute(add_user_info) self.write({"success": "true"}) user["pass_word"] = "hidden" self.set_secure_cookie("bwitter", tornado.escape.json_encode(user)) self.finish() else: self.finish()
def generate_config(hass, passwd): """Generate a configuration based on current Home Assistant instance.""" config = { "listeners": { "default": {"max-connections": 50000, "bind": "0.0.0.0:1883", "type": "tcp"}, "ws-1": {"bind": "0.0.0.0:8080", "type": "ws"}, }, "auth": {"allow-anonymous": hass.config.api.api_password is None}, "plugins": ["auth_anonymous"], } if hass.config.api.api_password: username = "******" password = hass.config.api.api_password # Encrypt with what hbmqtt uses to verify from passlib.apps import custom_app_context passwd.write( "homeassistant:{}\n".format(custom_app_context.encrypt(hass.config.api.api_password)).encode("utf-8") ) passwd.flush() config["auth"]["password-file"] = passwd.name config["plugins"].append("auth_file") else: username = None password = None client_config = ("localhost", 1883, username, password, None, PROTOCOL_311) return config, client_config
def private_profile(): """ The settings page for current_user. Here current_user may toggle suggestions, private, delete or report names, change about & photo with a shoddy ChangeDetailsForm, change password with an acceptable ChangePasswordForm, or permanently delete the account. :return: profile.html rendered with list of suggested names for current_user amd forms """ names = Name.query.filter_by(userID=current_user.get_id()).all() # TODO: implement a new form to change account details you lazy trashbag form_d = ChangeDetailsForm(csrf_enabled=False) form_p = ChangePasswordForm() if form_p.validate_on_submit(): if pwd_context.verify(form_p.current_password.data, current_user.password): user = User.query.get(current_user.id) user.password = pwd_context.encrypt(form_p.new_password.data) db.session.commit() flash("Changes saved.") return redirect(url_for("private_profile")) else: flash("Incorrect password.") return redirect(url_for("private_profile")) if form_d.validate_on_submit(): user = User.query.get(current_user.id) if form_d.about.data != "": user.about = form_d.about.data app.logger.debug("result: "+user.about) if form_d.url.data != "": user.photo_url = form_d.url.data db.session.commit() flash("Changes saved.") return redirect(url_for("private_profile")) return render_template("profile.html", names=names, form_d=form_d, form_p=form_p)
def __init__(self, name, email, password): #TODO check for valid email address #TODO check for valid password? self.id = str(uuid.uuid4()) self.name = name self.email = email self.hashed_password = pw_context.encrypt(password)
def hash_password(cls, password: str): """Static method to hash a password""" return pwd_context.encrypt(password)
def hash_password(self, password): self.password_hash = pwd_context.encrypt(password)
def new_user(request): """New User form.""" username = password = password_verify = first_name = '' last_name = phone_number = email = error = message = '' if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] password_verify = request.POST['password_verify'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] phone_number = request.POST['phone_number'] email = request.POST['email'] try: query = request.dbsession.query(Users) result = query.filter_by(username=username).first() except DBAPIError: # pragma: no cover return Response(db_err_msg, content_type='text/plain', status=500) if result: message = 'User "{}" already exists.'.format(username) else: if username != '' and password != '' and password_verify != ''\ and first_name != '' and last_name != '' and email != '': if (password == password_verify) and (len(password) > 6): message = "good job, you can enter info" date_joined = datetime.datetime.now() date_last_logged = datetime.datetime.now() new = Users( username=username, first_name=first_name, last_name=last_name, email=email, email_verified=False, date_joined=date_joined, date_last_logged=date_last_logged, pass_hash=pwd_context.encrypt(password), phone_number=phone_number, phone_number_verified=False, active=True, password_last_changed=datetime.datetime.now(), password_expired=False, is_admin=0, ) request.dbsession.add(new) headers = remember(request, username) return HTTPFound(location=request.route_url('search'), headers=headers) else: error = 'Passwords do not match or password'\ ' is less than 6 characters' else: error = 'Missing Required Fields' return { 'error': error, 'username': username, 'first_name': first_name, 'last_name': last_name, 'phone_number': phone_number, 'email': email, 'message': message }
def password(self, password): self.password_hash = custom_app_context.encrypt(password)
def hash_password(self, password): """ 密码散列 :param password: 明文密码 """ self.password_hash = pwd_context.encrypt(password)
def hash_password(self, password): """Create password hash from password string""" self.password_hash = pwd_context.encrypt(password)
def initialize_database(): with dbapi2.connect(app.config['dsn']) as connection: cursor = connection.cursor() query = """DROP TABLE IF EXISTS USERDB CASCADE""" cursor.execute(query) query = """CREATE TABLE USERDB (ID SERIAL PRIMARY KEY, NAME VARCHAR(40) NOT NULL, REALNAME VARCHAR(50) NOT NULL,NUMBER BIGINT, EMAIL VARCHAR(50), PSW VARCHAR(200), LEVEL INTEGER DEFAULT 0) """ cursor.execute(query) query = """INSERT INTO USERDB(NAME,REALNAME,PSW,LEVEL) VALUES(%s, %s, %s, %s) """ cursor.execute(query, ( 'admin', 'Admin', pwd_context.encrypt('admin'), 1, )) query = """INSERT INTO USERDB(NAME,REALNAME,PSW,NUMBER,EMAIL) VALUES(%s, %s, %s, %s, %s) """ cursor.execute(query, ( 'koray', 'Bulent Koray Oz', pwd_context.encrypt('123'), 12345, '*****@*****.**', )) query = """INSERT INTO USERDB(NAME,REALNAME,PSW,NUMBER,EMAIL) VALUES(%s, %s, %s, %s, %s) """ cursor.execute(query, ( 'turgut', 'Turgut Can Aydinalev', pwd_context.encrypt('123'), 12345, '*****@*****.**', )) query = """INSERT INTO USERDB(NAME,REALNAME,PSW,NUMBER,EMAIL) VALUES(%s, %s, %s, %s, %s) """ cursor.execute(query, ( 'beste', 'Beste Burcu Bayhan', pwd_context.encrypt('123'), 12345, '*****@*****.**', )) query = """DROP TABLE IF EXISTS CLUBDB CASCADE""" cursor.execute(query) query = """ CREATE TABLE CLUBDB (ID SERIAL PRIMARY KEY, NAME VARCHAR(40) NOT NULL, TYPE VARCHAR(40) NOT NULL, EXP VARCHAR(2000), ACTIVE INTEGER DEFAULT 0, CM INT REFERENCES USERDB(ID) ) """ cursor.execute(query) query = """DROP TABLE IF EXISTS CLUBMEM CASCADE""" cursor.execute(query) query = """CREATE TABLE CLUBMEM (ID SERIAL PRIMARY KEY,CLUBID INT REFERENCES CLUBDB(ID) ON DELETE CASCADE, USERID INT REFERENCES USERDB(ID), LEVEL INTEGER DEFAULT 0)""" cursor.execute(query) connection.commit() query = """DROP TABLE IF EXISTS SOCMED CASCADE""" cursor.execute(query) query = """CREATE TABLE SOCMED (ID SERIAL PRIMARY KEY,CLUBID INT REFERENCES CLUBDB(ID) ON DELETE CASCADE, TYPESOC VARCHAR(20), LINK VARCHAR(100))""" cursor.execute(query) connection.commit() query = """DROP TABLE IF EXISTS APPTAB CASCADE""" cursor.execute(query) query = """CREATE TABLE APPTAB(ID SERIAL PRIMARY KEY,CLUBID INT REFERENCES CLUBDB(ID) ON DELETE CASCADE, USERID INT REFERENCES USERDB(ID))""" cursor.execute(query) connection.commit() query = """DROP TABLE IF EXISTS EVENT CASCADE""" cursor.execute(query) query = """ CREATE TABLE EVENT (ID SERIAL PRIMARY KEY, CLUBID INT REFERENCES CLUBDB(ID) ON DELETE CASCADE, NAME VARCHAR(40) NOT NULL, EXP VARCHAR(200), DATE TIMESTAMP NOT NULL, LOCATION VARCHAR(20)) """ cursor.execute(query) connection.commit() query = """DROP TABLE IF EXISTS BALANCE CASCADE""" cursor.execute(query) query = """ CREATE TABLE BALANCE (ID SERIAL PRIMARY KEY, CLUBID INT REFERENCES CLUBDB(ID) ON DELETE CASCADE ,AMOUNT FLOAT NOT NULL, EXPL VARCHAR(200)) """ cursor.execute(query) query = """DROP TABLE IF EXISTS INVENTORY CASCADE""" cursor.execute(query) query = """ CREATE TABLE INVENTORY (ID SERIAL PRIMARY KEY, CLUBID INT REFERENCES CLUBDB(ID) ON DELETE CASCADE, INAME VARCHAR(80) NOT NULL, USERNAMEID INTEGER REFERENCES USERDB(ID),PRICE INTEGER, AVAILABLE INTEGER DEFAULT 0)""" cursor.execute(query) query = """DROP TABLE IF EXISTS NOTICE CASCADE""" cursor.execute(query) query = """ CREATE TABLE NOTICE (ID SERIAL PRIMARY KEY, CLUBID INT REFERENCES CLUBDB(ID) ON DELETE CASCADE, TITLE VARCHAR(80) NOT NULL, EXP VARCHAR(200), DATE TIMESTAMP NOT NULL)""" cursor.execute(query) query = """DROP TABLE IF EXISTS MESSAGE CASCADE""" cursor.execute(query) query = """ CREATE TABLE MESSAGE (ID SERIAL PRIMARY KEY, USERID INT REFERENCES USERDB(ID), CLUBID INT REFERENCES CLUBDB(ID) ON DELETE CASCADE, DATE TIMESTAMP NOT NULL, MSG VARCHAR(160), DIR BOOLEAN) """ cursor.execute(query) query = """ INSERT INTO USERDB(NAME,REALNAME,NUMBER,EMAIL,PSW,LEVEL) VALUES ('ceyda', 'Ceyda Aladag', 123456, '*****@*****.**', '$6$rounds=656000$2pciOKNmxUaBMP9o$E/9Gs1CKiuCE9wtqxOr3kQskYyhm52BzHyZz5QG3qFjuHxcKo3LUsq77sK/fSc5JG5hcXTqiMS/saAyKBFEuh.', 0); INSERT INTO USERDB(NAME,REALNAME,NUMBER,EMAIL,PSW,LEVEL) VALUES ('melis', 'Melis Gulenay', 4123, '*****@*****.**', '$6$rounds=656000$ndu2sy9DMg5bVp1D$uPIOHBTnMWBjAjI4PuendQeYY5tNS7RcCfLSpaGxdxXBBcojaK07bMilkSXFC4qx7IqH1IgbcoelFYurcH.JS0', 0); INSERT INTO USERDB(NAME,REALNAME,NUMBER,EMAIL,PSW,LEVEL) VALUES ('mert', 'Mert Kartaltepe', 4125, '*****@*****.**', '$6$rounds=656000$yi1XAGdkPXFN/S8x$Rayqxk8A7lmsrz/ScCkUn2zBHBd2wxtjpZ3aYBCAPo5WHLmjIyTHUf0oyeLtqys8TdWlSHxgu2zlwFpD.a.G4.', 0); INSERT INTO CLUBDB(NAME,TYPE,EXP,ACTIVE,CM) VALUES ('E-sport Kulubu', 'Sport', 'Online oyun sporlari', 1, 3); INSERT INTO CLUBDB(NAME,TYPE,EXP,ACTIVE,CM) VALUES ('Felsefe Kulubu', 'Culture/Art', 'Felsefi akim tartismalari', 1, 4); INSERT INTO CLUBDB(NAME,TYPE,EXP,ACTIVE,CM) VALUES ('Paten Kulubu', 'Sport', 'Tekerlekli patenle yapilan tum sporlar', 1, 2); INSERT INTO CLUBDB(NAME,TYPE,EXP,ACTIVE,CM) VALUES ('Bilisim Kulubu', 'Profession', 'Turkiye''de bilisim teknolojisi bilincinin arttirilmasi uzerine calismalar', 1, 7); INSERT INTO APPTAB(CLUBID,USERID) VALUES (1, 4); INSERT INTO APPTAB(CLUBID,USERID) VALUES (1, 5); INSERT INTO CLUBMEM(CLUBID,USERID,LEVEL) VALUES (1, 3, 1); INSERT INTO CLUBMEM(CLUBID,USERID,LEVEL) VALUES (2, 4, 1); INSERT INTO CLUBMEM(CLUBID,USERID,LEVEL) VALUES (3, 2, 1); INSERT INTO CLUBMEM(CLUBID,USERID,LEVEL) VALUES (1, 2, 3); INSERT INTO CLUBMEM(CLUBID,USERID,LEVEL) VALUES (1, 6, 0); INSERT INTO CLUBMEM(CLUBID,USERID,LEVEL) VALUES (1, 7, 4); INSERT INTO CLUBMEM(CLUBID,USERID,LEVEL) VALUES (4, 7, 1); INSERT INTO CLUBMEM(CLUBID,USERID,LEVEL) VALUES (3, 3, 0); INSERT INTO EVENT(CLUBID,NAME,EXP,DATE,LOCATION) VALUES (1, 'Hearthstone Turnuvasi', 'Odullu Hearthstone turnuvasi', '2017-12-29 20:00:00', 'MED'); INSERT INTO EVENT(CLUBID,NAME,EXP,DATE,LOCATION) VALUES (2, 'Platon Hakkinda', 'Eserleri hakkinda tartisma', '2017-12-24 18:00:00', 'FEB'); INSERT INTO EVENT(CLUBID,NAME,EXP,DATE,LOCATION) VALUES (3, 'Inline Hokey Maci', 'Hazirlik karsilasmasi', '2017-12-26 19:00:00', 'Spor Salonu'); INSERT INTO SOCMED(CLUBID,TYPESOC,LINK) VALUES (2, 'Facebook', 'facebook.com/felsefeitu'); INSERT INTO SOCMED(CLUBID,TYPESOC,LINK) VALUES (1, 'Twitter', 'twitter.com/esporitu'); INSERT INTO SOCMED(CLUBID,TYPESOC,LINK) VALUES (1, 'Facebook', 'facebook.com/esporitu'); INSERT INTO MESSAGE(USERID, CLUBID, DATE, MSG, DIR) VALUES (2, 1, '2017-10-22 18:00:00', 'etkinlige en gec kacta gelebiliriz ogrenebilir miyim?', true); INSERT INTO MESSAGE(USERID, CLUBID, DATE, MSG, DIR) VALUES (2, 1, '2017-10-22 19:00:00', 'oglen 12 de', false); INSERT INTO MESSAGE(USERID, CLUBID, DATE, MSG, DIR) VALUES (2, 2, '2017-10-22 19:00:00', 'selam', true); INSERT INTO MESSAGE(USERID, CLUBID, DATE, MSG, DIR) VALUES (2, 2, '2017-10-22 18:00:00', 'selam hocam', false); """ cursor.execute(query) connection.commit() flash("Database initialized.") return redirect(url_for('link1.home_page'))
def hash_password(self, password): self.password_hash = pwd_security.encrypt(password)
def __init__(self, email, password): self.email = email self.password = pwd_context.encrypt(password)
def hash_senha(self, password): self.senha_hash = custom_app_context.encrypt(password)
def set_password(self, pwd): pwd_hash = pwd_context.encrypt(pwd, category='admin') self.password_hash = pwd_hash
def hash_password(self, password): if password: self.password = pwd_context.encrypt(password)
def check_password(password): """Varify password matches hashed password.""" hashed = pwd_context.encrypt(os.environ.get('PASSWORD')) return pwd_context.verify(password, hashed)
def encrypt_password(self, password): self.password = pwd_context.encrypt(password)
def register(): session.clear() # logout user (clear session) TODO if request.method == 'POST': # connects to database db = get_db() #flag used to check if all entered data is valid register_form_valid = 1 #checks that username is valid and not duplicate (a-z, A-Z, 0-9, _ - 1-15 letters) if (len(request.form.get('username')) < 1): register_form_valid = 0 flash("No username entered") else: if not re.match("^[A-Za-z0-9_-]*$", request.form.get('username')): register_form_valid = 0 flash("Username contains unallowed characters") if (len(request.form.get('username')) > 15): register_form_valid = 0 flash("Username longer than 15 characters") if (db.execute( """SELECT EXISTS(SELECT 1 FROM users WHERE username=:username LIMIT 1);""", { 'username': request.form.get('username') }).fetchone()[0]): register_form_valid = 0 flash("Username already taken") #checks that password is valid if (not request.form.get('password')): register_form_valid = 0 flash("No password entered") else: if (len(request.form.get('password')) < 5): register_form_valid = 0 flash("Password is less than 5 characters") elif (len(request.form.get('password')) > 26): register_form_valid = 0 flash("Password is more than 26 characters") if not re.match("^[A-Za-z0-9_-]*$", request.form.get('password')): register_form_valid = 0 flash("Password contains unallowed characters") if (not request.form.get('passwordConfirmation')): register_form_valid = 0 flash("No password confirmation entered") elif (request.form.get('password') != request.form.get('passwordConfirmation')): register_form_valid = 0 flash("Passwords do not match") if register_form_valid: #create hash for password hash = pwd_context.encrypt(request.form.get('password')) #inserts the dataset in the database query = ("""INSERT INTO users (username,hash) VALUES(:username,:hash)""") db.execute(query, { 'username': request.form.get('username'), 'hash': hash }) db.commit() flash('Success!') return redirect(url_for('login')) #return to login page return render_template('register.html')
def post(self): """Reset a user's password --- tags: - auth parameters: - in: body name: body description: Old password and new user password type: string schema: id: change-password properties: username: default: kevin email: default: [email protected] responses: 201: description: successfully changed the password 400: description: Bad request. Wrong details, missing parameters and invalid passwords """ request_dict = request.get_json() if not request_dict: resp = {'error': 'No input data provided'} return resp, status.HTTP_400_BAD_REQUEST try: email = request_dict['email'] except Exception: response = {"error": 'Missing field'} return response, status.HTTP_400_BAD_REQUEST user = User.query.filter_by(email=email).first() if not user: return {'error': "Invalid email"}, 400 chars = string.ascii_uppercase + string.ascii_lowercase + string.digits new_password = ''.join(random.choice(chars) for i in range(8)) user.hashed_password = password_context.encrypt(new_password) user.update() try: msg = Message("Password Reset, Yummy Recipes", sender="Admin", recipients=[email]) msg.html = "<h1>Hello," + user.username + "</h1>" \ "<p>Your password has been reset to: " + '<strong>' + new_password + '</strong>' + "</p>" \ "<p> Make sure to change your password " \ "on Login</p>" \ "<p> \n\nCheers, Kevin Samoei </p>" with app_context: mail.send(msg) return {"message": 'Password Reset successful. Mail sent! Check email'}, 200 except Exception as e: return {"error": str(e)}, 400
def register(): """Register user.""" # forget any user_id session.clear() # if user reached route via POST (as by submitting a form via POST) if request.method == "POST": # ensure username was submitted if not request.form.get("username"): return apology("must provide username") # ensure password was submitted elif not request.form.get("password"): return apology("must provide password") # ensure password was entered again elif not request.form.get("password1"): return apology("must re-enter password") # ensure that the passwords match if request.form.get("password") != request.form.get("password1"): return apology("Passwords doesn't match!") # query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) # ensure username is available if len(rows) == 1: return apology("Sorry, username already taken.") # insert data into the database user = db.execute("INSERT INTO users ( username, hash ) VALUES( :username, :pwhash )", username = request.form.get("username"), pwhash = pwd_context.encrypt(request.form.get("password"))) # remember which user has logged in session["user_id"] = user # redirect user to home page return redirect(url_for("index")) # else if user reached route via GET (as by clicking a link or via redirect) else: return render_template("register.html")
def hash_password(self): self.tmp = pwd_context.encrypt(self.password) return self.tmp
def __init__(self, name, password): self.name = name self.password = pwd.encrypt(password) session.add(self) session.commit()
def hash(self, password): # ENCRYPTAR LA CONTRASEÑA. self.password_hashed = pwd_context.encrypt(password)
def hash_password(self, password): """ Хэширует пароль пользователья при регистрации :param password: пароль пользователя из конструктора """ self.password_hash = pwd_context.encrypt(password)
def hash_password(self, password): return pwd_context.encrypt(password)
def hash_password(self, facebook_id): self.token = pwd_context.encrypt(facebook_id)
def set_password(self, password): self.pwd = pwd_context.encrypt(password) return
def set_pass(self, password): '''Set the password hash from a cleartext password.''' self.expire_sessions() self.phash = custom_app_context.encrypt(password) self.save()
def set_password(self, password): password_hash = blogger_pwd_context.encrypt(password) self.password = password_hash
def __init__(self, username, password, role=None): self.id = generate_uuid() self.username = username self.password_hashed = pwd_context.encrypt(password) self.last_connection_date = generate_date() if role: self.role = role
def hash_password(self, password): self.password = custom_app_context.encrypt(password)
def hash_password(self, password): #It stores a hash of it with the user: self.password_hash = pwd_context.encrypt(password)
def passwordF(self, password): self.password=pwd_context.encrypt(password)