示例#1
0
    def post(self):
        json_data = request.get_json()

        if not json_data:
            response = jsonify({'error': 'Invalid input.'})
            return response, 400

        try:
            data = auth_schema.load(json_data)
        except ValidationError as err:
            response = jsonify({'error': err.messages})

            return response, 422

        user = User.find_by_identity(data['identity'])

        if user and user.authenticated(password=data['password']):
            # identity is used to lookup a user on protected endpoints
            access_token = create_access_token(identity=user.username)

            response = jsonify({'data': {'access_token': access_token}})

            return response, 200

        response = jsonify({'error': 'Invalid credentials.'})
        return response, 401
示例#2
0
def callback_handling():
    # Handles response from token endpoint
    auth0.authorize_access_token()
    resp = auth0.get('userinfo')
    userinfo = resp.json()

    # Check if user in database
    if not User.find_by_identity(userinfo['email']):
        print('why I am here????')
        print(f"\n\n\n{User.find_by_identity(userinfo['email'])}\n\n\n")
        print(f"\n\n\n{userinfo['email']}\n\n\n")
        User.create(username=userinfo['nickname'],
                    name=userinfo['name'],
                    email=userinfo['email'],
                    image_link=userinfo['picture'])

    # Store the user information in flask session
    session[constants.JWT_PAYLOAD] = userinfo
    session[constants.PROFILE_KEY] = {
        'user_id': userinfo['sub'],
        'name': userinfo['name'],
        'picture': userinfo['picture']
    }

    return redirect('/dashboard')
示例#3
0
def login():
    form = LoginForm(next=request.args.get('next'))

    if form.validate_on_submit():
        u = User.find_by_identity(request.form.get('identity'))

        if u and u.authenticated(password=request.form.get('password')):
            # As you can see remember me is always enabled, this was a design
            # decision I made because more often than not users want this
            # enabled. This allows for a less complicated login form.
            #
            # If however you want them to be able to select whether or not they
            # should remain logged in then perform the following 3 steps:
            # 1) Replace 'True' below with: request.form.get('remember', False)
            # 2) Uncomment the 'remember' field in user/forms.py#LoginForm
            # 3) Add a checkbox to the login form with the id/name 'remember'
            if login_user(u, remember=True) and u.is_active():
                u.update_activity_tracking(request.remote_addr)

                # Handle optionally redirecting to the next URL safely.
                next_url = request.form.get('next')
                if next_url:
                    return redirect(safe_next_url(next_url))

                return redirect(url_for('user.settings'))
            else:
                flash('This account has been disabled.', 'error')
        else:
            flash('Identity or password is incorrect.', 'error')

    return render_template('user/login.html', form=form)
示例#4
0
def seed():
    """
    Seed the database with an initial user.

    :return: User instance
    """
    if User.find_by_identity(app.config['SEED_ADMIN_EMAIL']) is not None:
        return None

    params = {
        'role': 'admin',
        'email': app.config['SEED_ADMIN_EMAIL'],
        'username': app.config['SEED_ADMIN_USERNAME'],
        'password': app.config['SEED_ADMIN_PASSWORD']
    }

    member = {
        'role': 'member',
        'email': app.config['SEED_MEMBER_EMAIL'],
        'username': app.config['SEED_MEMBER_USERNAME'],
        'password': app.config['SEED_ADMIN_PASSWORD']
    }

    member2 = {
        'role': 'member',
        'email': app.config['SEED_TEST_EMAIL'],
        'password': app.config['SEED_ADMIN_PASSWORD']
    }

    User(**member).save()
    User(**member2).save()

    return User(**params).save()
示例#5
0
    def test_deliver_password_reset_email(self, token):
        """ Deliver a password reset email. """
        with mail.record_messages() as outbox:
            user = User.find_by_identity('*****@*****.**')
            deliver_password_reset_email(user.id, token)

            assert len(outbox) == 1
            assert token in outbox[0].body
示例#6
0
    def test_begin_update_credentials_email_change(self):
        """ Update credentials but only the e-mail address. """
        self.login()

        user = {'current_password': '******', 'email': '*****@*****.**'}
        response = self.client.post(url_for('user.update_credentials'),
                                    data=user,
                                    follow_redirects=True)

        assert_status_with_message(200, response,
                                   'Your sign in settings have been updated.')

        old_user = User.find_by_identity('*****@*****.**')
        assert old_user is None

        new_user = User.find_by_identity('*****@*****.**')
        assert new_user is not None
示例#7
0
def token(db):
    """
    Serialize a JWS token.

    :param db: Pytest fixture
    :return: JWS token
    """
    user = User.find_by_identity('*****@*****.**')
    return user.serialize_token()
示例#8
0
    def test_login_activity(self, users):
        """ Login successfully and update the activity stats. """
        user = User.find_by_identity('*****@*****.**')
        old_sign_in_count = user.sign_in_count

        response = self.login()

        new_sign_in_count = user.sign_in_count

        assert response.status_code == 200
        assert (old_sign_in_count + 1) == new_sign_in_count
def ensure_unique_identity(data):
    """
    Ensures that and email or username is not already taken

    :return: data from the request
    """
    user = User.find_by_identity(data)
    if user:
        raise ValidationError('{0} already exists.'.format(data))

    return data
示例#10
0
def ensure_identity_exists(form, field):
    """
    Ensure an identity exists.

    :param form: wtforms Instance
    :param field: Field being passed in
    :return: None
    """
    user = User.find_by_identity(field.data)

    if not user:
        raise ValidationError('Unable to locate account.')
示例#11
0
    def test_password_reset(self, users, token):
        """ Reset successful. """
        reset = {'password': '******', 'reset_token': token}
        response = self.client.post(url_for('user.password_reset'),
                                    data=reset,
                                    follow_redirects=True)

        assert_status_with_message(200, response,
                                   'Your password has been reset.')

        admin = User.find_by_identity('*****@*****.**')
        assert admin.password != 'newpassword'
示例#12
0
文件: views.py 项目: rcharp/parser
def login():

    form = LoginForm(next=request.args.get('next'))

    if form.validate_on_submit():
        u = User.find_by_identity(request.form.get('identity'))

        if u and u.authenticated(password=request.form.get('password')):
            # As you can see remember me is always enabled, this was a design
            # decision I made because more often than not users want this
            # enabled. This allows for a less complicated login form.
            #
            # If however you want them to be able to select whether or not they
            # should remain logged in then perform the following 3 steps:
            # 1) Replace 'True' below with: request.form.get('remember', False)
            # 2) Uncomment the 'remember' field in user/forms.py#LoginForm
            # 3) Add a checkbox to the login form with the id/name 'remember'
            if login_user(u, remember=True) and u.is_active():
                u.update_activity_tracking(request.remote_addr)

                # Handle optionally redirecting to the next URL safely.
                next_url = request.form.get('next')
                if next_url:
                    return redirect(safe_next_url(next_url))

                if current_user.role == 'admin':
                    return redirect(url_for('admin.dashboard'))

                if current_user.role == 'member':

                    if not cache.get(current_user.mailbox_id):
                        from app.blueprints.user.tasks import get_emails, get_rules, set_cache

                        emails = get_emails.delay(current_user.mailbox_id)

                        set_cache.delay(current_user.mailbox_id, emails.id)

                    if current_user.trial:
                        trial_days_left = 14 - (
                            datetime.datetime.now() -
                            current_user.created_on.replace(tzinfo=None)).days
                        if trial_days_left < 0:
                            current_user.trial = False
                            current_user.save()

                return redirect(url_for('user.settings'))
            else:
                flash('This account has been disabled.', 'error')
        else:
            flash('Your username/email or password is incorrect.', 'error')

    return render_template('user/login.html', form=form)
示例#13
0
    def test_welcome_with_existing_username(self, users):
        """ Create username failure due to username already existing. """
        self.login()

        u = User.find_by_identity('*****@*****.**')
        u.username = '******'
        u.save()

        user = {'username': '******'}
        response = self.client.post(url_for('user.welcome'),
                                    data=user,
                                    follow_redirects=True)

        assert_status_with_message(200, response,
                                   'You already picked a username.')
示例#14
0
def subscriptions(db):
    """
    Create subscription fixtures.

    :param db: Pytest fixture
    :return: SQLAlchemy database session
    """
    subscriber = User.find_by_identity('*****@*****.**')
    if subscriber:
        subscriber.delete()
    db.session.query(Subscription).delete()

    params = {
        'role': 'admin',
        'email': '*****@*****.**',
        'name': 'Subby',
        'password': '******',
        'payment_id': 'cus_000'
    }

    subscriber = User(**params)

    # The account needs to be commit before we can assign a subscription to it.
    db.session.add(subscriber)
    db.session.commit()

    # Create a subscription.
    params = {
        'user_id': subscriber.id,
        'plan': 'gold'
    }
    subscription = Subscription(**params)
    db.session.add(subscription)

    # Create a credit card.
    params = {
        'user_id': subscriber.id,
        'brand': 'Visa',
        'last4': '4242',
        'exp_date': datetime.date(2015, 6, 1)
    }
    credit_card = CreditCard(**params)
    db.session.add(credit_card)

    db.session.commit()

    return db
示例#15
0
def seed():
    """
    Seed the database with an initial user.

    :return: User instance
    """
    if User.find_by_identity(os.environ['SEED_ADMIN_EMAIL']) is not None:
        return None

    params = {
        'username': os.environ['SEED_USER_EMAIL'],
        'password': os.environ['SEED_USER_PASSWORD'],
        'first_name': os.environ['SEED_USER_FIRSTNAME'],
        'last_name': os.environ['SEED_USER_LASTNAME']
    }

    return User(**params).save()
示例#16
0
    def test_signup(self, users):
        """ Signup successfully. """
        old_user_count = User.query.count()

        user = {'email': '*****@*****.**', 'password': '******'}
        response = self.client.post(url_for('user.signup'),
                                    data=user,
                                    follow_redirects=True)

        assert_status_with_message(200, response,
                                   'Awesome, thanks for signing up!')

        new_user_count = User.query.count()
        assert (old_user_count + 1) == new_user_count

        new_user = User.find_by_identity('*****@*****.**')
        assert new_user.password != 'password'
示例#17
0
文件: cmd_db.py 项目: rcharp/parser
def seed():
    """
    Seed the database with an initial user.

    :return: User instance
    """
    if User.find_by_identity(app.config['SEED_ADMIN_EMAIL']) is not None:
        return None

    params = {
        'role': 'admin',
        'email': app.config['SEED_ADMIN_EMAIL'],
        'password': app.config['SEED_ADMIN_PASSWORD'],
        'mailbox_id': 'ADMIN'
    }

    return User(**params).save()
示例#18
0
def seed():
    """
    Seed the database with an initial user.

    :return: User Instance
    """
    # Look for the user with the seed admin email first. If the user
    # already exists in the database, exit the function
    if User.find_by_identity(app.config['SEED_ADMIN_EMAIL']) is not None:
        return None

    # Otherwise Create and Insert the user
    params = {
        'role': 'admin',
        'email': app.config['SEED_ADMIN_EMAIL'],
        'password': app.config['SEED_ADMIN_PASSWORD']
    }

    print("Seeding users.")
    # **params converts all the dictionary pairs to keyword arguments
    return User(**params).save()