Example #1
0
def update(db_session, user, new_password):
    check_password_format(user, new_password)

    # check actual password
    if user.hash and (user.hash == crypt(new_password, user.salt,
                                         1000).split('$').pop()):
        raise HTTPRequestError(
            400, "Please, choose a password"
            " that was not used before.")

    # check all old password from database
    if conf.passwdHistoryLen > 0:
        oldpwds = (db_session.query(PasswdInactive).filter_by(
            user_id=user.id).order_by(
                PasswdInactive.deletion_date.desc()).limit(
                    conf.passwdHistoryLen))

        for pwd in oldpwds:
            if pwd.hash == crypt(new_password, pwd.salt,
                                 1000).split('$').pop():
                raise HTTPRequestError(
                    400, "Please, choose a password"
                    " that was not used before")
    PasswdInactive.createInactiveFromUser(db_session, user)
    return create_pwd(new_password)
Example #2
0
def user_login(handler, username, password):
    """Looks for a user with the specified username and checks the specified password against the found user's password. Creates a token if the login is successful. """

    datastore_handler = handler.datastore_handler
    token = None
    body = None
    if '@' in username:
        yield ldap_login(handler)
        raise tornado.gen.Return()

    account_info = yield datastore_handler.find_user(username)

    invalid_acc_hash = crypt('__invalidpassword__')

    if not account_info:
        # Prevent timing attacks
        account_info = {
            'password_hash': invalid_acc_hash,
            'username': '******',
            'timestamp_created': 0
        }
    pw_hash = account_info['password_hash']

    if crypt(password, pw_hash) == pw_hash:
        token = yield get_or_create_token(datastore_handler,
                                          username,
                                          user_type=account_info['user_type'])
        raise tornado.gen.Return({
            'token': token,
            'user_type': account_info['user_type']
        })
    handler.status = 401
    raise Exception("Invalid password: " + password)
 def __tokenKey(self):
     if self.tokenKey is not None:
         return self.tokenKey
     password = Board.secret()
     s = Settings('telldus.api')
     tokenKey = s.get('tokenKey', '')
     if tokenKey == '':
         self.tokenKey = os.urandom(32)
         # Store it
         salt = os.urandom(16)
         key = PBKDF2(password, salt).read(32)
         pwhash = crypt(password)
         s['salt'] = base64.b64encode(salt)
         s['pw'] = pwhash
         # Encrypt token key
         cipher = AES.new(key, AES.MODE_ECB, '')
         s['tokenKey'] = base64.b64encode(cipher.encrypt(self.tokenKey))
     else:
         # Decode it
         salt = base64.b64decode(s.get('salt', ''))
         pwhash = s.get('pw', '')
         if crypt(password, pwhash) != pwhash:
             logging.warning('Could not decrypt token key, wrong password')
             return None
         key = PBKDF2(password, salt).read(32)
         enc = base64.b64decode(tokenKey)
         cipher = AES.new(key, AES.MODE_ECB, '')
         self.tokenKey = cipher.decrypt(enc)
     return self.tokenKey
Example #4
0
def UpdateFile(login, Pass, Filename):
    try:
        print("Hello?")
        global GLLOGIN, GLPASS, GLLOGINHASH, GLPASSHASH
        tcp_client = socket(AF_INET, SOCK_STREAM)
        tcp_client.connect((host_ip, server_port))
        x = Filename
        fileenc = FileBase64Enc(x)
        file = ''
        print(fileenc)
        for i in fileenc:
            string = str(i)[:len(str(i)) - 1]
            string = string[2:]
            file += string + '|'

        print(('U|' + str(pbkdf2.crypt(login, salt="NotASalt", iterations=150)) + '|' + str(
            pbkdf2.crypt(Pass, salt="NotASalt", iterations=150))))
        print("login = "******"\nPass = "******"U|" + str(login) + "|" + str(
            Pass) + "|", encoding="utf8") + bytes(x.split("/")[len(
            x.split("/")) - 1] + "|", encoding="utf8") + bytes(file, encoding="utf8"))
        print(path)
        received = tcp_client.recv(BUFFISZE)
        received = received.decode("utf8")
    except:
        print("Something went wrong")
    finally:
        tcp_client.close()
Example #5
0
 def UploadButtonClicked(self):
     global GLLOGINHASH, GLPASSHASH
     print("Upload button clicked")
     if Send_login(self.LoginText.text(), self.PassText.text()):
         GLLOGINHASH = pbkdf2.crypt(self.LoginText.text(), salt="NotASalt", iterations=150)
         GLPASSHASH = pbkdf2.crypt(self.PassText.text(), salt="NotASalt", iterations=150)
         self.ui.hide()
         thr.mainmenu.Show()
     else:
         print("Something went wrong")
Example #6
0
def authenticate(username, password):
    with open("users.json", mode="r") as f:
        users = json.loads(f.read())
        user = users.get(username, None)
    if user:
        if user['password'] == crypt(password, user['password']):
            return {"username": username, "full_name": user['full_name']}
    else:
        # constant time checker
        crypt(password)
    abort(401, "Bad username or password")
Example #7
0
def main():
    from pbkdf2 import crypt

    pwhash = crypt("secret")
    print pwhash

    alleged_pw = raw_input("Enter password: "******"Password good"
    else:
        print "Invalid password"
def signupresult():
    allowed_formats = [".png", ".jpg", ".jpeg", ".gif", ".JPG"]
    e = request.forms.get("signupemail")
    p = request.forms.get("signuppassword")
    pr = request.forms.get("signuppasswordr")
    avt = request.files.pic
    filename = avt.filename
    filenamewoe, ext = os.path.splitext(avt.filename)
    mfilename = str(random.randint(0, 999999)) + str(ext)
    connection = sqlite3.connect("/home/JackZhang1012/mysite/users.db")
    c = connection.cursor()
    c.execute("SELECT * from account WHERE user_email=?", (e, ))
    row = c.fetchone()
    if row != None:
        return '''
               <p>Email used.</p>
               <meta http-equiv="refresh" content="2;url=/signup"/>
               '''
    if p != pr:
        return template("/home/JackZhang1012/mysite/signupw")
    else:
        if ext not in allowed_formats:
            return "<p>Invalid format.</p>"
        else:
            file_path = "/home/JackZhang1012/mysite/assets/img/avatars/"
            avt.save(file_path + mfilename)
            cp = crypt(p)
            connection = sqlite3.connect("/home/JackZhang1012/mysite/users.db")
            cursor = connection.cursor()
            cursor.execute(
                "insert into account (user_email, user_password) values (?,?)",
                (e, cp))
            connection.commit()
            cursor.close()
            return template("/home/JackZhang1012/mysite/signupr")
Example #9
0
   def checkInternalUser(self,username,password):
      """
      Prueft ob interner User einlogen kann
      @param username                  username aus CGI
      @param password                  Passwrot aus CGI

      @return                          True/False

      HINT:
           setzt wenn OK Sessionattribute user

      """
      config = self.main.config
      
      userinfo = self.main.authen.getUserinfo(user=username)

      if config.authenMethod == 'md5':            
         hashPassword =  hashlib.md5(password).hexdigest()

         
      elif config.authenMethod == 'pbkdf2':
         auxPassword = crypt(password,config.authenSalt,10000)
         #raise Exception('pbkdf2:{'+auxPassword+'}')
         hashPassword = auxPassword
         
      else:
         raise ValueError('Methode bei Passwortverschluesselung fehlt (erlaubt md5,pbkdf2)')


      if  userinfo.get('user') == username and userinfo.get('password') == hashPassword :
         self.main.setAttribute('user',username)
         self.main.setAttribute('rights',userinfo.get('rights'))
         return True
      else:
         return False
Example #10
0
    def set_password(self,
                     raw_password=None,
                     hashed_password=None,
                     cached_password=None):
        """Set a password with the raw password string, or the pre-hashed password.
        If using the raw string, """
        assert hashed_password is None or settings.DEBUG, "Only use hashed_password in debug mode."
        assert raw_password is not None or hashed_password is not None, "Must be passing in raw or hashed password"
        assert not (raw_password is not None and hashed_password
                    is not None), "Must be specifying only one--not both."

        if raw_password:
            verify_raw_password(raw_password)

        if hashed_password:
            self.password = hashed_password

            # Can't save a cached password from a hash, so just make sure there is none.
            # Note: Need to do this, even if they're not enabled--we don't want to risk
            #   being out of sync (if people turn on/off/on the feature
            CachedPassword.invalidate_cached_password(user=self)

        else:
            n_iters = settings.PASSWORD_ITERATIONS_TEACHER_SYNCED if self.is_teacher else settings.PASSWORD_ITERATIONS_STUDENT_SYNCED
            self.password = crypt(raw_password, iterations=n_iters)

            if self.id:
                CachedPassword.set_cached_password(self, raw_password)
Example #11
0
    def set_cached_password(cls, user, raw_password):
        assert user.id, "Your user must have an ID before calling this function."

        if not cls.is_enabled():
            # Must delete, to make sure we don't get out of sync.
            cls.invalidate_cached_password(user=user)

        else:
            try:
                # Set the cached password.
                n_cached_iters = cls.iters_for_user_type(user)
                # TODO(bcipolli) Migrate this to an extended django class
                #   that uses get_or_initialize
                cached_password = get_object_or_None(
                    cls, user=user) or cls(user=user)
                cached_password.password = crypt(raw_password,
                                                 iterations=n_cached_iters)
                cached_password.save()
                logging.debug(
                    "Set cached password for user=%s; iterations=%d" %
                    (user.username, n_cached_iters))
            except Exception as e:
                # If we fail to create a cache item... just keep going--functionality
                #   can still move forward.
                logging.error(e)
Example #12
0
    def reset_password(self,cursor,connection,token):
        token_encode = jwt.decode(token,KEY_SECRET)

        self.mail = token_encode['email']
        
        query_token_valido = """SELECT token FROM usuario where correo=%s"""
        cursor.execute(query_token_valido,(self.mail,))
        token_value = cursor.fetchone()
        token_value = token_value['token'] if token_value else 0
        if token_value == 0:
            return {
                'status':400,
                'msg':'Ya realizo cambio de contraseña',
                'data':[]
            }

        passEncript = crypt(self.password,'PORTAFOLIO',400)
        query_update_password = """UPDATE usuario set password = %s,token=0 where correo = %s """
        cursor.execute(query_update_password,(passEncript,self.mail))
        connection.commit()
        
        return {
                'status':200,
                'msg':'Contraseña actualizada correctamente',
                'data':[]
            }
Example #13
0
def verify_pass(email, pw):
    user = User.query.filter(User.email == email).first().__dict__
    pw_hash = user["password"]
    # print(crypt(pw))
    if (pw_hash == crypt(pw, pw_hash)):
        return True
    return False
Example #14
0
def post_login():
    email = flask.request.json['email']
    password = flask.request.json['password']

    try:
        conn = dbh()
        with conn.cursor() as c:
            sql = "SELECT * FROM users WHERE email=%s"
            c.execute(sql, (email, ))
            user = c.fetchone()
            if not user:
                raise HttpException(requests.codes['forbidden'],
                                    "authentication failed")

            if pbkdf2.crypt(password, user["super_secure_password"]
                            ) != user["super_secure_password"].decode("ascii"):
                raise HttpException(requests.codes['forbidden'],
                                    "authentication failed")

            flask.session['user_id'] = user["id"]

    except MySQLdb.Error as err:
        app.logger.exception(err)
        raise HttpException(requests.codes['internal_server_error'],
                            "db error")

    return message_response("ok")
Example #15
0
    def set_password(self, raw_password=None, hashed_password=None, cached_password=None):
        """Set a password with the raw password string, or the pre-hashed password.
        If using the raw string, """
        assert hashed_password is None or settings.DEBUG, "Only use hashed_password in debug mode."
        assert raw_password is not None or hashed_password is not None, "Must be passing in raw or hashed password"
        assert not (raw_password is not None and hashed_password is not None), "Must be specifying only one--not both."

        if raw_password:
            verify_raw_password(raw_password)

        if hashed_password:
            self.password = hashed_password

            # Can't save a cached password from a hash, so just make sure there is none.
            # Note: Need to do this, even if they're not enabled--we don't want to risk
            #   being out of sync (if people turn on/off/on the feature
            CachedPassword.invalidate_cached_password(user=self)

        else:
            n_iters = (
                settings.PASSWORD_ITERATIONS_TEACHER_SYNCED
                if self.is_teacher
                else settings.PASSWORD_ITERATIONS_STUDENT_SYNCED
            )
            self.password = crypt(raw_password, iterations=n_iters)

            if self.id:
                CachedPassword.set_cached_password(self, raw_password)
Example #16
0
    def post(self):
        """Create a new user."""
        body = self.require_body_schema({
            "type": "object",
            "properties": {
                "username": {
                    "type": "string",
                    "pattern": "^[^:\s]*$",
                    "maxLength": 32,
                    "minLength": 1
                },
                "password": {
                    "type": "string",
                    "minLength": 1
                },
            },
            "required": ["username", "password"],
        })

        with self.get_db_session() as session:
            # check if username already exists
            if session.query(User).get(body["username"]) is not None:
                raise HTTPError(400, reason="Username already registered")
            # save new user
            password_hash = pbkdf2.crypt(body["password"])
            new_user = User(body["username"], password_hash)
            session.add(new_user)
            session.commit()
            logger.info("Registered new user '{}'"
                        .format(body["username"].encode('utf-8')))
        self.set_status(201)
Example #17
0
    def create_new_user(username, email, password):
        """
        Add a new user
        :param username:
        :param email:
        :param password:
        :return: Json Object {username, token}| {error}
        """

        password = password.strip()

        if not re.match("^[a-zA-Z0-9_]*$", username):
            raise InvalidUsage(
                'the only special char available for username is _')

        if len(password) < 8:
            raise InvalidUsage('password must be greater than 7 chars')

        if not User.validate_new_email(email):
            raise InvalidUsage('email already exists or not valid')

        if User.get_by_id(username) is not None:
            raise InvalidUsage('username already exists')

        key = ndb.Key(User, username)
        new_user = User(key=key,
                        username=username,
                        email=email,
                        password=pbkdf2.crypt(
                            password, iterations=config.CRYPT_LOG_ROUNDS))
        new_user.put()
        token = new_user.encode_auth_token()
        return {'username': username, 'token': token}
Example #18
0
 def check_password(self, raw_password):
     if self.password.split("$", 1)[0] == "sha1":
         # use Django's built-in password checker for SHA1-hashed passwords
         return check_password(raw_password, self.password)
     if self.password.split("$", 2)[1] == "p5k2":
         # use PBKDF2 password checking
         return self.password == crypt(raw_password, self.password)
Example #19
0
 def check_password(self, raw_password):
     if self.password.split("$", 1)[0] == "sha1":
         # use Django's built-in password checker for SHA1-hashed passwords
         return check_password(raw_password, self.password)
     if self.password.split("$", 2)[1] == "p5k2":
         # use PBKDF2 password checking
         return self.password == crypt(raw_password, self.password)
Example #20
0
def login_standard():
    username = request.form.get('username', None)
    password = request.form.get('password', None)
    honey_pot = request.form.get('xhp', None)

    # check for bots
    if honey_pot:
        return redirect('http://spam.abuse.net/overview/spambad.shtml')

    if username and password:
        username = username.strip()
        password = password.strip()

        try:
            user = User.select().where(User.username == username).get()
        except User.DoesNotExist:
            msg = u'Username was not found please sign up below.'
            flash(msg, 'warning')
            return redirect(url_for('sign_up'))

        if user.password == crypt(password, user.password):
            session['uid'] = user.id
            msg = u'Successfully logged in.'
            flash(msg, 'success')
            return redirect(url_for('index'))

        msg = u'Incorrect password'
        flash(msg, 'danger')
        return redirect(url_for('login'))

    msg = u'Please fill out the username and password fields'
    flash(msg, 'danger')
    return redirect(url_for('login'))
    def require_auth(self, session):
        """Return the authorized user's username.

        If authorization fails, raise HTTPError. This doesn't attempt to
        gracefully handle invalid authentication headers.

        HTTP basic auth is used. If the auth method is xBasic, no
        WWW-Authenticate header will be sent for failed authentication
        attempts, as a workaround for using the API via JavaScript.

        Furthermore, doing authentication in this way will protect us from
        general CSRF attacks. The user's browser will not automatically include
        our auth header in arbitrary requests to our API, even when the user is
        logged in due to our usage of xBasic.
        """
        try:
            auth_header = self.request.headers.get("Authorization")
            if auth_header is None:
                raise ValueError("No Authorization header provided")
            auth_type, auth_digest = auth_header.split(" ", 1)
            user, passwd = base64.decodestring(auth_digest).split(":", 1)
            if auth_type not in ["Basic", "xBasic"]:
                raise ValueError("Authorization type is not Basic")
            self.use_www_authenticate = auth_type == "Basic"
            user_model = session.query(database.User).get(user)
            if user_model is None:
                raise ValueError("Invalid username or password")
            passwd_hash = user_model.password_hash
            if pbkdf2.crypt(passwd, passwd_hash) != passwd_hash:
                raise ValueError("Invalid username or password")
        except ValueError as e:
            msg = "Authorization failed: {}".format(e)
            raise tornado.web.HTTPError(401, msg)
        else:
            return user
Example #22
0
def reset_token(token):
    """Reset the password using the token from the link received in the password-reset email."""
    # If the user is logged in, send them to homepage
    if current_user():
        return redirect("/")

    # Check the token for authenticity
    user = User.verify_reset_token(token)
    if user is None:
        return jsonify({'err': 'This is an invalid or expired token.'
                        }), HTTPStatus.BAD_REQUEST

    password1 = request.form.get('password1')
    password2 = request.form.get('password2')

    if password1 != password2:
        return jsonify({'err': 'The passwords don\'t match'
                        }), HTTPStatus.NOT_ACCEPTABLE
    elif password1 is None:
        return jsonify({'err': 'The passwords cannot be empty.'
                        }), HTTPStatus.NOT_ACCEPTABLE

    user.password = crypt(password1)  # update user's password into database
    db.session.commit()
    return redirect('/login')
Example #23
0
 def _hash_password(password):
     """
     将用户输入的密码 加盐
     :param password:
     :return:
     """
     return pbkdf2.crypt(password, iterations=0X2537)
Example #24
0
    def post(self):
        """Create a new user."""
        body = self.require_body_schema({
            "type": "object",
            "properties": {
                "username": {
                    "type": "string",
                    "pattern": "^[^:\s]*$",
                    "maxLength": 32,
                    "minLength": 1
                },
                "password": {
                    "type": "string",
                    "minLength": 1
                },
            },
            "required": ["username", "password"],
        })

        with self.get_db_session() as session:
            # check if username already exists
            if session.query(User).get(body["username"]) is not None:
                raise HTTPError(400, reason="Username already registered")
            # save new user
            password_hash = pbkdf2.crypt(body["password"])
            new_user = User(body["username"], password_hash)
            session.add(new_user)
            session.commit()
            logger.info("Registered new user '{}'".format(
                body["username"].encode('utf-8')))
        self.set_status(201)
Example #25
0
def register():
    password = request.form.get("password")
    password2 = request.form.get("password2")
    email = request.form.get("email")
    firstname = request.form.get("firstname")
    lastname = request.form.get("lastname")
    # profile_photo = request.form.get("profilePhoto")
    # role = request.form.get("role")
    # departament = request.form.get("departament")

    if len(password) < 8:
        return redirect("/")
    if password != password2:
        return redirect("/")

    user = User(
        password=crypt(password),
        email=email,
        firstname=firstname,
        lastname=lastname,
        verified=False,  # By default    =>  you should validate the user!
        # asii_members_data={
        #     "profilePhoto": profile_photo,
        #     "role": role,
        #     "departament": departament
        # }
    )

    db.session.add(user)
    db.session.commit()
    session['id'] = user.id
    return redirect('/')
Example #26
0
def hash_password(pwraw):
    """ Hash a unique email and password of user """

    hashCrypt = crypt(pwraw, defaultConfig.config['salt'], iterations=567)
    h = hashlib.md5()
    h.update(hashCrypt)
    return h.hexdigest()
Example #27
0
 def set_foris_password(cls, password):
     encrypted_pwd = pbkdf2.crypt(password)
     if not (uci_set("foris.auth", "config", cls.config_directory)
             and uci_set("foris.auth.password", encrypted_pwd,
                         cls.config_directory)
             and uci_commit(cls.config_directory)):
         raise InitException("Cannot set Foris password.")
 def login_user(cls, email, password):
     try:
         user = cls.query.filter_by(email=email).one()
     except exc.InvalidRequestError:
         return None
     if pbkdf2.crypt(password, user.pwhash) == user.pwhash:
         return user
     return None
Example #29
0
 def test_auth(self):
     passwd = 'unit_test_pass'
     u = User(nickname = 'UnitTester', email = '*****@*****.**', pwhash=crypt(passwd))
     db.session.add(u)
     db.session.commit()
     u = User.query.filter_by(email='*****@*****.**').first()
     assert u is None
     assert authenticate('*****@*****.**', passwd)
Example #30
0
def index():
    if 'profile_update' in request.form:
        profilecharge_client.update(g.user.person.username, request.form['profile_update'], 
                                    {g.user.token: crypt(g.user.token)})
        ## also update the cached version (see login.py)
        g.user.person.profile = request.form['profile_update']

    return render_template('index.html')
Example #31
0
 def set_foris_password(cls, password):
     encrypted_pwd = pbkdf2.crypt(password)
     if not (
         uci_set("foris.auth", "config", cls.config_directory)
         and uci_set("foris.auth.password", encrypted_pwd, cls.config_directory)
         and uci_commit(cls.config_directory)
     ):
         raise InitException("Cannot set Foris password.")
Example #32
0
 def save_password(self, new_password):
     """
     Store a new password.
     """
     # 55 iterations takes about 100 ms on a Netgear WNDR3800 or about 8ms on a
     # Core2 Duo at 1200 MHz.
     hashed = pbkdf2.crypt(new_password, iterations=55)
     self.write(self.password_filename, hashed)
 def create(cls, challenge, team, answer_text):
     answer = cls()
     answer.challenge = challenge
     answer.team = team
     answer.timestamp = datetime.datetime.utcnow()
     answer.answer_hash = pbkdf2.crypt(team.name + answer_text)
     db.session.add(answer)
     return answer
Example #34
0
 def test_create_user(self):
     """Should create a user with the correct data"""
     expected_user_data = {
         'username': USER['username'],
         'password': crypt(USER['password'], SECRET_KEY),
         'enabled': "True"
     }
     self.assertEqual(User.get(USER['username']), expected_user_data)
Example #35
0
def check_hash(password, hash):
    """Validate a given password

    This function is used to check whether password matches the given hash.
    The salt and iteration count are stored as part of the hash as per the
    pbkdf2 spec.
    """
    return (crypt(password, hash) == hash)
Example #36
0
    def _check_password(self, password):
        hash_check = pbkdf2.crypt(password, self.salt, 1000)
        if hash_check ==self.pass_hash:
            valid=True
        else:
            valid=False

        return valid
Example #37
0
    def generate_password_hash(self, password, salt=None, iterations=None):

        if iterations is None:
            iterations = self._iterations
        if salt is None:
            salt = token_hex()

        return pbkdf2.crypt(password, salt=salt, iterations=iterations)
Example #38
0
 def save_password(self, new_password):
     """
     Store a new password.
     """
     # 55 iterations takes about 100 ms on a Netgear WNDR3800 or about 8ms on a
     # Core2 Duo at 1200 MHz.
     hashed = pbkdf2.crypt(new_password, iterations=55)
     self.write(self.password_filename, hashed)
Example #39
0
def edit_number_plate_lg(req):	 
 
	if 'user_id' in req.session  and ('access_level' in req.session): 	 

		if req.method == "GET":				 			
			return HttpResponseRedirect('/store/plate-numbers/')

		elif req.method == "POST" and req.POST:				 
			form = PasswordTextForm(req.POST) 

			if form.is_valid():
				plate_id = req.POST.get("plate_number_id")				 
				 
				local_government = req.POST.get("local_government")
				paswd = form.cleaned_data.get("password")



				try:
					user_id = req.session['user_id']
					user = User.objects.get(id = user_id)

					if user.password == crypt(paswd, user.password):
						
						number_plate_obj = NumberPlate.objects.get(id = plate_id)

						notification =  Notification(notification_for= "Number Plate", notification_type = "Edit", notification_txt = "User with ID:"+str(user.id)+
							" edited Plate Number PN:"+str(number_plate_obj.number_plate)+" From Local Gov = "+ number_plate_obj.local_government+ ", Local Gov = "+local_government, generated_by= user)
 

						number_plate_obj.local_government = local_government

						notification.save()						
						number_plate_obj.save()
						messages.info(req, "record updated", extra_tags = "record_updated")
						return HttpResponseRedirect('/store/plate-numbers/')
 
					else:
						 
						messages.info(req, "Pease correct Password", extra_tags = "wrong_pass")
						return HttpResponseRedirect('/store/plate-numbers/')

				except User.DoesNotExist:
					messages.info(req, "Pease correct Password", extra_tags = "wrong_pass")
					return HttpResponseRedirect('/store/plate-numbers/')

				except IntegrityError as e:
				 
					messages.success(req, "Charge already exist", extra_tags = "record_already_created")
					return HttpResponseRedirect('/store/plate-numbers/')
			else:
			 
				messages.info(req, "Pease correct Data", extra_tags = "wrong_data")
				return HttpResponseRedirect('/store/plate-numbers/')
	else:
		 		 
		return render(req, 'login.html')
Example #40
0
    def set_password(self, password, secret):
        """

        :param password:
        :param secret:
        :return:
        """
        self.password_hash = crypt(word=password, salt=secret)
        return self.password_hash
Example #41
0
def isValidCredentials(user,passwd):
    store = db.select('stores', where='pin=$user', vars=locals())
    if (store is None or len(store) == 0):
        return -1
    store = store[0]
    actual = store['password']
    check = crypt(passwd,actual)
    if (check == actual): return store['acc_id']
    else: return -1
 def create(cls, name, description, points, answer, cid, unlocked=False):
     challenge = cls()
     challenge.name = name
     challenge.description = description
     challenge.points = points
     challenge.answer_hash = pbkdf2.crypt(answer)
     challenge.cat_cid = cid
     challenge.unlocked = unlocked
     db.session.add(challenge)
     return challenge
Example #43
0
def valid_password(user_pw_entry):
    """ Without SSL this is not secure!

    This is a demonstration of the idea behind password hashing, NOT a full
    implementation. Flask already offers login functionality in the flask-login
    package (https://flask-login.readthedocs.org/en/latest/).
    """
    user_entry_pw_hash = crypt(user_pw_entry, settings.FLASK_SECRET_KEY)
    app.logger.info(user_entry_pw_hash)
    return user_entry_pw_hash == settings.PASSWORD_HASH
Example #44
0
def password():
    form = forms.PasswordUser(request.form)
    if request.method == 'POST' and form.validate():
        query = "SELECT * FROM users WHERE id=%s"
        user = models.get_or_404(query, [g.user.id], models.User)
        user.password = crypt(form.password.data, "s3c3tS4lT")
        user.update()

        return redirect("/users/" + str(user.id))

    return render_template('edit_user.html', form=form)
Example #45
0
def get_application(handler):
    """Return Tornado application with demo user."""
    create_session = database.initialize_db('sqlite://')
    app = Application([("/", handler, dict(create_session=create_session,
                                           tasks=None, celery_poller=None))])
    session = create_session()
    # TODO: better way of creating the demo user
    session.add(database.User("demo", pbkdf2.crypt("demo")))
    session.commit()
    session.close()
    return app
Example #46
0
def genpass(password, *, nonce='', salt='', iterations=0x10000):
    '''
    >>> genpass('')
    '9G39QAZXnhIqc7y.3gF5fMbbG752/tve'
    >>> genpass('password', nonce='nonce', salt='salt', iterations=1)
    'ztWpkVwEFEmoWkX.7Vk6e5oFkVgFPTsh'

    '''
    result = pbkdf2.crypt('{}{}'.format(password, nonce),
                          salt=salt, iterations=iterations)
    return result.split('$')[4]
Example #47
0
 def login_user(cls, email, password):
     try:
         user = cls.query.filter_by(email=email).one()
     except exc.InvalidRequestError:
         return None
     if pbkdf2.crypt(password, user.pwhash) == user.pwhash:
         if flask.has_request_context():
             user.last_login_ip = flask.request.remote_addr
             db.session.commit()
         return user
     return None
Example #48
0
    def set_password(self, raw_password=None, hashed_password=None):
        """Set a password with the raw password string, or the pre-hashed password."""

        assert hashed_password is None or settings.DEBUG, "Only use hashed_password in debug mode."
        assert raw_password is not None or hashed_password is not None, "Must be passing in raw or hashed password"
        assert not (raw_password is not None and hashed_password is not None), "Must be specifying only one--not both."

        if hashed_password:
            self.password = hashed_password
        else:
            self.password = crypt(raw_password, iterations=Settings.get("password_hash_iterations", 2000 if self.is_teacher else 1000))
Example #49
0
 def create(cls, challenge, team, answer_text):
     answer = cls()
     answer.first_blood = (app.config.get('FIRST_BLOOD')
             if not challenge.solves else 0)
     answer.challenge = challenge
     answer.team = team
     answer.timestamp = datetime.datetime.utcnow()
     answer.answer_hash = pbkdf2.crypt(team.name + answer_text)
     if flask.request:
         answer.submit_ip = flask.request.remote_addr
     db.session.add(answer)
     return answer
Example #50
0
    def test_crypt(self):
        result = crypt("secret")
        self.assertEqual(result[:6], "$p5k2$")

        result = crypt("secret", "XXXXXXXX")
        expected = "$p5k2$$XXXXXXXX$L9mVVdq7upotdvtGvXTDTez3FIu3z0uG"
        self.assertEqual(expected, result)

        # 400 iterations (the default for crypt)
        result = crypt("secret", "XXXXXXXX", 400)
        expected = "$p5k2$$XXXXXXXX$L9mVVdq7upotdvtGvXTDTez3FIu3z0uG"
        self.assertEqual(expected, result)

        # 400 iterations (keyword argument)
        result = crypt("spam", "FRsH3HJB", iterations=400)
        expected = "$p5k2$$FRsH3HJB$SgRWDNmB2LukCy0OTal6LYLHZVgtOi7s"
        self.assertEqual(expected, result)

        # 1000 iterations
        result = crypt("spam", "H0NX9mT/", iterations=1000)
        expected = "$p5k2$3e8$H0NX9mT/$wk/sE8vv6OMKuMaqazCJYDSUhWY9YB2J"
        self.assertEqual(expected, result)

        # 1000 iterations (iterations count taken from salt parameter)
        expected = "$p5k2$3e8$H0NX9mT/$wk/sE8vv6OMKuMaqazCJYDSUhWY9YB2J"
        result = crypt("spam", expected)
        self.assertEqual(expected, result)
Example #51
0
 def save_password(self, new_password):
     """
     Store a new password.
     Returns True is the password was stored and False if the password 
     didn't fulfil all criteria.
     """
     if len(new_password) < self.PASSWORD_LENGTH_MIN:
         return False
     # 55 iterations takes about 100 ms on a Netgear WNDR3800 or about 8ms on a
     # Core2 Duo at 1200 MHz.
     hashed = pbkdf2.crypt(new_password, iterations=55)
     self.write(self.password_filename, hashed)
     return True
 def create(cls, name, description, points, answer, cid, unlocked=False):
     challenge = cls()
     challenge.name = name
     challenge.description = description
     challenge.points = points
     challenge.answer_hash = pbkdf2.crypt(answer)
     challenge.cat_cid = cid
     challenge.unlocked = unlocked
     weight = db.session.query(db.func.max(Challenge.weight)).scalar()
     challenge.weight = (weight + 1) if weight else 1
     challenge.prerequisite = ''
     db.session.add(challenge)
     return challenge
Example #53
0
def verify_password(username, alleged_password):
    try:
        user = User.select().where(User.username == username).get()
        verification = (crypt(alleged_password, user.password) == user.password)
        logging.debug('verify_password: username={}, encrypted_password={}, alleged_password={}, verification={}'.format(username, user.password, alleged_password, verification))

        if verification:
            AuthExt.save(user=user)

        return verification
    except Exception as e:
        logging.exception('verify_password')
        return False
Example #54
0
def login():
    if request.method == 'POST':
        someusername = request.form['inputEmail']
        alleged_password = request.form['inputPassword']
        user = User.objects(username=someusername).first()
        if user != None and user.password == crypt(alleged_password, user.password):
            session['userid'] = str(user.id)
            return redirect(url_for('index'))
        return render_template('login.html', data={"message":"Wrong email or password"})
    else:
        if 'userid' in session:
            return render_template('error.html', data={"error":"You're already logged in..."})
        else:
            return render_template('login.html', data={})
def transfer():
    warning = None
    try:
        if 'recipient' in request.form:
            zoobars = eval(request.form['zoobars'])
            bank_client.transfer(g.user.person.username, request.form['recipient'], zoobars,
                              {g.user.token: crypt(g.user.token)})   
            
            warning = "Sent %d zoobars" % zoobars
    except (KeyError, ValueError, AttributeError, NameError) as e:
        traceback.print_exc()
        warning = "Transfer to %s failed" % request.form['recipient']

    return render_template('transfer.html', warning=warning)