def create(cls, db, graph, raw_view_pass, raw_edit_pass): if raw_view_pass is not None: view_pass = bcrypt.hashpw( raw_view_pass.encode(), bcrypt.gensalt()).decode() else: view_pass = None if raw_edit_pass is not None: edit_pass = bcrypt.hashpw( raw_edit_pass.encode(), bcrypt.gensalt()).decode() else: edit_pass = None result = db.execute('select count(*) from polycules where graph = ?', [graph]) existing = result.fetchone()[0] if existing != 0: raise Polycule.IdenticalGraph cur = db.cursor() result = cur.execute('''insert into polycules (graph, view_pass, delete_pass, hash) values (?, ?, ?, ?)''', [ graph, view_pass, edit_pass, hashlib.sha1(graph.encode('utf-8')).hexdigest(), ]) db.commit() new_hash = db.execute('select hash from polycules where id = ?', [ result.lastrowid ]).fetchone()[0] return Polycule.get(db, new_hash, None, force=True)
def login(self, first_name, last_name, email_address, password, confirm_password): errors = [] errors.append(self.validate_length(first_name, 'first_name', 2, "First name is too short")) errors.append(self.validate_length(last_name, 'last_name', 2, "Last name is too short")) errors.append(self.password_match(password, confirm_password)) errors.append(self.validate_email(email_address)) error = [] print errors for elements in range(0, len(errors)): try: errors[elements][1] error.append(errors[elements][1]) except: pass error2 = {} for d in error: error2.update(d) if not bool(error2): user_level = 0 records = Register.objects.all(); try: records[0] except: user_level = 9 pw_bytes = password.encode('utf-8') hashed = bcrypt.hashpw(pw_bytes, bcrypt.gensalt()) Register.objects.create(first_name = first_name, last_name = last_name, password = hashed, email= email_address, salt = bcrypt.gensalt(), user_level = user_level) success = {} success['success'] = "Registeration comeplete, please log in" return (True, success) else: return (False, error2)
def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: print "Creating groups..." DBSession.add(Group(desc=Group.ADMIN)) DBSession.add(Group(desc=Group.GUEST)) DBSession.add(Group(desc=Group.TEACHER)) DBSession.add(Group(desc=Group.STUDENT)) print "Creating guest..." guestgroup = DBSession.query(Group).filter_by(desc=Group.GUEST).first().id guesthash = bcrypt.hashpw('', bcrypt.gensalt()) DBSession.add(User(username=User.GUEST, group=guestgroup, phash=guesthash)) print "Creating superuser..." admingroup = DBSession.query(Group).filter_by(desc=Group.ADMIN).first().id adminpw = getpass.getpass() adminhash = bcrypt.hashpw(adminpw, bcrypt.gensalt()) DBSession.add(User(username=User.ADMIN, group=admingroup, phash=adminhash))
def isValidRegistration(self, userInfo, request): passFlag = True if not userInfo['first_name'].isalpha(): passFlag = False if len(userInfo['first_name']) < 2: passFlag = False if not userInfo['last_name'].isalpha(): passFlag = False if len(userInfo['last_name']) < 2: passFlag = False if not EMAIL_REGEX.match(userInfo['email']): passFlag = False if len(userInfo['password']) < 7: passFlag = False if userInfo['password'] != userInfo['confirm_password']: passFlag = False if User.objects.filter(email = userInfo['email']): passFlag = False if passFlag: if User.userManager.all: status = 1 hashed = bcrypt.hashpw(userInfo['password'].encode(), bcrypt.gensalt()) self.create(first_name = userInfo['first_name'], last_name = userInfo['last_name'], email = userInfo['email'], password = hashed, status=status) else: status = 9 hashed = bcrypt.hashpw(userInfo['password'].encode(), bcrypt.gensalt()) self.create(first_name = userInfo['first_name'], last_name = userInfo['last_name'], email = userInfo['email'], password = hashed, status=status) else: messages.error(request, "Invalid Registration. Please try again.") return passFlag
def setPassword(self, password = None): if not password: return hashed = bcrypt.hashpw(password, bcrypt.gensalt()) self.password = hashed self.token = bcrypt.gensalt() self.save()
def on_post(self, req, resp): doc = req.context['doc'] users=Session.query(User).all() unique=True for user in users: if doc['email'] == user.email: unique=False if unique: user = User(name=doc['name'], email=doc['email'].lower(), signedin=False,registerTime=datetime.datetime.today()) print(datetime.datetime.today()) user.salt = bcrypt.gensalt() user.pw_hash = bcrypt.hashpw(doc['password'].encode('utf-8'), user.salt) s=smtplib.SMTP_SSL('smtp.gmail.com',465) s.ehlo() s.login('*****@*****.**','helloworld@ppclub') code=randint(1000000,10000000) user.code=code msg=MIMEText('Hi '+user.name+', your verification URL is: '+'http://192.168.1.127:8000/confirmation/'+str(code)) msg['From']='*****@*****.**' msg['To']=user.email msg['Subject']='PhoenixNow Account Confirmation' s.send_message(msg) s.close() Session.add(user) Session.flush() Session.commit() req.context['user'] = user.id req.context['result'] = {"result": "success", "action": "register"} else: user=get_user(req,resp) td=datetime.timedelta(minutes=30) if datetime.datetime.today()-td<user.registerTime or user.emailVerified==True: description = "User was already made" title = "User creation conflict" raise falcon.HTTPConflict(title=title, description=description) else: Session.delete(user) Session.flush() user = User(name=doc['name'], email=doc['email'], signedin=False,registerTime=datetime.datetime.today()) print(datetime.datetime.today()) user.salt = bcrypt.gensalt() user.pw_hash = bcrypt.hashpw(doc['password'].encode('utf-8'), user.salt) s=smtplib.SMTP_SSL('smtp.gmail.com',465) s.ehlo() s.login('*****@*****.**','helloworld@ppclub') code=randint(1000000,10000000) user.code=code msg=MIMEText('Hi '+user.name+', your verification URL is: '+'http://192.168.1.127:8000/confirmation/'+str(code)) msg['From']='*****@*****.**' msg['To']=user.email msg['Subject']='PhoenixNow Account Confirmation' s.send_message(msg) s.close() Session.add(user) Session.flush() Session.commit() req.context['user'] = user.id req.context['result'] = {"result": "success", "action": "register"}
def addnewuserprocess(request): errors = False check1 = User.UserManager.first_name(request.POST['first_name']) check1_char = User.UserManager.first_name_charcheck(request.POST['first_name']) check2 = User.UserManager.last_name(request.POST['last_name']) check3 = User.UserManager.reg_email(request.POST['email']) check4 = User.UserManager.password(request.POST['password']) # check5 = User.UserManager.password(request.POST['password']) # check6 = Userlog.UserManager.birthday(request.POST['birthday']) print request.POST['password'] print bcrypt.gensalt() check5 = User.UserManager.confirm_password(request.POST['password'] ,request.POST['confirm_password']) if check1[0] == False: messages.add_message(request, messages.INFO, "Invalid firstname", extra_tags="regtag") errors = True if check1_char[0] == False: messages.add_message(request, messages.INFO, "Invalid characters in firstname", extra_tags="regtag") errors = True if check2[0] == False: messages.add_message(request, messages.INFO, "Invalid lastname", extra_tags="regtag") errors = True if check3[0] == False: messages.add_message(request, messages.INFO, "Invalid Email", extra_tags="regtag") errors = True if check4[0] == False: messages.add_message(request, messages.INFO, "Invalid password", extra_tags="regtag") print check4[1] errors = True if check5[0] == False: messages.add_message(request, messages.INFO, "Passwords don't match", extra_tags="regtag") errors = True # if check6[0] == False: # print check6[1] # messages.add_message(request, messages.INFO, "Invalid BirthDate", extra_tags="regtag") # errors = True # To check DB whether Email already registered or not.... if User.objects.filter(email = request.POST['email']): messages.add_message(request, messages.INFO, "This email already existed!", extra_tags="regtag") errors = True # Errors Route if errors == True: # print "error" * 20 return redirect('/addnewuser') elif check1[0] == True & check2[0] == True & check3[0] == True & check4[0] == True & check5[0] == True : user = User.UserManager.create(first_name=check1[1], last_name=check2[1], email=check3[1], password=check4[1]) print "elif" * 20 request.session['user'] = check1[1] print "*" * 20 if user.id == 1: print user.id print "second" *10 print user.user_level user.user_level = 9 user.save() print user.user_level # messages.add_message(request, messages.INFO, "Successfully Registered", extra_tags="regtag") return redirect('/dashboard')
def bcrypt_hash_method(value, hashed = None): #Package seems broken right now. import bcrypt if hashed is None: hashed = bcrypt.gensalt() try: return bcrypt.hashpw(value.encode('utf-8'), hashed) except ValueError: #Invalid salt return bcrypt.hashpw(value.encode('utf-8'), bcrypt.gensalt())
def get_salt(username): if not g.cursor.execute( "SELECT `salt` FROM `users` WHERE `username` = %s", username): account_salt = bcrypt.gensalt(8) else: account_salt = g.cursor.fetchone()[0] session['SESSION_SALT'] = bcrypt.gensalt(8) return {'account_salt': account_salt, 'session_salt': session['SESSION_SALT']}
def get_sets(): for vals in request.form: data = loads(vals) FIRST_USE = False salts = gensalt(), gensalt() pswds = data["admin"]["pass"], data["security"]["pass"] gkeys = data["admin"]["gpass"], data["security"]["gpass"] db.insert("_users", ["root", hashpw(pswds[0]+gsalt, salts[1]), salts[1], "", "GOODLIKE", ""], "REPLACE") db.insert("_users", ["neo", hashpw(pswds[1]+gsalt, salts[1]), salts[1], "", "JUST BELIEVE THAT U SEE", ""], "REPLACE") db.insert("_gkey", ["root", gkeys[0]], "REPLACE") db.insert("_gkey", ["neo", gkeys[1]], "REPLACE") return jsonify({"data": "ok", "redirect": "/auth"})
def pre_students_post_callback(request): # assert request.path == '/students' # assert request.method == 'POST' print 'pre_students_post_callback' print request.path print request.method print request.get_json()["password"] passwd = request.get_json()["password"] print passwd.encode('utf-8') # print request.data print bcrypt.hashpw(passwd.encode('utf-8'), bcrypt.gensalt()) request.get_json()["password"] = bcrypt.hashpw(passwd.encode('utf-8'), bcrypt.gensalt()) print request.get_json()["password"]
def encrypt_password(password): password = password.encode('ascii') # Java doesn't understand bcrypt 2b yet: # cassandra.AuthenticationFailed: Failed to authenticate to localhost: # code=0000 [Server error] message="java.lang.IllegalArgumentException: # Invalid salt revision" try: salt = bcrypt.gensalt(prefix=b'2a') # Newer versions of bcrypt return a bytestring. return bcrypt.hashpw(password, salt).decode('ascii') except TypeError: # Trusty bcrypt doesn't support prefix= salt = bcrypt.gensalt() return bcrypt.hashpw(password, salt)
def register_user(request): session = DBSession() matchdict = request.matchdict if (request.logged_in): request.session.flash(_("You are already logged in and therefore cannot register for a new account.")) return HTTPFound(location = route_url("home", request)) login_url = route_url('login', request) referrer = request.url if (referrer == login_url): referrer = '/' # never use the login form itself as came_from came_from = request.params.get('came_from', referrer) fs = None if 'submitted' in request.params: fs = RegisterUserFieldSet().bind(User, session = session, data = request.params or None) valid = fs.validate() if valid: user = User() password = bcrypt.hashpw(fs.password1.value, bcrypt.gensalt()) # TODO # Shouldn't have to do this, but doing it for simplicity now user.username = fs.username.value user.password = password user.given_name = fs.given_name.value user.surname = fs.surname.value user.homepage = fs.homepage.value #user.email = fs.email.value user.email = bcrypt.hashpw(fs.email.value, bcrypt.gensalt()) user.created_time = time.time() user.user_type = User.NORMAL session.add(user) session.flush() User.addToGroup(fs.username.value, "nexus") request.session["username"] = fs.username.value headers = remember(request, User.getID(fs.username.value)) request.session.flash(_("You have successfully created a new account!")) return HTTPFound(location = route_url("home", request), headers = headers) if (fs is None): fs = RegisterUserFieldSet().bind(User, session = session) form = fs.render() return dict(form = form, title = _("Register new user"))
def hash_password(password, algorithm, rounds): ''' Hash a password with a chosen algorithm and number of rounds. ''' if algorithm == 'bcrypt': return bcrypt.hashpw(password, bcrypt.gensalt(rounds)) else: raise NotImplementedError("Hash algorithm is unsupported: %s" % algorithm)
def add_user(self): ''' Login validation is missing, we need to write that very soon ''' self.logger.info('Hi, I am in, what now... ') password = self.password.encode('utf-8') ''' Changing the prefix since the node bcrypt package uses 2a, not 2b. ''' hashed = bcrypt.hashpw(password, bcrypt.gensalt(10, prefix=b"2a")) user_db = self.db['users'] self.user_obj = user_db.find_one_and_update( { 'username': self.user, 'club': self.club, }, {'$set': { 'username': self.user, 'club': self.club, 'encryptedPassword': hashed, } }, return_document=ReturnDocument.AFTER, upsert=True) return self.user_obj
def isValidReg(self, userInfo, request): passflag = True password = userInfo['password'] if not EMAIL_REGEX.match(userInfo['email']): passflag = False if len(userInfo['first_name']) < 1: messages.error(request,"First name cannot be empty!") passflag = False if len(userInfo['last_name']) < 1: messages.error(request, "Last Name cannot be empty!") passflag = False if len(userInfo['email']) < 1: messages.error(request, "Email cannot be empty") passflag = False if len(userInfo['password']) < 1: messages.error(request, "Password cannot be empty!" ) passflag = False if len(userInfo['confirm']) < 1: messages.error(request, "Password cannot be empty!") passflag = False if userInfo['password'] != userInfo['confirm']: messages.error(request,"Passwords must match") passflag = False if len(User.objects.filter(email = userInfo['email'])) > 0: messages.error(request, "You already exist") passflag = False #.filter will return an array of user objects if passflag == True: messages.success(request, 'THANKS MAN please login now') hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt()) print hashed User.objects.create(email = userInfo['email'], first_name = userInfo['first_name'], last_name = userInfo ['last_name'], password = hashed) return passflag
def register(request): if request.method == "POST": username = request.POST["username"] userExists = User.objects.filter(username = username) if userExists: print "Pick a different username!" return redirect('/entry') else: name = request.POST["name"] userPassword = request.POST["password"] c_password = request.POST["c_password"] if(len(username) < 2 or len(name) < 2 or len(userPassword) < 8): print("Invalid Info") return redirect('/entry') if(userPassword != c_password): print("Password does not match.") return redirect('/entry') if not'username' in request.session: request.session['username'] = username if not'name' in request.session: request.session['name'] = name if not'password' in request.session: hashed = bcrypt.hashpw(userPassword.encode(), bcrypt.gensalt()) new_user = User.objects.create( username = username, name = name, password = hashed, user_level = 1) print new_user.username print new_user.name print new_user.password print User.objects.all() request.session['user_id'] = new_user.id return redirect('/') return redirect('/entry')
def sign_up_user(user_info): try: cur = database_conn("auth", "auth_db_user", "localhost", "4a9ae88667d0efcb4d596c5516b3fe3bf5a22ab4") # 4a9ae88667d0efcb4d596c5516b3fe3bf5a22ab4 is the SHA1 of "Auth_db_user" # Generated with echo "Auth_db_user" | openssl sha1 # check if the same username or password already exisits cur.execute("SELECT * FROM auth WHERE username='******' OR email='{}';".format(user_info["username"], user_info["email"])) is_already_existing = cur.fetchall() if is_already_existing != []: uname_loc = 1 email_loc = 3 for elem in is_already_existing: if elem[uname_loc] == user_info["username"]: return (False, "Username already taken") if elem[email_loc] == user_info["email"]: return (False, "Email already taken") # store the username, salted password and email password_salted = bcrypt.hashpw(user_info["password"], bcrypt.gensalt()) cur.execute("INSERT INTO auth(username, password_salted, email) VALUES('{}','{}','{}');".format(str(user_info["username"]), str(password_salted), user_info["email"])) cur2 = database_conn("user_info", "user_info_db_user", "localhost", "8487997120e51bb4a83a5b4883f2b7daf80ac14a") # 8487997120e51bb4a83a5b4883f2b7daf80ac14a is the SHA1 of "User_info_db_user" # Generated with echo "User_info_db_user" | openssl sha1 # Join date for metrics cur2.execute("INSERT INTO user_info(join_date) VALUES('{}');".format(time.strftime("%Y/%m/%d"))) return (True, "User signed up") except: return (False, "Unable to establish database connection")
def bcrypt_check_password(raw_pass, stored_hash, extra_salt=None): """ Check to see if this password matches. Args: - raw_pass: user submitted password to check for authenticity. - stored_hash: The hash of the raw password (and possibly extra salt) to check against - extra_salt: (optional) If this password is with stored with a non-database extra salt (probably in the config file) for extra security, factor this into the check. Returns: True or False depending on success. """ if extra_salt: raw_pass = u"%s:%s" % (extra_salt, raw_pass) hashed_pass = bcrypt.hashpw(raw_pass.encode('utf-8'), stored_hash) # Reduce risk of timing attacks by hashing again with a random # number (thx to zooko on this advice, which I hopefully # incorporated right.) # # See also: rand_salt = bcrypt.gensalt(5) randplus_stored_hash = bcrypt.hashpw(stored_hash, rand_salt) randplus_hashed_pass = bcrypt.hashpw(hashed_pass, rand_salt) return randplus_stored_hash == randplus_hashed_pass
def change_password(cls, id_, password, current_password=None): ''' Changes a users password. Set `current_password` to verify the users current password, before changing it. :param id: int :param password: str :param current_password: str :returns: boolean ''' with new_session() as session: if current_password: if not cls.verify_password(id_=id_, password=current_password): return False session.query( models.User, ).filter( models.User.id==id_, ).update({ 'password': bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(10)), }) session.commit() return True
def create_user(): email = flask.request.form['email'] name = flask.request.form['name'] password = flask.request.form['password'] # do the passwords match? error = None if password != flask.request.form['confirm']: error = "Passwords don't match" # is the login ok? if len(email) > 100: error = "E-mail address too long" # search for existing user existing = models.User.query.filter_by(email=email).first() if existing is not None: # oops error = "Username already taken" if error: return flask.render_template('landing.html', error=error) # create user user = models.User() user.email = email user.name = name # hash password user.pw_hash = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt(15)) # save user db.session.add(user) db.session.commit() flask.session['auth_user'] = user.id # It's all good! return flask.redirect(flask.url_for('index'), 303)
def post(self): try: clear = self.get_argument('clear', 0) if clear: model.Banco.objects().delete() model.Categoria.objects().delete() model.Lancamento.objects().delete() pw = self.get_argument('password') us = self.get_argument('user') salt = bcrypt.gensalt() reset = self.get_argument('reset', 1) if reset: model.User.objects().delete() model.Module.objects().delete() model.Permission.objects().delete() user = model.User.objects() if len(user) > 0: raise Exception('ja instalado') hash = bcrypt.hashpw(pw.encode('utf-8'), salt) user = model.User(username=us,password=hash,salt=salt) install.install(user) user.save() self.write('instalacao concluida!') except Exception as err: self.set_status(500) print(err) self.write(str(err))
def generate_password_hash(self, password, rounds=None): '''Generates a password hash using bcrypt. Specifying `rounds` sets the log_rounds parameter of `bcrypt.gensalt()` which determines the complexity of the salt. 12 is the default value. Example usage of :class:`generate_password_hash` might look something like this:: pw_hash = bcrypt.generate_password_hash('secret', 10) :param password: The password to be hashed. :param rounds: The optional number of rounds. ''' if not password: raise ValueError('Password must be non-empty.') if rounds is None: rounds = self._log_rounds if PYVER < 3 and isinstance(password, unicode): password = password.encode('u8') elif PYVER >= 3 and isinstance(password, bytes): password = password.decode('utf-8') password = str(password) return bcrypt.hashpw(password, bcrypt.gensalt(rounds))
def scrypt_test(): start = time.time() hashed = hashlib.sha256(scrypt.hash(password,bcrypt.gensalt(16))).digest() obj =AES.new(hashed,AES.MODE_CBC, 'This is an IV456') end = time.time() ciphertext = obj.encrypt("The answer is no") print "scrypt : ",(end-start)
def register_user(): if all (x in request.form for x in ('username', 'password')): salt = bcrypt.gensalt() password = bcrypt.hashpw(request.form['password'], salt) query = ''' INSERT INTO users VALUES(NULL, :username, :salt, :hash); ''' try: result = db.session.execute(query, { 'username': request.form['username'], 'salt': salt, 'hash': password }) u_id = result.lastrowid key = gen_api_key(request.form['username'], salt) query = ''' INSERT INTO api_keys VALUES (NULL, :u_id, :key) ''' result2 = db.session.execute(query, { 'u_id': u_id, 'key': key }) db.session.commit() session['auth'] = request.form['username'] return '1' except: return '-1' #error in the query... (user exists) else: return '0' #missing post variables!
def createAdmin(db, config): username = input("input admin name: ") password = input("input admin password: "******"username": username, "password": password, "power": 20, "money": config["global"]["init_money"], "time": time.time(), "bookmark": [], "email": "", "qq": "", "website": "", "address": "", "signal": u"太懒,没有留下任何个人说明", "openwebsite": 1, "openqq": 1, "openemail": 1, "allowemail": 1, "logintime": None, "loginip": None } member = db.member member.insert(user)
def post(self): name = self.get_argument('name') passwd = self.get_argument('passwd') email = self.get_argument('email') xxxx = self.get_query_argument('xxxx', '') if not (name and passwd and email): self.render("reg.html", error="信息不完整!") return # 先检查有没有该用户 sql = "SELECT user_uuid FROM site_user WHERE email=%s;" if db_conn.query(sql, email): self.render("reg.html", error="该Email已经被注册!") return passwd_hd = hashpw(passwd.encode(), gensalt()) sql = "INSERT INTO site_user(username, passwd, email, xxxx) VALUES(%s, %s, %s, %s)" db_conn.execute(sql, name, passwd_hd, email, xxxx) # 检测 sql = "SELECT user_uuid, username FROM site_user WHERE email=%s; " rets = db_conn.get(sql, email) if rets: self.render("reg_ok.html", title="readmeinfo - register", info=rets) else: self.render("reg.html", error="失败,请重试!") return
def register(): error = None if request.method == 'POST': # session['username'] = request.form['username'] usermail = request.form["usermail"] mgr = sql #userpass = pbkdf2_sha256.encrypt(request.form["password"], rounds=200000, salt_size=16) userpass = bcrypt.hashpw(request.form["password"], bcrypt.gensalt()) #userpass = request.form["password"] print usermail + " \t " + userpass username = request.form["username"] # baka = sql.login(usermail, userpass) baka = mgr.login(usermail, userpass) baka1 = sql.usernameInDB(username) baka2 = sql.usermailInDB(usermail) print "the bakas!" + baka1 + baka2 print baka if baka1 != "None": print("Login fehlgeschlagen!") if baka2 != "None": print("usermail bereits in datalist") else: baka4 = sql.register(username, usermail, userpass) session['username'] = username #session['sid'] = sessionid #lolz = escape(session['sid']) #mgr.set_session( lolz, usermail, userpass) print "baka4: " + baka4 print("registriert!!") return redirect(url_for('profile')) return render_template('register.html', error=error)
def post(self): data_dict = json.loads(request.data) user = session.get("user") if not user: return abort(404) update_type = data_dict["type"] if update_type == "profile": userid = user["_id"] twitter = data_dict["twitter"] website = data_dict["website"] return cuser.update_profile_info(session, user, twitter, website) elif update_type == "password": userid = user["_id"] user = db.users.find_one({"email": unicode(user['email'])}) if not user: return {'error': 'user not found'}, 404 current_pwd = data_dict["current_pwd"] new_pwd = data_dict["new_pwd"] pwd_hash = user["password"] if bcrypt.hashpw(current_pwd, pwd_hash) != pwd_hash: return {'error': 'password is invalid'}, 404 else: new_pwd_hash = bcrypt.hashpw(new_pwd, bcrypt.gensalt()) db.users.update( {"_id": ObjectId(userid)}, {"$set": {"password": new_pwd_hash}} ) return 200 return 402
def hash_password(password, hashedpw=None): """Hashes password Parameters ---------- password: str Plaintext password hashedpw: str, optional Previously hashed password for bcrypt to pull salt from. If not given, salt generated before hash Returns ------- str Hashed password Notes ----- Relies on bcrypt library to hash passwords, which stores the salt as part of the hashed password. Don't need to actually store the salt because of this. """ # all the encode/decode as a python 3 workaround for bcrypt if hashedpw is None: hashedpw = gensalt() else: hashedpw = hashedpw.encode('utf-8') password = password.encode('utf-8') output = hashpw(password, hashedpw) if isinstance(output, bytes): output = output.decode("utf-8") return output
def hash(value): return bcrypt.hashpw(value.encode(), bcrypt.gensalt()).decode()
def _hash_password_with_bcrypt(clear_text: str) -> bytes: return bcrypt.hashpw(clear_text.encode("utf-8"), bcrypt.gensalt())
def main(): """ Launch tests to check required modules and OS-specific dependencies. Exit with a relevant error code. """ exit_code = 0 import sys print('python %s' % (sys.version,)) try: import zlib except: sys.stderr.write('"zlib" is missing.\n') exit_code = 131 else: print('zlib %s' % (zlib.__version__,)) try: from ssl import OPENSSL_VERSION import _hashlib exit_code = egg_check(_hashlib) | exit_code except: sys.stderr.write('standard "ssl" is missing.\n') exit_code = 132 else: print('stdlib ssl - %s' % (OPENSSL_VERSION,)) try: from cryptography.hazmat.backends.openssl.backend import backend import cryptography openssl_version = backend.openssl_version_text() if CHEVAH_OS in [ "win", "macos", "lnx", "rhel-8" ]: if CHEVAH_OS == "rhel-8": # On RHEL 8.3, OpenSSL got updated to 1.1.1g. To keep backward # compatibility, link to version 1.1.1c from CentOS 8.2.2004. expecting = u'OpenSSL 1.1.1c FIPS 28 May 2019' else: # Use latest OpenSSL version when building it from source. expecting = u'OpenSSL 1.1.1k 25 Mar 2021' if openssl_version != expecting: sys.stderr.write('Expecting %s, got %s.\n' % ( expecting, openssl_version)) exit_code = 133 except Exception as error: sys.stderr.write('"cryptography" failure. %s\n' % (error,)) exit_code = 134 else: print('cryptography %s - %s' % ( cryptography.__version__, openssl_version)) try: from ctypes import CDLL import ctypes CDLL except: sys.stderr.write('"ctypes - CDLL" is missing. %s\n') exit_code = 138 else: print('ctypes %s' % (ctypes.__version__,)) try: from ctypes.util import find_library find_library except: sys.stderr.write('"ctypes.utils - find_library" is missing.\n') exit_code = 139 try: import multiprocessing multiprocessing.current_process() except: sys.stderr.write('"multiprocessing" is missing or broken.\n') exit_code = 140 try: import subprocess32 as subprocess dir_output = subprocess.check_output('ls') except: sys.stderr.write('"subprocess32" is missing or broken.\n') exit_code = 145 else: print('"subprocess32" module is present.') try: import bcrypt password = b"super secret password" # Hash the password with a randomly-generated salt. hashed = bcrypt.hashpw(password, bcrypt.gensalt()) # Check that an unhashed password matches hashed one. if bcrypt.checkpw(password, hashed): print('bcrypt %s' % (bcrypt.__version__,)) else: sys.stderr.write('"bcrypt" is present, but broken.\n') exit_code = 146 except: sys.stderr.write('"bcrypt" is missing.\n') exit_code = 147 try: import bz2 test_string = b"just a random string to quickly test bz2" test_string_bzipped = bz2.compress(test_string) if bz2.decompress(test_string_bzipped) == test_string: print('"bz2" module is present.') else: sys.stderr.write('"bzip" is present, but broken.\n') exit_code = 148 except: sys.stderr.write('"bz2" is missing.\n') exit_code = 149 try: import setproctitle current_process_title = setproctitle.getproctitle() except: sys.stderr.write('"setproctitle" is missing or broken.\n') exit_code = 150 else: print('setproctitle %s' % (setproctitle.__version__,)) try: from sqlite3 import dbapi2 as sqlite except: sys.stderr.write('"sqlite3" is missing or broken.\n') exit_code = 153 else: print('sqlite3 %s - sqlite %s' % ( sqlite.version, sqlite.sqlite_version)) try: import psutil cpu_percent = psutil.cpu_percent() except: sys.stderr.write('"psutil" is missing or broken.\n') exit_code = 160 else: print('psutil %s' % (psutil.__version__,)) try: import uuid uuid.uuid4() except: sys.stderr.write('"uuid" is missing or broken.\n') exit_code = 163 else: print('"uuid" module is present.') if os.name == 'nt': # Windows specific modules. try: from ctypes import windll windll except: sys.stderr.write('"ctypes - windll" is missing.\n') exit_code = 152 else: print('ctypes %s' % (ctypes.__version__,)) else: # Linux / Unix stuff. try: import crypt crypt except: sys.stderr.write('"crypt" is missing.\n') exit_code = 155 # Check for the git revision in Python's sys.version on Linux and Unix. try: git_rev_cmd = ['git', 'log', '-1', '--no-merges', '--format=%h'] git_rev = subprocess.check_output(git_rev_cmd).strip().decode() except: sys.stderr.write("Couldn't get the git rev for the current tree.\n") exit_code = 157 else: bin_ver = sys.version.split('(')[1].split(',')[0] if bin_ver != git_rev: sys.stderr.write("Python version doesn't match git revision!\n" "\tBin ver: {0}".format(bin_ver) + "\n" "\tGit rev: {0}".format(git_rev) + "\n") exit_code = 158 if platform_system in [ 'linux', 'sunos' ]: try: import spwd spwd except: sys.stderr.write('"spwd" is missing, but it should be present.\n') exit_code = 161 else: print('"spwd" module is present.') # The readline module is built using libedit only on selected platforms. if BUILD_LIBEDIT: try: import readline readline.get_history_length() except: sys.stderr.write('"readline" is missing or broken.\n') exit_code = 162 else: print('"readline" module is present.') exit_code = test_dependencies() | exit_code sys.exit(exit_code)
def generate_password_hash(password): hashed = bcrypt.hashpw(password, bcrypt.gensalt()) return hashed
def hashpw(password): digest = hashlib.sha256(password.encode()).digest() encoded = base64.b64encode(digest) return bcrypt.hashpw(encoded, bcrypt.gensalt())
def make_salt(): return bcrypt.gensalt(rounds=config['bcrypt_rounds']).decode('utf-8')
def encrypt(self, password): """Encrypt the password.""" return hashpw(password.encode('utf8'), gensalt())
def set_password(self, password): self.password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
def create_user(self, data): pw_hash = bcrypt.hashpw(data['password'].encode(), bcrypt.gensalt(12)) return self.create(first_name=data['first_name'], last_name=data['last_name'], email=data['email'], pw_hash=pw_hash)
def hashpwd(password: str) -> str: return bcrypt.hashpw(str.encode(password), bcrypt.gensalt()).decode()
def encrypt(self, plain_password): return bcrypt.hashpw(plain_password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
def save_password(cls, userid, password): User.get(userid) #raise NotFoundException if no user user_pw = UserPassword() user_pw.key = userid user_pw.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) user_pw.persist()
def setPassword(self, password): salt = bcrypt.gensalt(5) return bcrypt.hashpw(password.encode("utf-8"), salt)
def generate_salt(): '''function to generate the salt for hashing password''' return bcrypt.gensalt().decode()
email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired(), Length(min=8, max=64)]) confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Add') class LoginForm(FlaskForm): username = StringField('Username', validators = [DataRequired(), Length(min=2, max=20)], render_kw={"placeholder": "Username"}) password = PasswordField('Password', validators = [DataRequired(), Length(min=8, max=64)], render_kw={"placeholder": "Password"}) submit = SubmitField('Login') class InviteUserForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) submit = SubmitField('Invite') hashpass = bcrypt.hashpw('adminpass101'.encode('utf-8'), bcrypt.gensalt()) # users = mongo_users.db.users # users.insert({ # 'FName': 'Admin', # 'LName': 'Admin', # 'UName': 'admin', # 'Password': hashpass, # 'IsAdmin': 1 # }) # for x in users.find(): # print(x) # users.delete_one({"UName": "admin"}) # users.delete_one({"UName": "admin"}) # users.delete_one({"UName": "new_admin"}) # for x in users.find():
def add_user(): form = AddUserForm() if 'username' in session: if session['IsAdmin'] == 1: if request.method == 'POST': if form.validate_on_submit(): users = mongo_users.db.users existing_user = users.find_one({'UName': request.form['username']}) if existing_user is None: hashpass = bcrypt.hashpw(request.form['password'].encode('utf-8'), bcrypt.gensalt()) users.insert({ 'FName': request.form['first_name'], 'LName': request.form['last_name'], 'Email': request.form['email'], 'UName': request.form['username'], 'Password': hashpass, 'IsAdmin': 0 }) flash(f'Account created for {form.username.data}!', 'success') return redirect(url_for('add_user')) flash(f'User {form.username.data} Already Exists!', 'danger') return redirect(url_for('add_user')) return render_template('add_user.html', form=form, isAdmin = session['IsAdmin']) else: abort(404) return redirect(url_for('login'))
__namespace__ = 'rpclib.examples.authentication' session_id = Mandatory.String user_name = Mandatory.String class Preferences(ComplexModel): __namespace__ = 'rpclib.examples.authentication' language = String(max_len=2) time_zone = String user_db = { 'neo': bcrypt.hashpw('Wh1teR@bbit', bcrypt.gensalt()), } session_db = set() preferences_db = RpclibDict({ 'neo': Preferences(language='en', time_zone='Underground/Zion'), 'smith': Preferences(language='xx', time_zone='Matrix/Core'), }) class AuthenticationService(ServiceBase): __tns__ = 'rpclib.examples.authentication' @srpc(Mandatory.String, Mandatory.String, _returns=String, _throws=AuthenticationError)
def register(username, password): db = read_file() db[username] = hashpw(bytes(password, "utf-8"), gensalt()) write_file(db)
def encrypt_password(_password): config = current_config() rounds = config.get('BCRYPT_ROUNDS', 12) password = str(_password).encode('utf-8') encrypted = bcrypt.hashpw(password, bcrypt.gensalt(rounds)).decode('utf-8') return encrypted
def hash_bcrypt(cls, password): if isinstance(password, str): password = password.encode('utf-8') hash_ = bcrypt.hashpw(password, bcrypt.gensalt()).decode('utf-8') return '$'.join(['bcrypt', hash_])
def hash_password(plain_text_password): hashed_bytes = bcrypt.hashpw(plain_text_password.encode('utf-8'), bcrypt.gensalt()) return hashed_bytes.decode('utf-8')
def create(cls, email, password): email = email.strip() hashed_password = hashpw(password.encode(), gensalt()) user = cls(mail=email, password=hashed_password.decode()) return user.save(email, password)
if args.task.upper() == "ADD": inputs = {} params = ["username", "name", "surname", "email", "role"] for item in params: stdin = "" while stdin == "": stdin = raw_input("Enter {}: ".format(item)) inputs[item] = stdin pw = "" while pw == "": pw = getpass.getpass() inputs["password"] = pw try: salt = bcrypt.gensalt(prefix=b"2a") except: salt = bcrypt.gensalt() pwhash = bcrypt.hashpw(inputs["password"], salt) db_curs.execute( "INSERT INTO users ( username, pwhash, salt, name, surname, email, role, tmppwhash ) VALUES (?,?,?,?,?,?,?,?)", (inputs["username"], pwhash, salt, inputs["name"], inputs["surname"], inputs["email"], inputs["role"], None)) db_conn.commit() elif args.task.upper() == "DEL": username = "" while username == "": username = raw_input("Enter username: ")
def hashpwd(password): hash = bcrypt.hashpw(password, bcrypt.gensalt()) return hash
def manejar_comando(self, recibido, client_socket): ''' Este método toma lo recibido por el cliente correspondiente al socket pasado como argumento. :param recibido: diccionario de la forma: {"status": tipo, "data": información} :param client_socket: socket correspondiente al cliente que envió el mensaje :return: ''' # Podemos imprimir para verificar que toodo anda bien if recibido["status"] == "mensaje": #inlcuimos sala nombre = self.sockets[client_socket]['nombre'] for skt, sala in self.salas.items(): if nombre in sala['jugadores']: jugadores = sala['jugadores'] sala = sala['nombre'] break msj = { "status": "mensaje", "data": { "usuario": self.sockets[client_socket]['nombre'], "contenido": recibido["data"]["contenido"], 'sala': sala } } borrar = 0 #aqui vemos si es un comando lo que llega voto_elim = self.comando_valido(recibido["data"]["contenido"]) if voto_elim: self.votos_expulsion[voto_elim].add(msj['data']['usuario']) else: for skt, usr in self.sockets.items(): if usr['nombre'] in jugadores: self.send(msj, skt) if len(recibido["data"]["contenido"]) > 1 and voto_elim: if len(self.votos_expulsion[voto_elim]) > len(jugadores) // 2: print(f'expulsado el usuario {voto_elim}') for skt, usr in self.sockets.items(): if usr['nombre'] in jugadores: msj2 = { "status": "eliminacion", "data": f'{voto_elim}' } self.send(msj2, skt) borrar = 1 if borrar != 0: #hacer esto despues pass elif recibido["status"] == "nuevo_usuario": base = leer_base_datos() nombre = recibido['data']['nombre'] contrasena = recibido['data']['contrasena'] contrasena = contrasena.encode('utf-8') hashed = bcrypt.hashpw(contrasena, bcrypt.gensalt(14)) for usr in self.sockets.values(): if usr != None: if (nombre == usr['nombre'] or nombre == 'empty'): print('usuario ya registrado ') self.send({'status': 'usr en linea'}, client_socket) return for n, usr in enumerate(base, 0): if usr != None: if (usr['nombre'] == nombre and self.contraena_corresp( contrasena, usr['contrasena'])): self.sockets[client_socket] = usr self.send({'status': 'usr aceptado'}, client_socket) self.send_img(client_socket, usr['foto']) self.send( { 'status': 'act sala', 'data': [v for v in self.salas.values()] }, client_socket) return elif (usr['nombre'] == nombre): self.send({'status': 'contrasena mala'}, client_socket) return hashed = hashed.decode('utf-8') new = { "nombre": recibido["data"]['nombre'], "foto": "empty.png", "id": 0, "contrasena": hashed } self.sockets[client_socket] = new base.append(new) self.send({'status': 'usr aceptado'}, client_socket) guardar_datos(base) self.send_img(client_socket, "empty.png") self.send( { 'status': 'act sala', 'data': [v for v in self.salas.values()] }, client_socket) elif recibido['status'] == 'cambio usuario': self.abandono_sala(client_socket) self.act_salas() elif recibido['status'] == 'new_img': response_bytes_length = client_socket.recv(4) response_length = int.from_bytes(response_bytes_length, byteorder="big") response = bytearray() while len(response) < response_length: bytes_leer = min(256, response_length - len(response)) response += client_socket.recv(bytes_leer) path = self.sockets[client_socket]['nombre'] with open(f'imagenes/{path}.png', 'wb') as f: f.write(response) print(path) self.sockets[client_socket]['foto'] = f'{path}.png' actualizar(self.sockets[client_socket]) self.send_img(client_socket, path + '.png') elif recibido['status'] == 'crear sala': #el numero de salas nunca se reiniciará if not (client_socket in self.salas.keys()): jefe = self.sockets[client_socket]['nombre'] self.contador_salas += 1 nombre = f'Sala numero {self.contador_salas}' self.salas[client_socket] = { 'jefe': jefe, 'nombre': self.contador_salas, 'jugadores': [jefe], 'n_jugadores': 1, 'block': False } self.act_salas() d = { 'status': 'aceptado sala', 'data': { 'jefe': jefe, 'n_sala': self.contador_salas, 'sala': self.salas[client_socket] } } self.send(d, client_socket) elif recibido['status'] == 'union sala': jefe = recibido['data']['jefe'] nombre = self.sockets[client_socket]['nombre'] for skt, val in self.sockets.items(): if (val['nombre'] == jefe and (nombre not in self.salas[skt]['jugadores'])): if self.salas[skt]['n_jugadores'] < 15 - 1: self.salas[skt]['jugadores'].append(nombre) self.salas[skt]['n_jugadores'] += 1 sala = self.salas[skt] elif self.salas[skt]['n_jugadores'] == 15 - 1: self.salas[skt]['jugadores'].append(nombre) self.salas[skt]['n_jugadores'] += 1 self.salas[skt]['block'] = True sala = self.salas[skt] elif self.salas[skt]['n_jugadores'] >= 15: print('esto es imposible') return self.act_salas() self.send( { 'status': 'aceptado sala', 'data': { 'jefe': jefe, 'n_sala': sala['nombre'], 'sala': sala } }, client_socket) elif recibido['status'] == 'salir sala': self.abandono_sala(client_socket) self.act_salas() elif recibido['status'] == 'inicio contador': jug = self.salas[client_socket]['jugadores'] for skt, usr in self.sockets.items(): if usr['nombre'] in jug: msj = {'status': 'inicio contador'} self.send(msj, skt) elif recibido['status'] == 'inicio juego': if client_socket not in self.salas: return jug = self.salas[client_socket]['jugadores'] sala = self.salas[client_socket] self.salas[client_socket]['block'] = True for skt, usr in self.sockets.items(): if usr['nombre'] in jug: msj = {'status': 'inicio juego', 'sala': sala} self.send(msj, skt) self.act_salas() elif recibido['status'] == 'filtro dibujo': path = self.sockets[client_socket]['foto'] nd = filtro_dibujo('imagenes/' + path) with open('imagenes/' + path, 'wb') as f: f.write(nd) self.send_img(client_socket, path) elif recibido["status"] == "cerrar_sesion": name = self.sockets[client_socket]['nombre'] print(name, ' ha abandonado') for i in self.votos_expulsion: if name in self.votos_expulsion[i]: self.votos_expulsion[i].remove(name) self.abandono_sala(client_socket) del self.sockets[client_socket] self.act_salas()
def register(): if 'username' in request.form and 'email' in request.form and 'password' in request.form and 'age' in request.form and 'height_ft' in request.form and 'height_in' in request.form and 'gender' in request.form and 'timezone' in request.form and 'exp_cardio' in request.form and 'exp_chest' in request.form and 'exp_legs' in request.form and 'exp_back' in request.form and 'exp_core' in request.form and 'exp_shoulders' in request.form and 'exp_arms' in request.form: print(type(request.form['age'])) username = request.form['username'] email = request.form['email'] password = request.form['password'] if password: password = password.encode() hashed_pass = bcrypt.hashpw(password, bcrypt.gensalt()).decode() password = hashed_pass else: return jsonify({'error' : 'missing data'}) logged_in = 0 age = request.form['age'] height_ft = request.form['height_ft'] height_in = request.form['height_in'] gender = request.form['gender'] timezone = request.form['timezone'] exp_cardio = request.form['exp_cardio'] exp_chest = request.form['exp_chest'] exp_legs = request.form['exp_legs'] exp_back = request.form['exp_back'] exp_core = request.form['exp_core'] exp_shoulders = request.form['exp_shoulders'] exp_arms = request.form['exp_arms'] register_code = random.randint(1000, 9999) created = str(datetime.now().timestamp()) last_activity = str(datetime.now().timestamp()) if username and email and hashed_pass and age and height_ft and height_in and gender and timezone and exp_cardio and exp_chest and exp_legs and exp_back and exp_core and exp_shoulders and exp_arms: cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute("SELECT * FROM Accounts WHERE email = %(email)s", {'email': email}) existing_account = cursor.fetchone() if existing_account: cursor.close() return jsonify({'error' : 'invalid email'}) else: cursor.execute("INSERT INTO Accounts (username,email,password,logged_in,age,height_ft,height_in,gender,timezone, exp_cardio, exp_chest, exp_legs, exp_back, exp_core, exp_shoulders, exp_arms, register_code, created, last_activity ) VALUES ( %(username)s, %(email)s, %(password)s, %(logged_in)s, %(age)s, %(height_ft)s, %(height_in)s, %(gender)s, %(timezone)s, %(exp_cardio)s, %(exp_chest)s, %(exp_legs)s, %(exp_back)s, %(exp_core)s, %(exp_shoulders)s, %(exp_arms)s, %(register_code)s, %(created)s, %(last_activity)s )", {'username': username, 'email': email, 'password': password, 'logged_in': logged_in, 'age': age, 'height_ft': height_ft, 'height_in': height_in, 'gender': gender, 'timezone': timezone, 'exp_cardio':exp_cardio, 'exp_chest': exp_chest, 'exp_legs': exp_legs, 'exp_back': exp_back, 'exp_core': exp_core, 'exp_shoulders': exp_shoulders, 'exp_arms': exp_arms, 'created': created, 'register_code': register_code, 'last_activity': last_activity}) mysql.connection.commit() cursor.execute("SELECT * from Accounts WHERE email = %(email)s", {'email': email}) account = cursor.fetchone() if not account: cursor.close() return jsonify({'error' : 'missing data'}) else: cursor.close() session.permanent = True session['logged_in'] = 0 session['email'] = account['email'] session['account_id'] = account['account_id'] session['register_code'] = account['register_code'] reg_code = account['register_code'] session['username'] = account['username'] rec_email = account['email'] created_stamp = account['created'] try: draft = nylas.drafts.create() draft.subject = "UNCW fit shuffle app" draft.body = "Thanks for signing up {name}! Here is your 4-digit registeration code: {code}".format( name = username, code= reg_code) draft.to = [{'name': username, 'email': email}] draft.send() except: pass cur_var = str(datetime.now() + timedelta(seconds=1200))[:19] sched_id = 'Registertask-' + account['email'] scheduler.add_job(name="RegisterTask", id=sched_id, func = registercheck, trigger='date', run_date=cur_var, kwargs = { 'u_id': str(account['account_id']), 'email': str(account['email']), 'created': str(created_stamp), 'code': str(account['register_code'])} ) return jsonify({'error' : 'none'}) else: return jsonify({'error' : 'missing data'}) else: return jsonify({'error' : 'missing data'})
def passhash(password): return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(m.MACRO_BCRYPT_ROUNDS)).decode('ascii')
def hash_password(cls, password): return bcrypt.hashpw(password.encode("utf8"), bcrypt.gensalt()).decode("utf8")
def _hash_password(password: str) -> str: """ Hash password method """ hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()) return hashed
def new_password(password): return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')