示例#1
0
 def test_check_password(self):
     # Ensure given password is correct after unhashing.
     user = User.query.filter_by(email='*****@*****.**').first()
     self.assertTrue(bcrypt.check_password_hash(user.password,
                                                'admin_user'))
     self.assertFalse(bcrypt.check_password_hash(user.password,
                                                 'foobar'))
示例#2
0
 def test_check_password(self):
     # Ensure given password is correct after unhashing.
     user = User.query.filter_by(email='*****@*****.**').first()
     self.assertTrue(
         bcrypt.check_password_hash(
             user.password,
             'admin_user'))
     self.assertFalse(bcrypt.check_password_hash(user.password, 'foobar'))
示例#3
0
    def test_password(self):
        '''
        Validate password.

        :return:
        '''
        user = User.query.filter_by(username='******').first()
        self.assertTrue(bcrypt.check_password_hash(user.password, 'testuser'))
        self.assertFalse(bcrypt.check_password_hash(user.password,
                                                    'incorrect'))
def verify_email(token):
    ''' creates a email_token_hash and sends email with token to user (assumes login=email), idempotent (could be use for resend)'''
    user_id = User.decode_email_token(token)
    user = User.get(user_id)
    if not user or not user.email_token_hash:
        raise NotFoundException(
            message='Invalid verification. Please try again.')
    bcrypt.check_password_hash(user.email_token_hash, token)

    with session_scope(db.session):
        user.email_validation_date = datetime.utcnow()
    return {
        'status': 'success',
        'message': 'Successful email verification.',
    }
示例#5
0
def login_user():
    response = {'status': 'fail', 'message': 'Invalid payload'}
    post_data = request.get_json()

    # empty request
    if not post_data:
        response['message'] = 'Empty payload'
        return jsonify(response), 400

    email = post_data.get('email')
    password = post_data.get('password')

    try:
        # get user from db
        user = User.query.filter_by(email=email).first()
        if user and bcrypt.check_password_hash(
                user.password, password):  # use bcrypt to verify password
            token = user.encode_jwt(user.id)  # if authorized, create JWT
            if token:  # if valid, return it
                response['status'] = 'success'
                response['message'] = 'Logged In'
                response['token'] = token.decode()
                return jsonify(response), 200
        else:
            response['message'] = 'Username or password incorrect'
            return jsonify(response), 404
    except Exception:
        response['message'] = 'Something went wrong'
        return jsonify(response), 500
示例#6
0
def login_user():
    """Login a user."""
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'Invalid payload.'}
    if not post_data:
        return jsonify(response_object), 400
    email = post_data.get('email')
    password = post_data.get('password')
    try:
        # Fetch user
        user = User.query.filter_by(email=email).first()
        if user and bcrypt.check_password_hash(user.password, password):
            auth_token = user.encode_auth_token(user.id)
            if auth_token:
                response_object = {
                    'status': 'success',
                    'message': 'Successfully logged in.',
                    'auth_token': auth_token.decode()
                }
                return jsonify(response_object), 200
        else:
            response_object['message'] = 'User does not exist.'
            return jsonify(response_object), 404
    # Handle errors
    except Exception as e:
        response_object['message'] = 'Try again.'
        return jsonify(response_object), 500
示例#7
0
def register():
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        user = User(
            login=form.login.data,
            email=form.email.data,
            password=form.password.data
        )
        print(user)
        db.session.add(user)
        db.session.commit()

        login_user(user)
        flash('You registered and are now logged in. Welcome!', 'success')
        return redirect('/dashboard')
    else:
        print("shit")
    form2 = LoginForm(request.form)
    print("login")
    if form2.validate_on_submit():
        print("good")
        user = User.query.filter_by(login=form2.login.data).first()
        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            login_user(user)
            flash('Welcome.', 'success')
            return redirect('/dashboard')
        else:
            flash('Invalid email and/or password.', 'danger')
            return render_template('index.html', form2=form2, form=form)

    return render_template('index.html', form=form, form2=form2)
def authenticate(username, password):
    user = User.query.filter(User.username == username).first()
    if bcrypt.check_password_hash(user.password, password):
        token = jwt.encode({
            'id': user.id
        }, 'secret', algorithm='HS256').decode('utf-8')
        return token
示例#9
0
def login():
    """Login."""
    error = None
    form = LoginForm(request.form)

    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter_by(name=form.name.data).first()

            if user is not None and bcrypt.check_password_hash(
                    user.password, form.password.data):
                session['logged_in'] = True
                session['user_id'] = user.id
                session['role'] = user.role
                session['name'] = user.name
                flash("Welcome, {0}".format(user.name))
                return redirect(url_for('tasks.tasks'))
            else:
                error = 'Invalid credentials.  Please try again.'
        else:
            error = 'Both fields are required.'

    return render_template(
        'login.html',
        form=form,
        error=error
    )
示例#10
0
def login_user():
    # get post data
    post_data = request.get_json()
    response_object = {
        'status': 'fail',
        'message': 'Invalid payload.'
    }
    if not post_data:
        return jsonify(response_object), 400
    username = post_data.get('username')
    password = post_data.get('password')
    try:
        # fetch the user data
        user = User.query.filter_by(username=username).first()
        if user and bcrypt.check_password_hash(user.password, password):
            response_object['status'] = 'success'
            response_object['message'] = 'Successfully logged in.'
            user.logedin = True
            db.session.commit()
            return jsonify(response_object), 200
        else:
            response_object['message'] = 'User does not exist.'
            return jsonify(response_object), 404
    except Exception as e:
        response_object['message'] = 'Try again.'
        return jsonify(response_object), 500
示例#11
0
def login_user():
    #get post data
    post_data = request.get_json()
    # pdb.set_trace()
    if not post_data:
        response_object = {'status': 'error', 'message': 'Invalid payload.'}
        return make_response(jsonify(response_object)), 400
    email = post_data.get('email')
    password = post_data.get('password')

    try:
        #fetch data from db
        user = User.query.filter_by(email=email).first()
        if user and bcrypt.check_password_hash(user.password, password):
            user_token = user.encode_auth_token(user.id)
            if user_token:
                response_object = {
                    'status': 'success',
                    'message': 'Login success!',
                    'auth_token': user_token.decode()
                }
                return make_response(jsonify(response_object)), 200
        else:
            response_object = {
                'status': 'error',
                'message': 'User does not exsit.'
            }

            return make_response(jsonify(response_object)), 404
    except Exception as e:
        print(e)
        response_object = {'status': 'error', 'message': 'Try again'}
        return make_response(jsonify(response_object)), 500
示例#12
0
 def authenticate(cls, username, password):
     found_user = cls.query.filter_by(username=username).first()
     if found_user:
         is_authenticated = bcrypt.check_password_hash(found_user.password, password)
         if is_authenticated:
             return found_user
     return False
示例#13
0
def reset(email):
    error = None
    if request.method == 'POST':
        account = Account.query.filter_by(hash_email=email).first()

        if account is not None:
            password = request.form['password']
            confirm_pass = request.form['confirm-pass']
            if password != confirm_pass:
                error = "* Passwords do not match"
            elif bcrypt.check_password_hash(account.password, password):
                error = "* Password can not be the same as the last password"
            elif len(password) < 8:
                error = "* New password is too short"
            else:
                # update database and send back to home
                account.password = bcrypt.generate_password_hash(password, 10)
                db.session.commit()
                return redirect(
                    url_for(
                        'success',
                        message=
                        "You have successfully changed your password. Click login to"
                        " return to login page."))
    return render_template('reset.html', error=error)
示例#14
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['name']).first()
            if user is None:
                error = 'Invalid username or password.'
                return render_template(
                    "login.html",
                    form=form,
                    error=error
                )
            elif bcrypt.check_password_hash(
                user.password, request.form['password']
            ):
                session['logged_in'] = True
                session['user_id'] = user.id
                session['role'] = user.role
                session['name'] = user.name
                flash('Welcome!')
                return redirect(url_for('tasks.tasks'))
        else:
            return render_template(
                "login.html",
                form=form,
                error=error
            )
    if request.method == 'GET':
        return render_template('login.html', form=form)
示例#15
0
文件: views.py 项目: RMDK/flask-taskr
def login():
    error = None
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            u = User.query.filter_by(
                name=request.form['name']).first()
            if u is None:
                error = "Cannot find that username."
                return render_template('login.html', form=form, error=error)
            elif bcrypt.check_password_hash(
                    u.password, request.form['password']):
                session['logged_in'] = True
                session['user_id'] = u.id
                session['role'] = u.role
                session['name'] = u.name
                flash('You are logged in. Go Crazy.')
                return redirect(url_for('tasks.tasks'))
            else:
                error = 'Invalid password / username combination.'
                return render_template('login.html', form=form, error=error)
        else:
            return render_template('login.html', form=form, error=error)
    if request.method == 'GET':
        return render_template('login.html', form=form)
示例#16
0
文件: users.py 项目: sangtb92/ciand
def user_login():
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'Invalid payload.'}
    email = post_data.get('email')
    if not post_data:
        return make_response(jsonify(response_object)), 400
    user = User.query.filter_by(email=email).first()
    if not user:
        return make_response(jsonify(response_object)), 404
    try:
        password = post_data.get('password')
        if user and bcrypt.check_password_hash(user.password, password):
            auth_token = user.encode_auth_token(user_id=user.id)
            if auth_token:
                response_object = {
                    'status': 'success',
                    'message': 'Successfully logged in.',
                    # covert bytes to string
                    'auth_token': auth_token.decode("utf-8")
                }
                return make_response(jsonify(response_object)), 200
        else:
            response_object = {
                'status': 'fail',
                'message': 'User does not exist.'
            }
            return make_response(jsonify(response_object)), 404
    except Exception as e:
        print(e)
        return make_response(jsonify(response_object)), 500
示例#17
0
def login():
    form = LoginForm()
    if request.method == 'POST':
        if form.validate():
            found_user = User.query.filter_by(
                username=form.username.data).first()
            if found_user:
                is_authenticated = bcrypt.check_password_hash(
                    found_user.password, form.password.data)
                if is_authenticated:
                    login_user(found_user)
                    flash({
                        'text': "Hello, {}!".format(found_user.username),
                        'status': 'success'
                    })
                    return redirect(url_for('users.show', id=current_user.id))
                else:
                    flash({
                        'text': "Wrong password, please try again.",
                        'status': 'danger'
                    })
            else:
                flash({
                    'text': "Invalid username. Please try again",
                    'status': 'danger'
                })
            return render_template('users/login.html', form=form)
    return render_template('users/login.html', form=form)
示例#18
0
文件: auth.py 项目: szmski/dfrt
def login_user():
    # get post data
    post_data = request.get_json()
    response_object = {
        "status": "fail",
        "message": "Invalid payload"
    }

    if not post_data:
        return jsonify(response_object), 400

    email = post_data.get("email")
    password = post_data.get("password")

    try:
        # fetch the user data
        user = User.query.filterBy(email=email)
        if user and bcrypt.check_password_hash(user.password, password):
            auth_token = user.encode_auth_token(user.id)

            if auth_token:
                response_object['status'] = "success"
                response_object['message'] = "Succesfully logged in."
                response_object['auth_token'] = auth_token.decode()

                return jsonify(response_object), 200
            else:
                 response_object['message'] = "User does not exist"

                 return jsonify(response_object), 404
        else:
            response_object['message'] = 'Try again.'

            return jsonify(response_object), 500
示例#19
0
    def post(self):
        """Login user"""
        post_data = request.get_json()
        email = post_data.get("email")
        password = post_data.get("password")

        res = {"status": False, "message": "Invalid payload"}

        if email is None or password is None:
            return res, 400

        valid_email = EMAIL_REGEX.match(email)

        if valid_email is None:
            res["message"] = "Please provide a valid email address"
            return res, 400

        current_user = get_user_by_email(email)
        if current_user is None or not bcrypt.check_password_hash(
            current_user.password, password
        ):
            res["message"] = "User does not exist."
            return res, 404

        access_token = current_user.encode_token(current_user.id, "access")
        refresh_token = current_user.encode_token(current_user.id, "refresh")

        res = {
            "access_token": access_token.decode(),
            "refresh_token": refresh_token.decode(),
        }

        return res, 200
示例#20
0
def post_signin():
    """ POST /auth/get_jwt
    Signs in the user and fetches the user's token.
    requires:
        email,
        password

    :return: A Flask Response
    """

    data = request.get_json()
    if not data:
        return error_response(), 400
    email = data.get('email')
    password = data.get('password')
    try:
        user = User.query.filter_by(email=email).first()
        if user and bcrypt.check_password_hash(user.password, password):
            token = user.encode_jwt(user.id)
            if token:
                return success_response(
                    '{email} signed in.'.format(email=email),
                    data={'token': token.decode()}), 200
        return error_response('User does not exist.'), 404
    except Exception as e:
        print(e)
        return error_response('Try again.'), 500
示例#21
0
def login_user():
    # get post data
    post_data = request.get_json()
    response = {
        'status': 'fail',
        'message': 'Invalid payload.'
    }
    if not post_data:
        return jsonify(response), 400
    email = post_data.get('email')
    password = post_data.get('password')
    try:
        # fetch the user data
        user = User.query.filter_by(email=email).first()
        if user and bcrypt.check_password_hash(user.password, password):
            auth_token = user.encode_auth_token(user.id)
            if auth_token:
                response['status'] = 'success'
                response['message'] = 'Successfully logged in.'
                response['auth_token'] = auth_token.decode()
                return jsonify(response), 200
        else:
            response['message'] = 'User does not exist.'
            return jsonify(response), 401
    except Exception as e:
        print(e)
        response['message'] = 'Try again.'
        return jsonify(response), 500
示例#22
0
 def check_password(self, password):
     """
     Check User password
     """
     return bcrypt.check_password_hash(
         self.password, password
     )
示例#23
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        deleted_list = [
            _.email for _ in User.query.filter_by(deleted=True).all()
        ]
        panned_list = deleted_list + [
            _.email for _ in User.query.filter_by(activate=False,
                                                  confirmed=True).all()
        ]
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               request.form['password']):
            if form.email.data in panned_list:
                flash(u'لقد تم حظرك من المنظومة ,ارجاء الإتصال بمشرف التطبيقه',
                      'warning')
                return render_template('user/login.html', form=form)
            else:
                login_user(user)
                user.last_login = datetime.datetime.now()
                db.session.commit()
                flash(u'مرحباً', 'success')
                return redirect(url_for('main.home'))
        else:
            flash(u'البريد الإلكتروني  و  أو كلمة المرور  غير صالح', 'danger')
            return render_template('user/login.html', form=form)
    return render_template('user/login.html', form=form)
示例#24
0
	def authenticate(cls, username, password):
		user = cls.query.filter_by(username=username).first()
		if user:
			authenticated_user=bcrypt.check_password_hash(user.password, password)
			if authenticated_user:
				return user
		return False
def login():
    """This method represents route to the 'login.html' and serves as login feature.
    This method validates user's credentials and if user exists and password is correct, then
    the user is logged into the application.

    Returns:
        render_template: Returns rendered 'login.html' template.
    """

    form = LoginForm(request.form)

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()

        if user and bcrypt.check_password_hash(user.password,
                                               request.form['password']):
            login_user(user)
            flash('Welcome.', 'success')
            return redirect(url_for('main.home'))

        else:
            flash(
                'Entered email and password did not match our records. \
                Please check your credentials and try again.', 'danger')
            return render_template('user/login.html', form=form)

    return render_template('user/login.html', form=form)
示例#26
0
文件: views.py 项目: sznote/flask
def login():
    error = None
    form = LoginFrom(request.form)

    if request.method == 'POST':
        #print request.form['username']
        #print request.form['password']

        if form.validate_on_submit():

            user = User.query.filter_by(name=form.username.data).first()
            if user is not None  and bcrypt.check_password_hash(user.password, form.password.data): 
            #print "sss"
            # if (request.form['username'] != 'admin') \
            #         or request.form['password'] != 'admin':
            #     error = 'Invalid Credentials. Please try again.'
            # else:
                #session['logged_in'] = True
                login_user(user)
                print current_user.id
                print current_user.name
                print current_user.get_id()
                #print current_user
                flash('You were logged in.')
                return redirect(url_for('homes.home'))
            else:
                error = 'Invalid Credentials. Please try again.'
    return render_template('login.html', form=form, error=error)
示例#27
0
def login():
    form = LoginUser()
    if request.method == "POST" and form.validate():
        found_user = User.query.filter_by(email=form.email.data).first()
        if found_user:
            authenticated_user = bcrypt.check_password_hash(
                found_user.password, request.form['password'])
            if authenticated_user:
                login_user(found_user)
                return redirect(url_for("locations.index", id=found_user.id))
            else:
                error_found = "Incorrect Password"
                return render_template("users/login.html",
                                       form=form,
                                       error=error_found)

        else:
            error_found = "No Such User"
            return render_template("users/login.html",
                                   form=form,
                                   error=error_found)

    if request.method == "POST":
        error_found = next(iter(form.errors.values()))[0]
        return render_template("users/login.html",
                               form=form,
                               error=error_found)

    if request.method == "GET":
        return render_template("users/login.html", form=form, error="")
示例#28
0
def set_standalone_user(user_id: int):
    ''' changes user password when logged in'''
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    username = post_data.get('username')
    pw_old = post_data.get('old_password')
    pw_new = post_data.get('new_password')
    if not username or not pw_old or not pw_new:
        raise InvalidPayload()

    # fetch the user data
    user = User.get(user_id)
    if not user.fb_id:
        raise NotFoundException(
            message='Must be a facebook user login. Please try again.')

    # fetch the user data
    user = User.get(user_id)
    if not bcrypt.check_password_hash(user.password, pw_old):
        raise NotFoundException(message='Invalid password. Please try again.')

    if not User.first(User.username == username):
        with session_scope(db.session):
            user.username = username
            user.password = bcrypt.generate_password_hash(
                pw_new, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()
        return {
            'status': 'success',
            'message': 'Successfully changed password.',
        }
    else:
        raise BusinessException(
            message=
            'Sorry. That username already exists, choose another username')
示例#29
0
def password_reset():
    ''' reset user password (assumes login=email)'''
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    token = post_data.get('token')
    pw_new = post_data.get('password')
    if not token or not pw_new:
        raise InvalidPayload()

    # fetch the user data

    user_id = User.decode_password_token(token)
    user = User.get(user_id)
    if not user or not user.token_hash or not bcrypt.check_password_hash(
            user.token_hash, token):
        raise NotFoundException(message='Invalid reset. Please try again.')

    with session_scope(db.session):
        user.password = bcrypt.generate_password_hash(
            pw_new, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()
        user.token_hash = None
    return {
        'status': 'success',
        'message': 'Successfully reset password.',
    }
示例#30
0
def login():
    if current_user.is_authenticated:
        initUser()
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()

        if user and bcrypt.check_password_hash(user.password,
                                               form.password.data):
            if str(user.parent_org) != 'None':
                emp = empList.query.filter_by(empname=user.username).first()
                if not emp:
                    flash(
                        "Login Unsuccessful, Your Organization request has not been approved yet.",
                        "warning")
                    return render_template('login.html',
                                           title='Login',
                                           form=form)
            login_user(user, remember=form.remember.data)
            next_page = request.args.get(
                'next'
            )  #args is a dictionary we use get method so that if the next prameter dost not exits it gives none so dont use square brackets with the key
            initUser()
            flash("Login Successful", "success")
            return redirect(next_page) if next_page else redirect(
                url_for('home')
            )  # this is done so that if login page is directed from a restricted page then after login it redirects to that page instead of home page
        else:
            flash("Login Unsuccessful, Please check your email and password",
                  "danger")
    return render_template('login.html', title='Login', form=form)
示例#31
0
def abort_if_user_doesnt_exist(user, password):
    """
        Abort api demand if user name does not exist or if user name and
        password do not match an existing account.
    """
    if user is None or not bcrypt.check_password_hash(user.password, password):
        abort(401, message="error: User does not exist or user name and password do not match.")
示例#32
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['name']).first()

            if user is None:
                error = 'Invalid username or password.'

                return render_template('login.html', form=form, error=error)

            elif bcrypt.check_password_hash(user.password,
                                            request.form['password']):
                session['logged_in'] = True
                session['user_id'] = user.id
                session['role'] = user.role
                session['name'] = user.name

                flash('You are logged in. Go Crazy.')
                return redirect(url_for('tasks.tasks'))

        else:
            return render_template('login.html', form=form, error=error)

    if request.method == 'GET':
        return render_template('login.html', form=form)
示例#33
0
def login():
    form = LoginForm()
    if request.method == "POST":
        if not form.errors:
            if form.validate():
                found_user = User.query.filter_by(
                    username=form.username.data).first()
                if found_user:
                    authenticated_user = bcrypt.check_password_hash(
                        found_user.password, form.password.data)
                    if authenticated_user:
                        login_user(found_user)
                        flash({
                            'text': "Hello, {}!".format(found_user.username),
                            'status': 'success'
                        })
                        return redirect(url_for('root'))
            flash({'text': "Try again", 'status': 'danger'})
            return render_template('users/login.html', form=form)
        flash({
            'text':
            str(list(form.errors.values())).replace('[', '').replace(']', ''),
            'status':
            'danger'
        })
        return render_template('users/login.html', form=form)
    return render_template('users/login.html', form=form)
示例#34
0
文件: auth.py 项目: hoou/pis_project
    def post(self):
        data = request.get_json()

        if not data:
            raise InvalidPayload

        email = data.get('email')
        password = data.get('password')

        if email is None or password is None:
            raise InvalidPayload

        user = users.get_by_email(email)

        if user is None:
            raise AuthenticationFailed

        if not user.active:
            raise UserNotActive

        is_valid_password = bcrypt.check_password_hash(user.password, password)

        if not is_valid_password:
            raise AuthenticationFailed

        access_token = create_access_token(user.id)
        refresh_token = create_refresh_token(user.id)

        return {'access_token': access_token, 'refresh_token': refresh_token}
示例#35
0
def change():
    _form_title = 'User'
    _template = 'default/add-form.html'
    _func_name = 'user.change'
    _form_seq = [
        ['old_password'],
        ['new_password','retry_password']
    ]
    user = User.query.filter_by(id=current_user.id).first_or_404()
    form = ChangePasswordForm()

    if request.method == 'POST' and form.validate():
        if not bcrypt.check_password_hash(user.password, form.old_password.data):
            flash('Wrong Old Password.')
            return redirect(url_for(_func_name ))
        if not (form.new_password.data == form.retry_password.data):
            flash('Password did not match')
            return redirect(url_for(_func_name ))
        else:
            user.set_password(form.new_password.data)

            db.session.add(user)
            db.session.commit()
            flash('Password Successfully Change.')
            return redirect(url_for(_func_name ))
    return render_template(_template,
                           form=form,
                           form_title = _form_title,
                           form_seq = _form_seq)
示例#36
0
    def validate(self):
        # Standard Validation
        rv = Form.validate(self)
        if not rv:
            return False

        # user validation
        user = User.query.filter_by(email=self.email.data).first()
        if user is None:
            self.email.errors.append('Your login details are incorrect.')
            return False

        # account validation
        if user.token is not None:
            self.email.errors.append('Please confirm your account before '
                                     'loggin in.')
            resend_url = url_for('.resend_confirmation') + '?email=' +\
                self.email.data
            self.email.errors.append(
                'If you do not revieve your confirmation email you can resend '
                'it by clicking <a href="' + resend_url + '">here</a>')
            return False

        # password validation
        if not bcrypt.check_password_hash(
            user.password, self.password.data
        ):
            self.password.errors.append('Your login details are incorrect.')
            return False

        self.user = user
        return True
示例#37
0
def login_user():
    post_data = request.get_json()
    response_object = {"status": "fail", "message": "Invalid payload."}

    if not post_data:
        return jsonify(response_object), 400

    email = post_data.get("email")
    password = post_data.get("password")

    try:
        user = User.query.filter_by(email=email).first()
        if user and bcrypt.check_password_hash(user.password, password):
            auth_token = user.encode_auth_token(user.id)
            if auth_token:
                response_object["status"] = "success"
                response_object["message"] = "Successfully logged in."
                response_object["auth_token"] = auth_token.decode()
                return jsonify(response_object), 200
        else:
            response_object["message"] = "User does not exist."
            return jsonify(response_object), 404
    except Exception:
        response_object["message"] = "Try again."
        return jsonify(response_object), 500
示例#38
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(email=post_data.get('email')).first()
         if user:
             if bcrypt.check_password_hash(user.password,
                                           post_data.get('password')):
                 auth_token = user.encode_auth_token(user.id)
                 if auth_token:
                     responseObject = {
                         'status': 'success',
                         'message': 'Successfully logged in.',
                         'auth_token': auth_token.decode()
                     }
                     user.update_login_date()
                     return make_response(jsonify(responseObject)), 200
             else:
                 responseObject = {
                     'status': 'fail',
                     'message': 'Password is incorrect.'
                 }
                 return make_response(jsonify(responseObject)), 401
         else:
             responseObject = {
                 'status': 'fail',
                 'message': 'User does not exist.'
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         print(e)
         responseObject = {'status': 'fail', 'message': 'Try again'}
         return make_response(jsonify(responseObject)), 500
示例#39
0
def login():
    if current_user.is_authenticated():
        flash('You are already logged in.')
        return redirect(url_for('home.home'))
    login_error = None
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            email = form.email.data
            password = form.password.data
        else:
            email = request.args.get('email', type=str)
            password = request.args.get('password', type=str)

        user = User.query.filter_by(email=email).first()
        if user is None:
            login_error = 'Invalid username or password.'
        elif bcrypt.check_password_hash(user.password, password):
            login_user(user)
            flash('You were successfully logged in.')
            next_url = request.args.get('next')
            return redirect(next_url or url_for('home.home'))
        else:
            login_error = 'Invalid username or password.'

    return render_template('login.html', form=form, login_error=login_error)
示例#40
0
def verify_password(username, password):
    user = User.query.filter_by(name=username).first()
    if user is not None and bcrypt.check_password_hash(
            user.password, password):
        g.user = user
        return True
    else:
        return False
示例#41
0
def login():
    user = User.query.filter_by(email=request.json['email']).first()
    if not user or not bcrypt.check_password_hash(user.password,request.json['password']):
        response = jsonify({"error":"1","data":{},"message":'failed'})
        response.status_code = 401
    else:
        token = create_token(user) 
        response = jsonify(token=token,information={"error":"null","data":{'token':token,'expires': "today",'user':{'id':user.userid,'email': user.email,'name':user.display_name},"message":"Success"}})
    return response
示例#42
0
def login():
    user = User.query.filter_by(email=request.json['email']).first()
    if not user or not bcrypt.check_password_hash(user.password,request.json['password']):
        response = jsonify({"error":"1","data":{},"message":'failed'})
        response.status_code = 401
    else:
        token = create_token(user)
        payload = jwt.decode(token,app.config['TOKEN_SECRET'], algorithm=['HS256']) 
        response = jsonify(token=token,information={"error":"null","data":{'token':token,'expires': timeinfo(payload['exp']),'user':{'id':user.userid,'email': user.email,'name':user.display_name},"message":"Success"}})
    return response
示例#43
0
def two_factor_login():
    form = TwoFactorLoginForm(request.form)

    if form.validate_on_submit():

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

        if user and bcrypt.check_password_hash(user.password, form.password.data):
            if bcrypt.check_password_hash(user.otp, form.otp.data):
                login_user(user)
                flash('You are logged in. Welcome!', 'success')
                user.otp = None
                db.session.commit()
                return redirect(url_for('user.members'))
            else:
                flash('Invalid one time password.', 'danger')
        else:
            flash('Invalid email and/or password.', 'danger')

    return render_template('user/two_factor_login.html', form=form)
示例#44
0
文件: users.py 项目: lingxz/todoapp
def login():
    json_data = request.json
    user = User.query.filter_by(email=json_data['email']).first()
    if user and bcrypt.check_password_hash(
            user.password, json_data['password']):
        session['logged_in'] = True
        session['user_id'] = user.id
        token = auth.create_token(user)
        return jsonify({'result': True, "token": token, "username": user.username})
    else:
        return jsonify({'result': False, "token": -1})
示例#45
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 bcrypt.check_password_hash(user.password,request.form['password']):
                login_user(user)
                flash('You were just logged in.')
                return redirect(url_for('home.home'))
            else:
               error = 'Invalid Credentials. Please try again.'
    return render_template('login.html', form=form, error=error)
示例#46
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            login_user(user)
            flash('Welcome.', 'success')
            return redirect(url_for('main.home'))
        else:
            flash('Invalid email and/or password.', 'danger')
            return render_template('user/login.html', form=form)
    return render_template('user/login.html', form=form)
示例#47
0
文件: views.py 项目: anandka/SEWA
def login():
    if request.method == 'POST':
        user = User.query.filter_by(username=request.form['name']).first()
        print user.password
        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            login_user(user)
            #flash('Welcome.', 'success')
            return render_template('html/myservices.html')
        else:
            #flash('Invalid email and/or password.', 'danger')
            return render_template('html/login.html')
    return render_template('html/login.html')
示例#48
0
def login():
    """Login page for admins."""
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password, request.form["password"]):
            login_user(user)
            flash("You are logged in. Welcome!", "success")
            return redirect(url_for("user.admin"))
        else:
            flash("Invalid email and/or password.", "danger")
            return render_template("user/login.html", form=form)
    return render_template("user/login.html", form=form)
示例#49
0
def apilogin():
    if request.headers['Content-Type'] == 'application/json':
        # user = User.query.filter_by(user_token = request.json['token']).first()
        user = User.query.filter_by(email = request.json['email']).first()

        data = {}
        if user and bcrypt.check_password_hash(user.password, request.json['password']):
            login_user(user)
            data['token'] = user.user_token
            data['response'] = "success"
            return json.dumps(data)
        else:
            data['response'] = "failure"
            return json.dumps(data)
示例#50
0
def change_pswd():
    form = ChangePasswordForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            user.password = request.form['new']
            login_user(user)
            flash('Welcome.', 'success')
            return render_template('user/chat_login.html')
        else:
            flash('Invalid password or passwords do not match.', 'danger')
            return render_template('user/change_pswd.html', form=form)
    return render_template('user/change_pswd.html', form=form)
示例#51
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        # We can find the user and the password matches its hashed value
        if user and bcrypt.check_password_hash(
                user.password, request.form['password']):
            login_user(user)
            flash('Welcome.', 'success')
            return render_template('user/chat_login.html')
        else:
            flash('Invalid username and/or password.', 'danger')
            return render_template('user/login.html', form=form)
    return render_template('user/login.html', form=form)
示例#52
0
文件: views.py 项目: doobeh/gsam
def login():
    if g.user.is_authenticated:
        flash("You are already Logged in", "warning")
        return redirect(request.args.get("next") or url_for("members"))
    error = ""
    lforms = LoginForm()
    if lforms.validate_on_submit():
        user = User.query.filter_by(username=lforms.username.data).first()
        if user is not None and bcrypt.check_password_hash(user.password, lforms.password.data):
            login_user(user, remember=lforms.remember.data)
            flash("You are sucessfuly Logged in", "success")
            return redirect(url_for("members"))
        else:
            flash("You have entered an incorrect username and passwor", "danger")
    return render_template("gstheme/login.html", forms=lforms, error=error)
def login():
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter_by(name=request.form['name']).first()
            if user and bcrypt.check_password_hash(user.password, request.form['password']):
                session['logged_in'] = True
                session['user_id'] = user.id
                session['user_role'] = user.role
                session['user_name'] = user.name
                flash('Welcome')
                return redirect(url_for('tasks.tasks'))
            elif not user:
                form.name.errors.append('Username not recognized')
            else:
                form.password.errors.append('Incorrect password')
    return render_template('login.html', form=form)
示例#54
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['name']).first()
            if user is not None and bcrypt.check_password_hash(user.password,
                                                               request.form['password']):
                flash("Welcome ! You were successfully logged in.")
                session['logged_in'] = True
                session['user_id'] = user.user_id
                session['role'] = user.role
                session['name'] = user.name
                return redirect(url_for('tasks.tasks'))
            else:
                error = 'Invalid username or password. Please try again.'
    return render_template("login.html", form=form, error=error)
示例#55
0
 def test_new_account_in_database(self):
     """Test new account in database with encrypted password."""
     self.client.post(
         '/users/register',
         data={
             'name': 'John Smith',
             'email': self.new_email,
             'password': self.new_password,
             'confirm_password': self.new_password
         },
         follow_redirects=True
     )
     user = User.query.filter_by(email=self.new_email).first()
     self.assertTrue(user)
     self.assertEqual('John Smith', user.name)
     self.assertTrue(bcrypt.check_password_hash(
         user.password, self.new_password
     ))
示例#56
0
def login():
    error = None
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            query = User.query
            """:type: sqlalchemy.orm.Query"""
            user = query.filter_by(name=request.form['name']).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['role'] = user.role
                session['name']=user.name
                flash("Welcome!")
                return redirect(url_for('tasks.tasks'))
            else:
                error = 'Invalid username or password'
    return render_template("login.html", form=form, error=error)
示例#57
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['name']).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['role'] = user.role
                flash("You have succesfully logged in, %s" % user.name)
                return redirect(url_for('tasks.tasks'))
            else:
                error = "Invalid username or password"
                return render_template("login.html", form=form, error=error)
        else:
            return render_template("login.html", form=form, error=error)
    return render_template("login.html", form=form)
示例#58
0
 def test_user_can_change_password(self):
     """Test the user can update email."""
     with self.client:
         self.login()
         response = self.client.post(
             '/users/edit/password',
             data={
                 'password': self.new_password,
                 'confirm_password': self.new_password,
             },
             follow_redirects=True
         )
         self.assertIn(
             b'Your password has been updated.',
             response.data
         )
         self.assertTrue(bcrypt.check_password_hash(
             current_user.password, self.new_password
         ))
示例#59
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['name']).first()
            if user is not None and bcrypt.check_password_hash(user.password, form.password.data ):
                login_user(user)
                flash('Logged in!')
                return redirect(url_for('users.dash', id = user.id))
            else:
                error = "Invalid Credentials, please try again."
                return render_template('login.html',form=form,error=error)
        else:
            return render_template('login.html',form=form,error=error)
    # 
    return render_template('login.html',form=form,error=error)
示例#60
0
    def post(self):
        data = request.get_json(force=True)
        email = data['email']
        password = data['password']
        user = Users.query.filter_by(email=email).first()
        if user == None:
            response = make_response(
                jsonify({'message': 'invalid username/password'}))
            # response.status_code = 401
            return response
        if bcrypt.check_password_hash(user.password, password):

            token = create_token(user)
            return {'message': 'successful','token': token}
        else:
            response = make_response(
                jsonify({'message': 'invalid username/password'}))
            # response.status_code = 401
            return response