Beispiel #1
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')
Beispiel #2
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()
Beispiel #3
0
def init(with_testdb, with_data):
    """
    Initialize the database.

    :param with_data:
    :param with_testdb: Create a test database
    :return: None
    """
    uri = app.config['SQLALCHEMY_DATABASE_URI']
    print(f"Database uri is {uri}")
    if not database_exists(uri):
        create_database(uri)
        db.create_all()
    else:
        db.drop_all()
        db.create_all()

    if with_testdb:
        db_uri = '{0}_test'.format(app.config['SQLALCHEMY_DATABASE_URI'])
        if not database_exists(db_uri):
            create_database(db_uri)

    user = User()
    user.username = "******"
    user.save()

    if with_data:
        _seed_catalog()
    return None
Beispiel #4
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)
Beispiel #5
0
def users(db):
    """
    Create user fixtures. They reset per test.

    :param db: Pytest fixture
    :return: SQLAlchemy database session
    """
    db.session.query(User).delete()

    users = [
        {
            'role': 'admin',
            'email': '*****@*****.**',
            'password': '******'
        },
        {
            'active': False,
            'email': '*****@*****.**',
            'password': '******'
        }
    ]

    for user in users:
        db.session.add(User(**user))

    db.session.commit()

    return db
 def register_user(self, seed):
     user = User(email='user' + str(seed) + '@example.com',
                 username='******' + str(seed),
                 password='******')
     db.session.add(user)
     db.session.commit()
     return user
def db(app):
    """
    Set up test database, this only gets executed once per session.

    :param app: Pytest fixture
    :return: SQLAlchemy database session
    """

    _db.drop_all()
    _db.create_all()

    # Create a single user, a lot of tests will not mutate this user
    params = {
        'role': 'admin',
        'email': '*****@*****.**',
        'username': '******',
        'password': '******'
    }

    admin = User(**params)

    _db.session.add(admin)
    _db.session.commit()

    return _db
Beispiel #8
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
Beispiel #9
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
Beispiel #10
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()
Beispiel #11
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
Beispiel #12
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'],
        'password': app.config['SEED_ADMIN_PASSWORD'],
        'mailbox_id': 'ADMIN'
    }

    return User(**params).save()
Beispiel #13
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
Beispiel #14
0
def users(page):
    search_form = SearchForm()
    bulk_form = BulkDeleteForm()

    sort_by = User.sort_by(request.args.get('sort', 'created_on'),
                           request.args.get('direction', 'desc'))
    order_values = '{0} {1}'.format(sort_by[0], sort_by[1])

    paginated_users = User.query \
        .filter(User.search(request.args.get('q', ''))) \
        .order_by(User.role.asc(), User.payment_id, User.created_on).paginate(page, 50, True)#text(order_values)) \
    #.paginate(page, 50, True)

    return render_template('admin/user/index.html',
                           form=search_form,
                           bulk_form=bulk_form,
                           users=paginated_users)
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        username = form.username.data
        if User.find_by_username(username):
            flash("The username has been taken.",
                  "alert alert-danger")
            return redirect(url_for('bp_user.register'))
        else:
            user = User(username=username)
            user.set_password(form.password.data)
            db.session.add(user)
            db.session.commit()
            flash("Welcome {}, you're now ready to go.".format(username),
                  "alert alert-success")
            # add auto login after register
            return redirect(url_for('bp_user.login'))
    return render_template('register.html', form=form)
Beispiel #16
0
def token(db):
    """
    Serialize a JWS token.

    :param db: Pytest fixture
    :return: JWS token
    """
    user = User.find_by_identity('*****@*****.**')
    return user.serialize_token()
Beispiel #17
0
def delete_users(ids):
    """
    Delete users and potentially cancel their subscription.

    :param ids: List of ids to be deleted
    :type ids: list
    :return: int
    """
    return User.bulk_delete(ids)
Beispiel #18
0
def begin_password_reset():
    form = BeginPasswordResetForm()

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

        flash('An email has been sent to {0}.'.format(u.email), 'success')
        return redirect(url_for('user.login'))

    return render_template('user/begin_password_reset.html', form=form)
Beispiel #19
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
Beispiel #21
0
def password_reset():
    form = PasswordResetForm(reset_token=request.args.get('reset_token'))

    if form.validate_on_submit():
        u = User.deserialize_token(request.form.get('reset_token'))

        if u is None:
            flash('Your reset token has expired or was tampered with.',
                  'error')
            return redirect(url_for('user.begin_password_reset'))

        form.populate_obj(u)
        u.password = User.encrypt_password(request.form.get('password'))
        u.save()

        if login_user(u):
            flash('Your password has been reset.', 'success')
            return redirect(url_for('user.settings'))

    return render_template('user/password_reset.html', form=form)
Beispiel #22
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'
Beispiel #23
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.')
Beispiel #24
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()
Beispiel #25
0
def dashboard():
    # initialize the current user
    user = User.find_by_username(current_user.username)

    # initialize forms
    todo_form = ToDoForm()
    keepdo_form = KeepDoForm()

    # query url '?todopage=' and '?keepdopage='
    todo_page = request.args.get('todopage', 1, type=int)
    keepdo_page = request.args.get('keepdopage', 1, type=int)

    # initialize pagination objects and build necessary arguments
    todolist = user.todolist.order_by(ToDoList.status.desc(),
                                      ToDoList.timestamp.desc()).paginate(
                                          todo_page, 8, False)
    keepdolist = user.keepdolist.order_by(
        KeepDoList.created_timestamp.desc()).paginate(keepdo_page, 8, False)

    todo_args = pagination_builder(todolist,
                                   'todopage',
                                   form=todo_form,
                                   page=todo_page,
                                   todolist=todolist.items)
    keepdo_args = pagination_builder(keepdolist,
                                     'keepdopage',
                                     form=keepdo_form,
                                     page=keepdo_page,
                                     keepdolist=keepdolist.items)

    # IMPORTANT!
    # not based on user's timezone, improve in the future
    # modify keepdolist database everytime page is loaded, may slow the performance
    for keepdo in keepdolist.items:
        days_interval = (datetime.utcnow() - keepdo.last_check_point).days
        # if not checked for over 1 day
        # change daily check status to False and commit to database
        if days_interval > 0:
            keepdo.daily_check_status = False
            db.session.commit()

    # initialize session keys for the first time
    # will not run those lines afterwards
    # those session keys will be used in generating templates
    if not 'todolist_collapse' in session:
        session['todolist_collapse'] = 'in'  # default expand todolist panel
        # default expand keepdolist panel
        session['keepdolist_collapse'] = 'in'

    return render_template('dashboard.html',
                           todo_args=todo_args,
                           keepdo_args=keepdo_args)
Beispiel #26
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))

                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)
Beispiel #27
0
 def google_logged_in(blueprint, token):
     if not token:
         flash("Failed to log in with {name}".format(name=blueprint.name))
         return
     # figure out who the user is
     resp = blueprint.session.get("/oauth2/v2/userinfo")
     if resp.ok:
         username = resp.json()["email"]
         query = User.query.filter_by(username=username)
         try:
             user = query.one()
         except NoResultFound:
             # create a user
             user = User()
             user.username = username
             user.save()
         login_user(user)
         flash("Successfully signed in with Google", "success")
     else:
         msg = "Failed to fetch user info from {name}".format(
             name=blueprint.name)
         flash(msg, category="error")
Beispiel #28
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.')
Beispiel #29
0
 def github_logged_in(blueprint, token):
     if not token:
         flash("Failed to log in with {name}".format(name=blueprint.name))
         return
     # figure out who the user is
     resp = blueprint.session.get("/user")
     if resp.ok:
         print(f"Response from github: {resp.json()}")
         username = resp.json()["login"]
         query = User.query.filter_by(username=username)
         try:
             user = query.one()
         except NoResultFound:
             # create a user
             user = User()
             user.username = username
             user.save()
         login_user(user)
         flash("Successfully signed in with Github", "success")
     else:
         print(resp.text)
         msg = "Failed to fetch user info from {name}".format(
             name=blueprint.name)
         flash(msg, category="error")
Beispiel #30
0
def seed():
    """
    Seed the database with an initial user. The username, email and password
    are taken from the app config.

    :return: User instance
    """

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

    return User(**params).save()