Example #1
0
def check_credentials(username, passphrase):
    """Verifies credentials for username and passphrase.
    Returns None on success or a string describing the error on failure"""

    if not username or not passphrase:
        error = "No username or password."
        cfg.log(error)
        return error

    # hash the password whether the user exists, to foil timing
    # side-channel attacks
    try:
        if username in cfg.users:
            u = cfg.users[username]
            pass_hash = bcrypt.encrypt(passphrase, salt=u['salt'])
        else:
            u = None
            pass_hash = bcrypt.encrypt(passphrase)
    except PasswordSizeError:
        error = "Password is too long."
        cfg.log(error)
        return error

    if u is None or u['passphrase'] != pass_hash:
        error = "Bad user-name or password."
    else:
        error = None

    if error:
        cfg.log(error)
    return error
Example #2
0
 def test_htpasswd_bcrypt(self):
     try:
         from passlib.hash import bcrypt
         from passlib.exc import MissingBackendError
     except ImportError:
         pytest.skip("passlib is not installed")
     try:
         bcrypt.encrypt("test-bcrypt-backend")
     except MissingBackendError:
         pytest.skip("bcrypt backend for passlib is not installed")
     self._test_htpasswd(
         "bcrypt",
         "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3VNTRI3w5KDnj8NTUKJNWfVpvRq")
Example #3
0
def add_user(username, passphrase, name='', email='', expert=False):
    """Add a new user with specified username and passphrase.
    """
    error = None
    if not username: error = "Must specify a username!"
    if not passphrase: error = "Must specify a passphrase!"

    if error is None:
        if username in map(lambda x: x[0], cfg.users.get_all()):
            error = "User already exists!"
        else:
            try:
                pass_hash = bcrypt.encrypt(passphrase)
            except PasswordSizeError:
                error = "Password is too long."

    if error is None:
        di = {
            'username':username,
            'name':name,
            'email':email,
            'expert':'on' if expert else 'off',
            'groups':['expert'] if expert else [],
            'passphrase':pass_hash,
            'salt':pass_hash[7:29], # for bcrypt
        }
        new_user = User(di)
        cfg.users.set(username,new_user)

    if error:
        cfg.log(error)
    return error
Example #4
0
    def register(self, password, group, age):
        if not self.find():
            user = Node("OnlineMusicAccount",
                        username=self.username,
                        password=bcrypt.encrypt(password))

            graph.create(user)

            OMA = graph.find_one("OnlineMusicAccount", "description",
                                 "OnlineMusicAccount")
            affRel = Relationship(user, "rdf:type", OMA)

            affiliationNode = Node("Affiliation", age=age, affiliation=group)
            graph.create(affiliationNode)
            affRel = Relationship(user, "schema:affiliation", affiliationNode)
            graph.create(affRel)

            nameNode = Node("OnlineMusicAccountName", username=self.username)
            graph.create(nameNode)
            nameRel = Relationship(user, "foaf:name", nameNode)
            graph.create(nameRel)

            dateNode = Node("Date", date=date())
            graph.create(dateNode)
            dateRel = Relationship(user, "dcterms:created", dateNode)
            graph.create(dateRel)

            return True
        else:
            return False
Example #5
0
 def add_user(username, email, characterid, charactername):
     logger.debug("Adding new market user %s" % username)
     plain_password = marketManager.__generate_random_pass()
     hash = bcrypt.encrypt(plain_password, rounds=13)
     hash_result = hash
     rounds_striped = hash_result.strip('$2a$13$')
     salt = rounds_striped[:22]
     username_clean = marketManager.__santatize_username(username)
     if marketManager.check_username(username)== False:
         if marketManager.check_user_email(username, email) == False:
             try:
                 logger.debug("Adding user %s to alliance market" % username)
                 cursor = connections['market'].cursor()
                 cursor.execute(marketManager.SQL_ADD_USER, [username_clean, username_clean, email, email, salt,
                                                             hash, characterid, charactername])
                 return username_clean, plain_password
             except:
                 logger.debug("Unsuccessful attempt to add market user %s" % username)
                 return "", ""
         else:
             logger.debug("Alliance market email %s already exists Updating instead" % email)
             username_clean, password = marketManager.update_user_info(username)
             return username_clean, password
     else:
         logger.debug("Alliance market username %s already exists Updating instead" % username)
         username_clean, password = marketManager.update_user_info(username)
         return username_clean, password
Example #6
0
 def register(self, password):
     if not self.find():
         user = Node("User", username=self.username, password=bcrypt.encrypt(password))
         graph.create(user)
         return True
     else:
         return False
Example #7
0
	def register(self, email, password):
		if not self.find():
			user = Node("User", username=self.username, email=email, password=bcrypt.encrypt(password), Uploaded_pp="0", bio='')
			graph.create(user)
			return True
		else:
			return False
Example #8
0
 def do_POST(self):
     #index or list action
     self.load_session()
     if self.path.startswith("/contacts"):
         lst = ContactsDB()
         usr = UserDB()
         matched = False
         allUsers = usr.getUsernames()
         for i in allUsers:
             if gSessionStore.sessionData[
                     self.session] == i[0] and i[0] != "":
                 matched = True
                 break
             else:
                 matched = False
         print(matched)
         if matched:
             length = self.header201()
             data, amount = self.parseInput(length)
             if amount > 6:
                 self.header404("Unable to add contact")
                 return
             lst.addContact(data)
             self.wfile.write(bytes(lst.getContacts(), "utf-8"))
         else:
             self.header401()
     elif self.path.startswith("/sessions"):
         lst = ContactsDB()
         usr = UserDB()
         length = int(self.headers['Content-Length'])
         data, amount = self.parseInput(length)
         idPath = data["email"]
         testPass = data["encryptedpass"]
         userInfo = usr.getUser(idPath)
         if userInfo:
             if bcrypt.verify(testPass[0], userInfo[0]["encryptedpass"]):
                 print("saved email")
                 self.header200()
                 self.wfile.write(bytes(json.dumps(userInfo), "utf-8"))
                 gSessionStore.sessionData[
                     self.session] = userInfo[0]["email"]
                 print(gSessionStore.sessionData)
             else:
                 self.header401()
     elif self.path.startswith("/users"):
         lst = ContactsDB()
         usr = UserDB()
         ids = usr.getUsernames()
         length = int(self.headers['Content-Length'])
         data, amount = self.parseInput(length)
         for i in ids:
             if i[0] == data["email"][0]:
                 self.header422()
                 return
         self.header201()
         data["encryptedpass"][0] = bcrypt.encrypt(data["encryptedpass"][0])
         useradded = usr.addUser(data)
         self.wfile.write(bytes(useradded, "utf-8"))
     else:
         self.header404("Collection not found")
Example #9
0
 def __init__(self, username, password):
     self.id = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6))
     self.username = username
     self.password = bcrypt.encrypt(password)
     self.active = True
     self.superuser = False
     self.created = datetime.utcnow()
Example #10
0
 def setUp(self):
     self.mp = MemoryPersistence(db=[])
     self.mp.create({
         "username": "******",
         "password": bcrypt.encrypt("pass", rounds=4)
     })
     self.pb = PersistenceAuthBackend(self.mp)
Example #11
0
def cli(ctx, email, password, group, nick, display_name, force):
    """
    Creates a new user account
    """
    assert isinstance(ctx, Context)

    # Make sure our configuration directory exists
    config_dir = os.path.join(FireflyIRC.CONFIG_DIR, 'config')
    if not os.path.exists(config_dir):
        os.makedirs(config_dir, 0o755)

    # Make sure the user doesn't already exist in our servers configuration
    users_config = FireflyIRC.load_configuration('users')
    users_cfg_path = os.path.join(config_dir, 'users.cfg')
    if email in users_config.sections():
        ctx.log.info('Configuration for %s already exists', email)
        if not force:
            raise click.ClickException('Configuration for {e} already exists'.format(e=email))
        users_config.remove_section(email)

    # Populate users.cfg
    users_config.add_section(email)
    users_config.set(email, 'Password', bcrypt.encrypt(password))
    users_config.set(email, 'Group', group)
    users_config.set(email, 'Nick', nick)
    users_config.set(email, 'DisplayName', display_name)

    # Write to our users configuration file
    with open(users_cfg_path, 'w') as cf:
        users_config.write(cf)

    click.secho('Configuration for user {e} successfully generated'.format(e=email), bold=True)
    click.secho('Users configuration path: {sp}'.format(sp=users_cfg_path), bold=True)
Example #12
0
 def register(self, password):
     if not self.find():
         user = Node('User', username=self.username, password=bcrypt.encrypt(password))
         graph.create(user)
         return True
     else:
         return False
Example #13
0
    def __init__(self, username, password, email):

        encrypted = bcrypt.encrypt(password)

        self.username = username
        self.password = encrypted
        self.email = email
Example #14
0
    def patch_attributes(self, attributes):
        if attributes.get('password', None) is not None:
            # defaults aren't set yet
            hash_method = HASH_METHODS[attributes.get(
                'hash_method',
                self.ITEM_ATTRIBUTES['hash_method'],
            )]
            salt = force_text(attributes.get('salt', None))
            if self.node.os == 'openbsd':
                attributes['password_hash'] = bcrypt.encrypt(
                    force_text(attributes['password']),
                    rounds=8,  # default rounds for OpenBSD accounts
                    salt=_DEFAULT_BCRYPT_SALT if salt is None else salt,
                )
            elif attributes.get('hash_method') == 'md5':
                attributes['password_hash'] = hash_method.encrypt(
                    force_text(attributes['password']),
                    salt=_DEFAULT_SALT if salt is None else salt,
                )
            else:
                attributes['password_hash'] = hash_method.encrypt(
                    force_text(attributes['password']),
                    rounds=5000,  # default from glibc
                    salt=_DEFAULT_SALT if salt is None else salt,
                )

        if 'use_shadow' not in attributes:
            attributes['use_shadow'] = self.node.use_shadow_passwords

        for attr in ('gid', 'uid'):
            if isinstance(attributes.get(attr), int):
                attributes[attr] = str(attributes[attr])

        return attributes
Example #15
0
def initialize_users():
    global db
    global force
    global admin_email

    if force or not db.get('global:nextUserId') or not db.get('uid:1:username'):
        # Setting global users counter
        db.set('global:nextUserId', 1)
        # Please don't change default admin's name!
        db.set('uid:1:username', 'admin')
        # To make things more secure please change default password inside of admin UI.
        db.set('uid:1:password', bcrypt.encrypt('admin'))
        # You can change email to yours above
        db.set('uid:1:email', admin_email)
        # Adding email into emails list
        db.sadd('users:emails', admin_email)
        # Creating new group - admin:
        db.sadd('users:groups', 'group:admins')
        db.sadd('users:groups', 'group:moderators')
        db.sadd('users:groups', 'group:users')
        # Setting admin's group
        db.set('uid:1:group', 'group:admins')
        # Connection your username with UID
        db.set('username:'******'uid:1:username') + ':uid', 1)
        # Adding your user into global users list
        db.sadd('users:list', 1)
        print ("Super user record was added, use next data to log in:\n"
               " - username: '******' \n - password: '******'\n" % db.get('uid:1:username'))
        print ("Please change your password in AJP for safety reasons.")
    else:
        print ('Super user exists, change force to True to rewrite super user\'s password')
Example #16
0
 def register(cls, user_name, phone_number, password, campus_address, student_id, portrait):
     if not User.find_by_phone_number(phone_number):
         query = """
         INSERT INTO User
         (`user_id`,
         `user_name`,
         `phone_number`,
         `password`,
         `campus_address`,
         `student_id`,
         `portrait`)
         VALUES
         (%s,
         %s,
         %s,
         %s,
         %s,
         %s,
         %s);
         """
         connection = mysql.connect()
         cursor = connection.cursor()
         cursor.execute(query, (uuid.uuid4(), user_name, phone_number, bcrypt.encrypt(password), campus_address, student_id, portrait))
         connection.commit()
         cursor.close()
         connection.close()
         return True
     else:
         return False
Example #17
0
def register():
    if _user_is_authenticated():
        return redirect('/')

    form = RegisterForm()
    if form.validate_on_submit():
        if dbsession.query(
                exists().where(User.email == form.email.data)).scalar():
            warning_markup = Markup(
                'User with email %(email) already exists. '
                'Click <a href="%(login_link)">here</a> to login.',
                email=form.email.data, login_link=url_for('login'))
            flash(warning_markup, 'warning')
            return render_template('register.html', form=form)
        user = User(name=form.name.data,
                    email=form.email.data,
                    password_hash=bcrypt.encrypt(form.password.data))
        dbsession.add(user)
        dbsession.commit()
        login_user(user, remember=True)
        return redirect('/')
    else:
        write_errors_to_flash(form)

    return render_template('register.html', form=form)
Example #18
0
 def register(cls, email, password, nickname, portrait):
     if not User.find_by_email(email):
         user = Node("User", id=str(uuid.uuid4()), email=email, password=bcrypt.encrypt(password), nickname=nickname, portrait = portrait)
         graph.create(user)
         return True
     else:
         return False
Example #19
0
def process_new_user(data=None, **kw):
    if 'password' not in data:
        raise ProcessingException(description='No password.', code=400)

    password = data['password']
    data['hashed_password'] = bcrypt.encrypt(password, rounds=12, ident='2y')
    del data['password']
Example #20
0
 def check(self, value):
     
     self.txt_error=''
     self.error=False
     
     value.strip()
     
     if value=='':
         
         if self.model!=None:
         
             if self.model.updated==True:
                 self.required=False
                 self.check_blank=True
                 return ""
             else:
                 
                 self.txt_error="The value is empty"
                 self.error=True
                 
         else:
             self.txt_error="The value is empty"
             self.error=True
         
     else:
         value = bcrypt.encrypt(value)
         
     
     return value
Example #21
0
def invite(invite_id):
	invites = models.Invite.query.all()

	for i in invites:
		if i.id == invite_id:
			if request.method == 'POST':
				name = request.form["username"]
				email = request.form["email"]
				password = request.form["password"]

				pwdhash = bcrypt.encrypt(password, rounds=12)

				user = models.User(name=name, email=email, pwdhash=pwdhash)

				db.session.add(user)

				# Invite is used and has to be destroyed
				# so it can not be used by someone else to register
				db.session.delete(models.Invite.query.get(invite_id))

				db.session.commit()

				return redirect(url_for("login"))

			return render_template("signup.html", invite_id=invite_id)

	return render_template("invalid_invite.html")
Example #22
0
def ct_create_person(user_data):
    ''' creates temp churchtools person '''
    with ct_connect.session_scope() as ct_session:
        # extracting column keys out of person table from churchtools
        ct_columns = ct_connect.Person.__table__.columns.keys()

        # create person data dict prefilled with default empty strings
        person_data = {}
        for column in ct_columns:
            person_data[column] = ''

        # for each item in user_data create an db entry
        for user in user_data:
            # getting person_data dict
            temp_person_data = person_data

            # fill the temp_person_dict
            for key, value in user.iteritems():
                if key == 'password':
                    temp_person_data[key] = bcrypt.encrypt(value)
                else:
                    temp_person_data[key] = value

            # define temp user
            temp_user = ct_connect.Person(**temp_person_data)

            # add temp user to session
            ct_session.add(temp_user)

        # save to db
        ct_session.commit()
Example #23
0
 def POST(self):
     i = web.input()
     user_email = i.email
     # hash users passwords to store them in the database
     hashed_password = bcrypt.encrypt(i.password)
     n = db.insert('users', email=user_email, password=hashed_password)
     raise web.seeother('/')
 def add_user(username, email, characterid, charactername):
     logger.debug("Adding new market user %s" % username)
     plain_password = marketManager.__generate_random_pass()
     hash = bcrypt.encrypt(plain_password, rounds=13)
     hash_result = hash
     rounds_striped = hash_result.strip("$2a$13$")
     salt = rounds_striped[:22]
     username_clean = marketManager.__santatize_username(username)
     if not marketManager.check_username(username):
         if not marketManager.check_user_email(username, email):
             try:
                 logger.debug("Adding user %s to alliance market" % username)
                 cursor = connections["market"].cursor()
                 cursor.execute(
                     marketManager.SQL_ADD_USER,
                     [username_clean, username_clean, email, email, salt, hash, characterid, charactername],
                 )
                 return username_clean, plain_password
             except:
                 logger.debug("Unsuccessful attempt to add market user %s" % username)
                 return "", ""
         else:
             logger.debug("Alliance market email %s already exists Updating instead" % email)
             username_clean, password = marketManager.update_user_info(username)
             return username_clean, password
     else:
         logger.debug("Alliance market username %s already exists Updating instead" % username)
         username_clean, password = marketManager.update_user_info(username)
         return username_clean, password
Example #25
0
    def handleUserCreate(self):
        length = int(self.headers["Content-length"])
        body = self.rfile.read(length).decode("utf-8")
        parsed_body = parse_qs(body)

        fname = parsed_body['fname'][0]
        lname = parsed_body['lname'][0]
        email = parsed_body['email'][0]
        password = parsed_body['password'][0]
        hash = bcrypt.encrypt(password)
        password = hash

        db = UserDB()
        checkEmail = db.emailInDatabase(email)
        json_string = json.dumps(checkEmail)

        if checkEmail:
            self.handle422()
        else:
            db = UserDB()
            db.createUser(fname, lname, email, password)

            checkEmail = db.emailInDatabase(email)
            json_string = json.dumps(checkEmail)
            self.session["userId"] = checkEmail['id']
            self.send_response(201)
            self.end_headers()
            self.wfile.write(bytes(json_string, "utf-8"))
Example #26
0
    def patch_attributes(self, attributes):
        if attributes.get('password', None) is not None:
            # defaults aren't set yet
            hash_method = HASH_METHODS[attributes.get(
                'hash_method',
                self.ITEM_ATTRIBUTES['hash_method'],
            )]
            salt = attributes.get('salt', None)
            if self.node.os in self.node.OS_FAMILY_BSD:
                attributes['password_hash'] = bcrypt.encrypt(
                    force_text(attributes['password']),
                    rounds=8,  # default rounds for OpenBSD accounts
                    salt=_DEFAULT_BCRYPT_SALT if salt is None else salt,
                )
            else:
                attributes['password_hash'] = hash_method.encrypt(
                    force_text(attributes['password']),
                    rounds=5000,  # default from glibc
                    salt=_DEFAULT_SALT if salt is None else salt,
                )

        if 'use_shadow' not in attributes:
            attributes['use_shadow'] = self.node.use_shadow_passwords

        for attr in ('gid', 'uid'):
            if isinstance(attributes.get(attr), int):
                attributes[attr] = str(attributes[attr])

        return attributes
def test_user_update_self_only(db_conn, session):
    """
  Ensure a user can only update herself.
  """

    raw_insert_users(
        db_conn,
        [{
            'name': 'other',
            'email': '*****@*****.**',
            # NOTE do not use rounds this low in production
            'password': bcrypt.encrypt('1234abcd', rounds=4),
        }])
    request = {
        'params': {
            'email': '*****@*****.**'
        },
        'cookies': {
            'session_id': session,
        },
        'db_conn': db_conn
    }
    code, response = routes.user.update_user_route(request, user_id)
    assert code != 200
    assert 'errors' in response
Example #28
0
def register():
	return render_template('register.html')
	if request.method == 'POST':
		try:
			mySQLconnect()
		except Exception:
			flash('The database is not availible.')
			return redirect('/index')
		username = request.form['username']
		password = request.form['password']
		passwordConfirm = request.form['confirmpassword']
		email = request.form['email']
		phone = request.form['phone']
		cursor.execute('SELECT username FROM users WHERE username = %s', (username,))
		if len(username) > 20 or len(username) < 6:
			flash('Your username must be between 6 and 20 characters')
			return redirect('/register')
		if cursor.fetchone():
			flash('Your username is already taken.')
			return redirect('/register')
		if password != passwordConfirm:
			flash('Your passwords do not match')
			return redirect('/register')
		if len(password) < 6 or len(password) > 20:
			flash('Your password must be between 6 and 20 characters')
			return redirect('/register')
		if '@' and '.' not in email:
			flash('Your email is invalid')
			return redirect('/register')
		password = bcrypt.encrypt(password)
		cursor.execute('INSERT INTO users(username,password,phone,email,confirmed,signup) VALUES(%s,%s,%s,%s,%s,%s)', (username,password,phone,email,'F',date.today()))
		db.commit()
		flash('Registration Complete.')		
		return render_template('index.html')
Example #29
0
def parseUsersFile(expiration=365):
    """
    Creates new user in the graph database and corresponding node, through the following steps:

        1. Generates new user identifier
        2. Checks if a user with given properties already exists in the database. If not:
        3. Creates new local user (access to graph database)
        4. Saves data to tab-delimited file.

    :param int expiration: number of days a user is given access.
    :return: Writes relevant .tsv file for the users in the provided file.
    """
    usersDir = ckg_config['users_directory']
    usersFile = os.path.join(usersDir, config['usersFile'])
    usersImportDir = ckg_config['imports_users_directory']
    usersImportFile = os.path.join(usersImportDir, config['import_file'])

    driver = connector.getGraphDatabaseConnectionConfiguration(database=None)

    data = pd.read_excel(usersFile).applymap(str)
    date = datetime.today() + timedelta(days=expiration)
    df = []
    try:
        user_identifier = get_new_user_identifier(driver)
        if user_identifier is None:
            user_identifier = 'U1'
        new_id = int(re.search('\d+', user_identifier).group())

        for index, row in data.iterrows():
            username = check_if_node_exists(driver, 'username',
                                            row['username'])
            name = check_if_node_exists(driver, 'name', row['name'])
            email = check_if_node_exists(driver, 'email', row['email'])
            if username.empty and name.empty and email.empty:
                row['ID'] = 'U{}'.format(new_id)
                row['acronym'] = ''.join(
                    [c for c in row['name'] if c.isupper()])
                row['rolename'] = 'reader'
                row['expiration_date'] = date.strftime('%Y-%m-%d')
                row['image'] = ''
                #create_db_user(driver, row)
                row['password'] = bcrypt.encrypt(row['password'])
                df.append(row)
                new_id += 1

    except Exception as err:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        logger.error("Extracting users info: {}, file: {},line: {}".format(
            sys.exc_info(), fname, exc_tb.tb_lineno))
    if len(df) > 0:
        data = pd.DataFrame(df)
        data['phone_number'] = data['phone_number'].str.split('.').str[0]
        data = data[[
            'ID', 'acronym', 'name', 'username', 'password', 'email',
            'secondary_email', 'phone_number', 'affiliation',
            'expiration_date', 'rolename', 'image'
        ]]
        GenerateGraphFiles(data, usersImportFile)
Example #30
0
 def set_password(self, password, rounds=12):
     """Hash a plain text password and set the encrypted version against
     this instance.
     :param password: hashable str
     :param rounds: Specify the number of rounds bcrypt will perform
     :returns: None
     """
     self.password = bcrypt.encrypt(password, rounds=rounds)
    def setUp(self):
        self.user, created = User.objects.get_or_create(
            username='******')
        self.user.cryptsum = bcrypt.encrypt('test', ident='2y')
        self.user.password = ''
        self.user.save()

        self.legacyauth = LegacyCoffeestatsAuth()
Example #32
0
    def register(self, password, fname, lname, postalcode, zcountry):
        if not self.find():
            user = Node("Person", gcemail=self.gcemail, password=bcrypt.encrypt(password), fname=fname, lname=lname, postalcode=postalcode, 
	    zcountry=zcountry, timestamp=timestamp(), date=date())
            graph.create(user)
            return True
        else:
            return False
Example #33
0
def add_default_sudopass(self):
    setting = yield Setting.objects.get(key='security_password')
    if not setting:
        setting = Setting()
        setting.key = 'security_password'
        setting.value = bcrypt.encrypt('es456')
        yield setting.save()
    self.finish()
def register(username,password,email,age,gender,mobile,country,state):
    if not find(username):
        user = Node('User', password=bcrypt.encrypt(password),username=username,email=email,gender=gender,age=age,mobile=mobile,country=country,state=state)
        graph.create(user)

        return True
    else:
        return False
Example #35
0
 def _encrypt(self, clearvalue, salt=None):
     # Using the parameter for rounds will generate the error
     # ValueError: rounds too high (bcrypt requires <= 31 rounds)
     # when using the bcrypt hasher.
     # rounds = int(parameters.get_admin('ROUNDS_NUMBER'))
     # To get around this, I use the default of 12.
     rounds = 12
     return bcrypt.encrypt(clearvalue, rounds=rounds)
Example #36
0
 def __init__(self, username, password, name, email):
     """Create new instance."""
     self.username = username
     self.password = bcrypt.encrypt(password)
     self.name = name
     self.email = email
     self.age = 0
     self.gender = "U"
Example #37
0
    def update_password(self, new_password):
        """Hash a new password to bcrypt.

        :param new_password: The new password
        :type new_password: str

        """
        self.password = bcrypt.encrypt(new_password)
Example #38
0
    def update_password(self, new_password):
        """Hash a new password to bcrypt.

        :param new_password: The new password
        :type new_password: str

        """
        self.password = bcrypt.encrypt(new_password)
Example #39
0
 def _encrypt(self, clearvalue, salt=None):
     # Using the parameter for rounds will generate the error
     # ValueError: rounds too high (bcrypt requires <= 31 rounds)
     # when using the bcrypt hasher.
     # rounds = parameters.get_global_parameter("rounds_number")
     # To get around this, I use the default of 12.
     rounds = 12
     return bcrypt.encrypt(clearvalue, rounds=rounds)
Example #40
0
 def _encrypt(self, clearvalue, salt=None):
     # Using the parameter for rounds will generate the error
     # ValueError: rounds too high (bcrypt requires <= 31 rounds)
     # when using the bcrypt hasher.
     # rounds = parameters.get_global_parameter("rounds_number")
     # To get around this, I use the default of 12.
     rounds = 12
     return bcrypt.encrypt(clearvalue, rounds=rounds)
Example #41
0
File: user.py Project: scarltee/CKG
 def register(self, password):
     if not self.find():
         return connector.create_node(driver,
                                      "User",
                                      username=self.username,
                                      password=bcrypt.encrypt(password))
     else:
         return False
Example #42
0
 def _encrypt(self, clearvalue, salt=None):
     # Using the parameter for rounds will generate the error
     # ValueError: rounds too high (bcrypt requires <= 31 rounds)
     # when using the bcrypt hasher.
     # rounds = int(parameters.get_admin('ROUNDS_NUMBER'))
     # To get around this, I use the default of 12.
     rounds = 12
     return bcrypt.encrypt(clearvalue, rounds=rounds)
Example #43
0
 def register(self, password):
     if self.find().single():
         return False
     else:
         usnm=self.username
         pswd=bcrypt.encrypt(password)
         query="CREATE (u:User {{username: '******', password: '******' }})".format(usnm,pswd)
         driver.RunQuery(query)
         return True
Example #44
0
def create_user_in_db(users_table, db_conn):
    return users_table.insert({
        'id': 'abcd1234',
        'name': 'test',
        'email': '*****@*****.**',
        'password': bcrypt.encrypt('abcd1234'),
        'created': r.now(),
        'modified': r.now()
    }).run(db_conn)
    def test_fetch(self):
        dir = os.path.dirname(os.path.realpath(__file__))

        with open('{}/config.yaml'.format(dir), 'r') as stream:
            config = yaml.load(stream)
            self.base_url = config['base_url']

        connect_db(self.io_loop)

        Branch.objects.limit(1).find_all(callback=self.stop)
        branch = self.wait()

        request = HTTPRequest('{}/api/request_token'.format(self.base_url),
                              headers={
                                  'ES-Branch': str(branch[0]._id),
                                  'ES-Password': branch[0].password
                              })

        client = AsyncHTTPClient(self.io_loop)
        client.fetch(request, self.handle_request_token)
        token = self.wait()

        password = bcrypt.encrypt('1234')
        users = []

        for index in range(0, DATABASE_LIMIT * 2):
            random = uuid.uuid4()
            user = User(first_name='APIUsersPaginationTest' + str(random),
                        last_name='last_name' + str(random),
                        email='email' + str(random) + '@localhost.com',
                        password=password,
                        status='Active',
                        credits=300)

            users.append(user)

        User.objects.bulk_insert(users, callback=self.stop)
        self.wait()

        request = HTTPRequest('{}/api/users'.format(self.base_url),
                              headers={'ES-Token': token})

        client = AsyncHTTPClient(self.io_loop)
        client.fetch(request, self.handle_fetch)
        self.wait()

        request = HTTPRequest('{}/api/users?page=1'.format(self.base_url),
                              headers={'ES-Token': token})

        client = AsyncHTTPClient(self.io_loop)
        client.fetch(request, self.handle_fetch)
        self.wait()

        User.objects \
            .filter({'first_name': {'$regex': '^APIUsersPaginationTest'}}) \
            .delete(callback=self.stop)
        self.wait()
Example #46
0
 def __init__(self, password=None, id=None, user_id=None, hash=None):
     if hash:
         self.hash = hash
     else:
         self.hash = bcrypt.encrypt(password)
     if id:
         self.id = id
     if user_id:
         self.user_id = user_id
Example #47
0
def create_user_in_db(users_table, db_conn):
    return users_table.insert({
        'id': 'abcd1234',
        'name': 'test',
        'email': '*****@*****.**',
        'password': bcrypt.encrypt('abcd1234'),
        'created': r.now(),
        'modified': r.now()
    }).run(db_conn)
Example #48
0
 def register(self, password):
     if not self.find():
         values = {
             "password": bcrypt.encrypt(password)
         }
         self.update(values)
         return True
     else:
         return False
Example #49
0
 def __init__(
         self,
         id=None,
         name=None,
         password=None
 ):
     self.id = id
     self.name = name
     self.password = bcrypt.encrypt(password)
Example #50
0
 def change_password(self, password):
     """Changes the user's password, encrypting the password with bcrypt."""
     user = self.find()
     graph.run(
         "MERGE (n:User {username: {username}}) SET n.password = {password}",
         {
             "username": self.username,
             "password": bcrypt.encrypt(password)
         })
Example #51
0
 def change_password(self, new_password):
     q = '''
     match (u:User)
     where u.username = $uname
     set u.password = $password
     '''
     return graph.run(q,
                      uname=self.username,
                      password=bcrypt.encrypt(new_password))
Example #52
0
    def __init__(self, username, password, professor):
        """"""

        self.username = username
        self.password = bcrypt.encrypt(password)
        self.professor = professor

        # create tables
        Base.metadata.create_all(engine)
Example #53
0
    def register(self, password, name_surname, email):
        # zaten modelde biz şifreliyormuşuz. yani metota 123456 gönderince o şifreleyip veritabanına kaydediyormuş. O yüzden tekrar şifrelemiycez haydaaa :D Aydınlıklar geliyor bana bana :D
        if not self.find(): # Eğer bu kullanıcı adından kimse yoksa, kayıt yap
            user = Node('User', username=self.username, password=bcrypt.encrypt(password), name=name_surname, email=email)
            graph.create(user)

            return True
        else:
            return False
Example #54
0
 def saveEditUser(self, userId, name, username, password, type, iter):
     result = config.db.session.query(Users)
     result = result.filter(Users.id == userId)
     result[0].name = name
     result[0].username = username
     if password:
         result[0].password = bcrypt.encrypt(password)
     result[0].permission = self.groupId
     config.db.session.commit()
Example #55
0
 def __init__(self, password=None, id=None, user_id=None, hash=None):
     if hash:
         self.hash = hash
     else:
         self.hash = bcrypt.encrypt(password)
     if id:
         self.id = id
     if user_id:
         self.user_id = user_id
Example #56
0
    def __init__(self, configuration, logger):
        super().__init__(configuration, logger)
        self.filename = os.path.expanduser(
            configuration.get("auth", "htpasswd_filename"))
        self.encryption = configuration.get("auth", "htpasswd_encryption")

        if self.encryption == "ssha":
            self.verify = self._ssha
        elif self.encryption == "sha1":
            self.verify = self._sha1
        elif self.encryption == "plain":
            self.verify = self._plain
        elif self.encryption == "md5":
            try:
                from passlib.hash import apr_md5_crypt
            except ImportError:
                raise RuntimeError(
                    "The htpasswd encryption method 'md5' requires "
                    "the passlib module.")
            self.verify = functools.partial(self._md5apr1, apr_md5_crypt)
        elif self.encryption == "bcrypt":
            try:
                from passlib.hash import bcrypt
            except ImportError:
                raise RuntimeError(
                    "The htpasswd encryption method 'bcrypt' requires "
                    "the passlib module with bcrypt support.")
            # A call to `encrypt` raises passlib.exc.MissingBackendError with a
            # good error message if bcrypt backend is not available. Trigger
            # this here.
            bcrypt.encrypt("test-bcrypt-backend")
            self.verify = functools.partial(self._bcrypt, bcrypt)
        elif self.encryption == "crypt":
            try:
                import crypt
            except ImportError:
                raise RuntimeError(
                    "The htpasswd encryption method 'crypt' requires "
                    "the crypt() system support.")
            self.verify = functools.partial(self._crypt, crypt)
        else:
            raise RuntimeError(
                "The htpasswd encryption method '%s' is not "
                "supported." % self.encryption)
Example #57
0
    def __init__(self, configuration, logger):
        super().__init__(configuration, logger)
        self.filename = os.path.expanduser(
            configuration.get("auth", "htpasswd_filename"))
        self.encryption = configuration.get("auth", "htpasswd_encryption")

        if self.encryption == "ssha":
            self.verify = self._ssha
        elif self.encryption == "sha1":
            self.verify = self._sha1
        elif self.encryption == "plain":
            self.verify = self._plain
        elif self.encryption == "md5":
            try:
                from passlib.hash import apr_md5_crypt
            except ImportError:
                raise RuntimeError(
                    "The htpasswd encryption method 'md5' requires "
                    "the passlib module.")
            self.verify = functools.partial(self._md5apr1, apr_md5_crypt)
        elif self.encryption == "bcrypt":
            try:
                from passlib.hash import bcrypt
            except ImportError:
                raise RuntimeError(
                    "The htpasswd encryption method 'bcrypt' requires "
                    "the passlib module with bcrypt support.")
            # A call to `encrypt` raises passlib.exc.MissingBackendError with a
            # good error message if bcrypt backend is not available. Trigger
            # this here.
            bcrypt.encrypt("test-bcrypt-backend")
            self.verify = functools.partial(self._bcrypt, bcrypt)
        elif self.encryption == "crypt":
            try:
                import crypt
            except ImportError:
                raise RuntimeError(
                    "The htpasswd encryption method 'crypt' requires "
                    "the crypt() system support.")
            self.verify = functools.partial(self._crypt, crypt)
        else:
            raise RuntimeError(
                "The htpasswd encryption method '%s' is not "
                "supported." % self.encryption)
Example #58
0
def recommend_post():
    random_node = []
    current_username = session.get('username')

    if current_username:
        random_record = naive_rule(current_username)

        try:
            len_record = len(random_record)

            # The following is used for the experiment only
            session['number_of_posts_viewed'] += 1
            if session['number_of_posts_viewed'] >= 40:
                secret_code = bcrypt.encrypt(current_username)
                return render_template(
                    'recommend/naive_rule.html',
                    message=
                    f'You have already viewed all posts. If you are coming from Amazon Mturk, your secret code is {secret_code}'
                )

        except TypeError:
            secret_code = bcrypt.encrypt(current_username)
            return render_template(
                'recommend/naive_rule.html',
                message=
                f'You have already viewed all posts. If you are coming from Amazon Mturk, your secret code is {secret_code}'
            )

        if len_record >= 1:
            random_node = random_record['post']
            if random_node:
                if random_node.has_label('Fact'):
                    return redirect(
                        url_for('content.view_fact',
                                fact_id=random_node['id']))
                elif random_node.has_label('Question'):
                    return redirect(
                        url_for('content.view_question',
                                question_id=random_node['id']))

    return render_template(
        'recommend/naive_rule.html',
        message='You must be logged in to use this feature.')