Beispiel #1
0
    def hash_text(self, h):
        klass = RedisObject.klass(h)
        max_length = 2048

        if not klass or klass not in [Album, File]:
            return {'error': 404}, 404

        properties = ["title", "description"]
        if not any(prop in request.form for prop in properties):
            return {'error': 400}, 400

        try:
            o = klass.from_hash(h) # We don't care about the object type
            if not check_password_hash(o.ip, get_ip()):
                return {'error': 401}, 401
        except:
            return {'error': 401}, 401

        if o.text_locked:
            return {'error': 408}, 408


        for prop in properties:
            if prop in request.form:
                data = request.form[prop]
                if len(data) > max_length:
                    return {'error': 414}, 414

                setattr(o, prop, data)
        o.save()
        return {'status': 'success'}
Beispiel #2
0
def login():
    """
    Check to see if the entered username is in the database.  If no, present an error.
    If the username is present in the database, check that the given password corresponds
    to the given username.  If so, log in, otherwise present an error.
    """
    error = None
    if request.method == 'POST':
        cur = g.db.execute('select username, password, gravataremail, flag_approval, flag_admin from userPassword where username=?',
                           [request.form['username']])
        row = cur.fetchone()

        if row is not None:
            # if the user is found
            user = {'username': row[0], 'password': row[1], 'gravataremail': row[2], 'flag_approval': row[3], 'flag_admin': row[4]}

            if not check_password_hash(user['password'], request.form['password']):
                # if the password hash in the database does not correspond to the hashed form of the given password
                error = 'Invalid password'
            elif user['flag_approval'] != 1:
                error = 'Please contact admin for permission to access'
            else:
                session['logged_in'] = True
                if user['flag_admin']==1:
                    session['admin'] = True
                session['username'] = user['username']
                session['gravataremail'] = user['gravataremail']
                session['admin'] = row[4]
                flash('You were logged in')
                return redirect(url_for('show_entries'))
        else:
            # TODO username needs to be made unique in the database,
            # TODO otherwise this method will malfunction
            error = 'Invalid username'
    return render_template('login.html', error=error)
Beispiel #3
0
def _album_params(album):
    items = album.items
    if not items:
        abort(404)
    files = objects[Album](album)['files']

    types = set([f.processor for f in items])
    filename = album.hash
    subtitles = False
    for f in items:
        metadata = {}
        if f.metadata and f.metadata != 'null':
            try:
                metadata = json.loads(f.metadata)
            except:
                pass
        if 'has_subtitles' in metadata:
            subtitles = metadata['has_subtitles']

    can_delete = None
    try:
        if request.cookies.get('hist-opt-out', '0') == '1':
            can_delete = check_password_hash(f.ip, get_ip())
    except:
        pass

    if album.description:
        album.description = slimdown.convert(album.description)

    return vars()
Beispiel #4
0
    def validate_login(self, field):
        user = self.get_user()

        if user is None:
            raise validators.ValidationError(u'Invalid User')

        # compare plaintext to hashed version
        if not check_password_hash(user.password, self.password.data):
            raise validators.ValidationError(u'Invalid Password')
Beispiel #5
0
    def check_password(self, plaintext):
        """
        Check that a plaintext password is equal to the hashed password.

        At this stage, this method is not being used except in testing.
        :param plaintext: plaintext password to check
        :return: Boolean value; if true, then the plaintext and hash correspond, else false.
        """
        return check_password_hash(self.password, plaintext)
Beispiel #6
0
def auth_user(username, password):
    try:
        password_hash = User.query.filter_by(username=username).first()
        password_hash = password_hash.password
        pw_result = check_password_hash(str(password_hash), str(password))
        return pw_result
    except Exception as inst:
        print("Error Type:", type(inst))
        print("Error Arguments:", inst.args)
        return False
Beispiel #7
0
    def check_password(self, plaintext):
        """Check a plaintext password against a stored password hash.

        Args:
            plaintext: A plaintext password

        Returns:
            A boolean value indicating if the plaintext password matches the
            stored password hash.
        """
        return check_password_hash(self.password, plaintext)
Beispiel #8
0
    def checkPassword(self, plainTextPassword):
        """ Check a plain text password against a hashed password.
        
        Args:
            plainTextPassword (str): The plain text password to test.

        Returns:
            bool: True if the password matches the instance of the user.
            
        """
        return check_password_hash(self.password, plainTextPassword)
 def test_check_hash(self):
     pw_hash = self.bcrypt.generate_password_hash('secret')
     # check a correct password
     self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret'))
     # check an incorrect password
     self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2'))
     # check unicode
     pw_hash = self.bcrypt.generate_password_hash(u'\u2603')
     self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603'))
     # check helpers
     pw_hash = generate_password_hash('hunter2')
     self.assertTrue(check_password_hash(pw_hash, 'hunter2'))
Beispiel #10
0
    def delete(self, h):
        klass = RedisObject.klass(h)

        if not klass:
            return {'error': 404}, 404
        try:
            o = klass.from_hash(h)
            if not check_password_hash(o.ip, get_ip()):
                return {'error': 401}, 401
        except:
            return {'error': 401}, 401

        deletion_procedures[klass](o)
        return {'status': 'success'}
Beispiel #11
0
def login():
    error = None
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter_by(name=request.form['username']).first()
            if user is not None and check_password_hash(user.password, request.form['password']):
                # session['logged_in'] = True
                login_user(user)
                flash('You were logged in.')
                return redirect(url_for('todo.todo_lst'))
            else:
                error = 'Invalid Credentials. Please try again.'

    return render_template('login.html', form=form, error=error)
Beispiel #12
0
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("your email or password doesn't match", "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash('You in bruh. Damn straight!', 'success')
                return redirect(url_for('stream'))
            else:
                flash("your email or password doesn't match", "error")
    return render_template('login.html', form=form)
Beispiel #13
0
def login():
    payload = request.get_json()
    try:
        #look for user by username
        user = models.User.get(models.User.username== payload['username'])
        user_dict = model_to_dict(user)
        if (check_password_hash(user_dict['password'], payload['password'])):
            del user_dict['password'] 
            login_user(user)
            return jsonify(data=user_dict, status={"code": 200, "message": "Log in Successful"})
        else:
            return jsonify(data={}, status={"code": 400, "message": "Username or password incorrect"})
    except models.DoesNotExist:
        return jsonify(data={}, status={"code": 400, "message": "Username or password incorrect"})
        
Beispiel #14
0
def login():
    password = request.json.get('password')
    cell = request.json.get('cell')
    if None in [password, cell]:
        return response_json(LOST_REQUIRED_FIELD)

    user = User.query.filter_by(cell=cell).first()
    if not user:
        return USER_NOT_EXIST
    if not check_password_hash(user.password, password):
        return USER_WRONG_PASSWORD

    login_user(user)

    return response_json(data=dict(id=user.id))
Beispiel #15
0
	def validate_password(form, field):
		user = Users.query.filter_by(nickname=form.username.data).first()
		if user is None:
			loginError()

		# Handle flask's new annoying way of mis-packing password strings. Sigh.
		if user.password.startswith("\\x"):
			print("Mis-packed password! Fixing!")
			old = user.password
			user.password = binascii.unhexlify(user.password[2:]).decode("utf-8")
			print("Old: ", old, "new: ", user.password)
			db.session.commit()

		if not check_password_hash(user.password.encode("UTF-8"), form.password.data.encode("UTF-8")):
			loginError()
Beispiel #16
0
def login():
    if request.method == "POST":
        name = request.form['username']
        password = request.form['password']

        try:
            user = User.get(User.username == name)
            if check_password_hash(user.password, password):
                # flash("Loggin Successful!")
                session['logged_in'] = True
                session['username'] = name
                return redirect(url_for('home'))
        except User.DoesNotExist:
            flash("Invalid username or password")
    return render_template("login.html")
Beispiel #17
0
def test_rest_hash_attribute(app, rest_cleanup):
    # check that hash attribute is correctly applied and can be matched with check_password_hash
    # also verify updates to hash are applied correctly through model

    from flask_bcrypt import check_password_hash

    # create an object with hash 'hash1' and save
    t = Rest_Secure.load(key="key1")
    t.hash = "hash1"
    assert t.save()

    # read back the object
    t = Rest_Secure.load(key="key1")
    assert t.exists()
    logger.debug("original hash: %s", t.hash)
    assert check_password_hash(t.hash, "hash1")

    # update the hash to 'hash2' and recheck
    t.hash = "hash2"
    assert t.save()
    t = Rest_Secure.load(key="key1")
    assert t.exists()
    logger.debug("updated hash: %s", t.hash)
    assert check_password_hash(t.hash, "hash2")
Beispiel #18
0
    def post(self):
        print('user login route hit')
        args = self.reqparse.parse_args()
        print(args)
        user = models.User.get(username=args.username)
        candidate = args['password']
        check = check_password_hash(user.password, candidate)
        print(check)
        if check == True:
            print(user.username, 'this is the user object')
            print(args.password, 'this is args pw')
            login_user(user)
            return marshal(user, user_fields), 201

        print('wrong password ya goof!')
Beispiel #19
0
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.username == form.username.data)
        except models.DoesNotExist:
            flash('User is not exist!!')
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("you are login!!")
                return redirect(url_for('index'))
            else:
                flash("Pasword is not correct!!")
    return render_template('login.html', form=form)
Beispiel #20
0
def api_vald(api_key, secret_key):
    try:
        api_auth = mydb.Os_ver.find_one({"api_key": api_key}, {"_id": 0})
        if api_auth:
            key_db = mydb.Os_ver.find_one({"api_key": api_key})
            secret_db = key_db['api_key']
            key_verf = check_password_hash(secret_key, secret_db)
            if key_verf:
                return "Api key Verified"
            else:
                return "Key Mismatch"
        else:
            return "Key not Found"
    except Exception as e:
        return "Error Occured: {}".format(str(e))
Beispiel #21
0
    def is_password_valid(cls, hash_password: str, password: str) -> bool:
        """is_password_valid(str hash_password, str password) -> bool

           Takes a hash password and plaintext password and confirms
           if the password is a match. Returns true if it is valid or False
           otherwise

           :parameter
                :hash_password: A hash string
                :password: A plaintext string

            :usage:
                PasswordImplementer.is_password_valid(hash_password. password)
        """
        return check_password_hash(hash_password, password)
Beispiel #22
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for("user.account"))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.objects(email=form.email.data).first()
        if user and check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            next_page = request.args.get("next")
            return redirect(next_page) if next_page else redirect(
                url_for("manage.mhome"))
        else:
            flash(f"Login Unsuccessful. Please check email and password",
                  "danger")
    return render_template("login.html", form=form, display_breadcrumbs=True)
Beispiel #23
0
    def post(self):
        args = parser.parse_args()
        email = args['email']
        password = args['password']
        user = db.session.query(User).filter_by(email=email).one()
        if not user:
            abort(400, message="Something went wrong logging in")

        match = check_password_hash(user.password_hash, password)

        if not match:
            abort(400, message="Something went wrong logging in")

        flask_login.login_user(user)
        return {'login': user.get_id}
Beispiel #24
0
def login():
    payload = request.get_json()
    print(payload, '< --- this is playload')
    try:
        user = models.User.get(models.User.email== payload['email'])
        user_dict = model_to_dict(user)
        if(check_password_hash(user_dict['password'], payload['password'])):
            del user_dict['password']
            login_user(user)
            print(user, ' this is user')
            return jsonify(data=user_dict, status={"code": 200, "message": "Success"})
        else:
            return jsonify(data={}, status={"code": 401, "message": "Username or Password is incorrect"})
    except models.DoesNotExist:
        return jsonify(data={}, status={"code": 401, "message": "Username or Password is incorrect"})
Beispiel #25
0
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("Your emails and password do not match!", "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("Successfully logged in!!", "success")
                return redirect(url_for('index'))
            else:
                flash("Your emails and password do not match!", "error")
    return render_template('login.html', form=form)
Beispiel #26
0
    def delete(self, h):
        klass = RedisObject.klass(h)

        if not klass:
            return {'error': 404}, 404
        try:
            o = klass.from_hash(h)
            if not check_password_hash(o.ip, get_ip()):
                return {'error': 401}, 401
        except Exception as e:
            print("delete exp", e)
            return {'error': 401}, 401

        deletion_procedures[klass](o)
        return {'status': 'success'}
Beispiel #27
0
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.username == form.username.data)
        except models.DoesNotExist:
            flash(('Sorry! Your username or ' 'password is incorrect.'))
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash('Welcome back!')
                return redirect(url_for('index'))
            else:
                flash(('Sorry! Your username or ' 'password is incorrect.'))
    return render_template('login.html', form=form)
Beispiel #28
0
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("Email doesn't match.", "error")

        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                return redirect(url_for('stream'))
            else:
                flash("Email or password isn't correct.", "error")
    return render_template('login.html', form=form)
Beispiel #29
0
def login():
	form = forms.AdminLoginForm()
	if form.validate_on_submit():
		try:
			admin = models.Admin.get(form.username.data == models.Admin.username)
			if(check_password_hash(admin.password, form.password.data)):
				login_user(admin)
				flash("Welcome back {}!".format(admin.username), "success")
				return redirect(url_for("admin_panel"))
			else:
				flash("Wrong username or password. Please try again.", "danger")	
		except models.DoesNotExist:
			flash("Wrong username or password. Please try again.", "danger")

	return render_template("login.html", form = form)
Beispiel #30
0
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.select().where(
                models.User.email**form.email.data).get()
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("You're now logged in!")
                return redirect(url_for('index'))
            else:
                flash("Email or password is invalid")
        except models.DoesNotExist:
            flash("Email or password is invalid")
    return render_template('login.html', form=form)
Beispiel #31
0
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("Your email or password doesn't match!", "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("You've been logged in!", "success")
                return redirect(url_for('index'))
            else:
                flash("Your email or password doesn't match!", "error")
    return render_template('login.html', form=form)
Beispiel #32
0
def auth_login():
    if request.method == "GET":
        return render_template("auth/loginform.html", form=LoginForm())

    form = LoginForm(request.form)

    user = User.query.filter_by(username=form.username.data).first()

    if user and check_password_hash(user.password, form.password.data):
        login_user(user)
        return redirect(url_for("index"))

    return render_template("auth/loginform.html",
                           form=form,
                           error="No such username or password")
Beispiel #33
0
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except DoesNotExist:
            flash("Email or password does not match.", "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("Welcome, {}!".format(user.username), "success")
                return redirect(url_for('index'))
            else:
                flash("Email or password does not match.", "error")
    return render_template('login.html', form=form)
Beispiel #34
0
def login():
    """For GET requests, display the login form. For POSTS, login the current user
    by processing the form."""

    form = LoginForm()
    if form.validate_on_submit():
        user = FlaskUser.query.filter_by(username=form.username.data).first()
        if user:
            if check_password_hash(user.password, form.password.data):
                user.authenticated = True
                db.session.add(user)
                db.session.commit()
                login_user(user, remember=True)
                return redirect(url_for("index.home"))
    return render_template("index/login.html", form=form)
Beispiel #35
0
def login():
    """login to the app"""
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.username == form.username.data)
        except models.DoesNotExist:
            flash('Your username or password does not match!', 'error')
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash('You are logged in', 'success')
                return redirect(url_for('clients'))
            else:
                flash("Your username or password doesn't match!", 'error')
    return render_template('login.html', form=form)
Beispiel #36
0
def login():
	form = forms.LoginForm()
	if form.validate_on_submit():
		try:
			user = models.User.get(models.User.email == form.email.data)
		except models.DoesNotExist:
			flash("Your email or password does not match", "error")
		else:
			if check_password_hash(user.password, form.password.data):
				login_user(user)
				"""Creating a session on user's browser"""
				flash("You have been logged in", "success")
				return redirect(url_for('index'))
			else:
				flash("Your email or password does not match", "error")
	return render_template('login.html', form = form)
Beispiel #37
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("you email or password doesn't match", "error")

        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("logged in as")
                return redirect(url_for('apply'))
            else:
                flash("you email or password doesn't match", "error")
    return render_template('login.html', form=form)
Beispiel #38
0
def login():
    payload =request.get_json()
    print(payload, "payload in login")
    try:
        user = models.User.get(models.User.username == payload["username"])
        print(user, "this is the found user!!!!!")
        user_dict = model_to_dict(user)    
        if (check_password_hash(user_dict["password"], payload["password"])):
            del user_dict["password"]
            login_user(user)
            print(user, "this is user in login route")
            return jsonify(data=user_dict, status={"code":200, "message": "Success"})
        else:
            return jsonify(data={}, status={"code": 401, "message": "Username or Password is incorrect"})
    except models.DoesNotExist:
        return jsonify(data={}, status={"code": 401, "message": "Username or Password is incorrect"})
def login():
    """View to have user login and validate credentials."""
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.username == form.username.data)
        except models.DoesNotExist:
            flash("You're username or password does not match.")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("You are logged in!")
                return redirect(url_for('index'))
            else:
                flash("You're email or password does not match.")
    return render_template('login.html', form=form)
Beispiel #40
0
def are_credentials_valid(username, password):
    """Returns whether a given username is stored in the
     database and, if it is, if the passwords match.
    """
    sqlite_connection = database_connection()
    cursor = sqlite_connection.cursor()

    cursor.execute('SELECT password FROM users WHERE username=?', (username, ))

    match = cursor.fetchone()

    if not match:
        return False

    stored_hash = match[0]
    return check_password_hash(stored_hash, password)
Beispiel #41
0
def edit_user(id):
    payload = request.get_json()
    try:
        user = models.User.get(models.User.id==id)
        user_dict = model_to_dict(user)
        if(check_password_hash(user_dict['password'],payload['password'])):
            query= models.User.update(email=payload["email"]).where(models.User.id == id)
            query.execute()
            
            updated_user = models.User.get_by_id(id)

            return jsonify(data=model_to_dict(updated_user), status={"code":200,"message":"Success"})
        else:
            return jsonify(data={}, status={"code": 401, "message": "Wrong Input"})
    except models.DoesNotExist:
        return jsonify(data={}, status={"code": 401, "message": "Wrong Input"})
Beispiel #42
0
def lock(previous_page):
    form = forms.Password()
    password_model = models.PasswordForAdd.select().get()
    if password_model.locked == True:
        if form.validate_on_submit():
            if check_password_hash(password_model.password,
                                   form.password.data):
                password_model.locked = False
                password_model.save()
                flash("Add features unlocked!", "success")
            else:
                flash("Incorrect Password", "fail")
            return redirect(url_for(previous_page))
        return render_template("unlock.html", form=form)
    else:
        return render_template("lock.html")
Beispiel #43
0
def loginPage():
    form = LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("Not a match")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("Logged In!")
                return redirect(url_for('swipePage'))
            else:
                flash("Not a match!")

    return render_template('login.html', form=form)
Beispiel #44
0
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("Your email or password does not match", "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                """Creating a session on user's browser"""
                flash("You have been logged in", "success")
                return redirect(url_for("index"))
            else:
                flash("Your email or password does not match", "error")
    return render_template("login.html", form=form)
Beispiel #45
0
def login():
    """Login user."""
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.select().get()
        except models.DoesNotExist:
            flash("Your credentials are invalid.", "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("You've been logged in!", "success")
                return redirect(url_for('index'))
            else:
                flash("Your credentials are invalid", "error")
    return render_template('login.html', form=form)
Beispiel #46
0
def change_password():
    form = forms.new_password()
    if form.validate_on_submit():
        user = models.User.get(models.User.email == current_user.email)
        if check_password_hash(user.password, form.old_password.data):
            q = models.User.update(
                password=generate_password_hash(form.password.data)).where(
                    models.User.email == current_user.email)
            q.execute()

            return redirect(url_for('index'))
        else:
            flash("Wrong Password!")
    return render_template('change-password.html',
                           user=current_user,
                           form=form)
Beispiel #47
0
def login():
    error = None
    form = LoginForm(request.form)
    if request.method == "POST":
        if form.validate_on_submit():
            user = User.query.filter_by(email=request.form['email']).first()
            if user is not None and bcrypt.check_password_hash(user.password, request.form['password']):
                session['logged_in'] = True
                session['user_id'] = user.id
                session['user_email'] = user.email
                flash(u'ברוכים הבאים, תהנו!')
                return redirect(url_for('notifier.feeds_editor'))
            else:
                error = 'כתובת דוא"ל או סיסמה שגויים'
        else:
            error = "שני השדות דרושים להתחברות."
    return render_template("login.html", form=form, error=error)
Beispiel #48
0
def login():
    error = None
    form = LoginForm(request.form)
    if request.method == "POST":
        if form.validate_on_submit():
            user = User.query.filter_by(email=request.form['email']).first()
            if user is not None and bcrypt.check_password_hash(user.password, request.form['password']):
                login_user(user)
            else:
                error = u'כתובת דוא"ל או סיסמה שגויים'
        else:
            error = u"שני השדות דרושים להתחברות."

    if 'logged_in' in session:  #if already logged in:
        flash(u'ברוכים השבים, את/ה כבר מחוברת!')
        return redirect(url_for('notifier.feeds_editor'))
    else:
        return render_template("login.html", form=form, error=error)
Beispiel #49
0
def login():
	#if g.user is not None and g.user.is_authenticated:
		#return redirect(url_for('index'))
	error = None
	form = LoginForm()	
	if form.validate_on_submit():
		user = User.query.filter_by(username=form.username.data).first()
		if user is None:
			error = 'user does not exist' 
		elif not check_password_hash(user.pwhash, form.password.data):
			error = 'Password is false, please try again'			
		else:
			login_user(user)
			flash('Logged in successfully')
			return redirect(url_for('index'))	
		
	return render_template('login.html', title='Sign In', form=form,
							error=error)
    def login(cls, form):
        """
        Login user by giving "LoginForm" form and validate if username+password pair is valid
        """
        if not form.validate_on_submit():
            flash.danger(u'Form is not valid.')
            return False

        user = UserFinder.by_username(form.username.data)
        if not user:
            flash.danger(u'User {} does not exists.'.format(form.username.data))
            return False

        if not check_password_hash(user.password, form.password.data):
            flash.warning(u'Invalid Credentials. Please try again.')
            return False

        LoginUserService(user).call()
        return user
Beispiel #51
0
def login():
    """
    Attempt to login the user if this is a POST or show them the login page
    :return: View
    """
    if request.method == 'POST':
        cur = g.db.execute('select id, name, password from users where name = ?', [request.form['name']])
        result = cur.fetchone()
        if result is not None:
            if check_password_hash(result[2], request.form['password']):
                session['logged_in'] = True
                session['user_name'] = result[1]
                return redirect(url_for('home.home'))
            else:
                error = "Password does not match our records"
            return render_template('login.html', error=error)
        else:
            error = "Name not found"
            return render_template('login.html', error=error)
    else:
        return render_template('login.html')
Beispiel #52
0
def login(value):
    login_name = value["login"]
    password = value["password"]
    con, c = dbconnect.connect()
    if validate_email(login_name):
        query = " SELECT * FROM user WHERE user_email = %s "
    else:
        query = " SELECT * FROM user WHERE user_name = %s "

    c.execute(query, (login_name,))
    row = c.fetchall()
    dbconnect.close(con, c)

    if len(row) != 0:
        row = row[0]
        pass_hash = row[3]
        if check_password_hash(pass_hash, password):
            valid_user = User(row[0], row[1], row[2], row[4], row[5])
            return (valid_user, jsonify({"Status": 1, "Message": "Logged in successfully."}))

    return (None, jsonify({"Status": 0, "Message": "Invalid username or password."}))
Beispiel #53
0
def login_user(data):
    log("User successfully logedin", "HIGH", "PASS")
    val_alpha_num(data.get('username'))
    username = data.get('username')
    try:
        if (users.query.filter(users.userName == username).one()):
            user = users.query.filter(users.userName == username).one()
            if (user.activated == "True"):
                if (user.access == "True"):
                    if check_password_hash(user.password, data.get('password')):
                        priv_user = privileges.query.filter(privileges.privilegeID == str(user.privilegeID)).first()
                        payload = {
                            # userid
                            'UserId': user.userID,
                            #issued at
                            'iat': datetime.utcnow(),
                            #privileges
                            'privilege': priv_user.privilege,
                            #expiry
                            'exp': datetime.utcnow() + timedelta(minutes=120)
                            #claims for access api calls
                            #'claims': 'kb/items/update,project/items,non/existing/bla,'
                        }
                        token_raw = jwt.encode(payload, settings.JWT_SECRET, algorithm='HS256')
                        if sys.version_info.major == 3:
                        	unicode = str
                        token = unicode(token_raw,'utf-8')
                        return {'Authorization token': token, 'username': username}
                    else:
                        log("User triggered error login failed", "HIGH", "FAIL")
                        return {'Authorization token': ''}
                else:
                    log("User triggered error login failed", "HIGH", "FAIL")
                    return {'Authorization token': ''}
            else:
                log("User triggered error login failed", "HIGH", "FAIL")
                return {'Authorization token': ''}
    except NoResultFound:
        log("User triggered error login failed", "HIGH", "FAIL")
        return {'Authorization token': ''}
Beispiel #54
0
def login():
    form = LoginForm()
    failure_message = "Incorrect username or password"
    success_message = "You have successfully logged in!"

    if request.method == 'POST' and form.validate():
        try:
            user = User.get(User.email == form.email.data)
        except DoesNotExist:
            flash(failure_message, "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash(success_message, 'success')
                return redirect(url_for('index'))
            else:
                flash(failure_message, "error")

    return render_template(
        'login.html',
        form=form
    )
Beispiel #55
0
    def flags_post(self, h):
        klass = RedisObject.klass(h)

        if not klass:
            return {'error': 404}, 404
        try:
            o = klass.from_hash(h)
            if not check_password_hash(o.ip, get_ip()):
                return {'error': 401}, 401
        except:
            return {'error': 401}, 401

        # At this point, we're authenticated and o is the object.
        for flag, value in request.form.items():
            v = True if value == 'true' else False

            try:
                setattr(o.flags, flag, v)
            except AttributeError:
                return {'error': 415}, 415

        o.save()

        return {"flags": o.flags.as_dict()}
 def test_unicode_hash(self):
     password = u'東京'
     h = generate_password_hash(password).decode('utf-8')
     self.assertTrue(check_password_hash(h, password))
Beispiel #57
0
 def is_correct_password(self, plaintext):
     return check_password_hash(self._password, plaintext)
Beispiel #58
0
def authenticate(username, password):
    user = get_account(str(username))
    return user and check_password_hash(user.password, password)
 def authenticate(self, plaintext):
     return check_password_hash(self._password, plaintext)
Beispiel #60
0
 def check_hash(password, hash):
     return check_password_hash(hash, password)