Beispiel #1
0
def user_apikey_route(user_id, action):
    """manage apikey for user"""

    user = User.query.get(user_id)
    form = ButtonForm()
    if user and form.validate_on_submit():

        if action == 'generate':
            apikey = PWS.generate_apikey()
            user.apikey = PWS.hash_simple(apikey)
            db.session.commit()
            return jsonify({
                'title': 'Apikey operation',
                'detail': 'New apikey generated: %s' % apikey
            }), HTTPStatus.OK

        if action == 'revoke':
            user.apikey = None
            db.session.commit()
            return jsonify({
                'title': 'Apikey operation',
                'detail': 'Apikey revoked'
            }), HTTPStatus.OK

    return jsonify({
        'title': 'Apikey operation',
        'detail': 'Invalid request'
    }), HTTPStatus.BAD_REQUEST
Beispiel #2
0
def login_route():
    """login route"""

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter(
            User.active, User.username == form.username.data).one_or_none()
        if user:
            if form.password.data:
                if PWS.compare(
                        PWS.hash(form.password.data,
                                 PWS.get_salt(user.password)), user.password):
                    if user.totp:
                        session['totp_login_user_id'] = user.id
                        return redirect(
                            url_for('auth.login_totp_route', **request.args))

                    regenerate_session()
                    login_user(user)
                    return redirect_after_login()
            else:
                if user.webauthn_credentials:
                    session['webauthn_login_user_id'] = user.id
                    return redirect(
                        url_for('auth.login_webauthn_route', **request.args))

        flash('Invalid credentials.', 'error')

    return render_template('auth/login.html', form=form)
Beispiel #3
0
def test_login_totp(client, user_factory):
    """test login totp"""

    password = PWS.generate()
    secret = TOTPImpl.random_base32()
    user = user_factory(password=PWS.hash(password), totp=secret)

    response = client.get(url_for('auth.login_totp_route'))
    assert response.status_code == HTTPStatus.FOUND
    assert url_for('auth.login_route') in response.headers['Location']

    form = client.get(url_for('auth.login_route')).form
    form['username'] = user.username
    form['password'] = password
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    form = response.follow().form
    form['code'] = 'invalid'
    response = form.submit()
    assert response.status_code == HTTPStatus.OK
    assert response.lxml.xpath(
        '//div[@class="invalid-feedback" and text()="Invalid code"]')

    form = response.form
    form['code'] = TOTPImpl(secret).current_code()
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    response = client.get(url_for('index_route'))
    assert response.lxml.xpath('//a[text()="Logout"]')
Beispiel #4
0
def apikey():
    """yield valid apikey for user in role agent"""

    tmp_apikey = PWS.generate_apikey()
    db.session.add(User(username='******', apikey=PWS.hash_simple(tmp_apikey), active=True, roles=['agent']))
    db.session.commit()
    yield tmp_apikey
Beispiel #5
0
class UserFactory(BaseModelFactory):  # pylint: disable=too-few-public-methods
    """test user model factory"""
    class Meta:  # pylint: disable=too-few-public-methods
        """test user model factory"""
        model = User

    username = '******'
    password = LazyAttribute(lambda x: PWS.hash(PWS.generate()))
    active = True
    roles = ['user']
Beispiel #6
0
def add_agent():
    """add new agent"""

    apikey = PWS.generate_apikey()
    agent = User(username=f'agent_{uuid4()}',
                 apikey=PWS.hash_simple(apikey),
                 active=True,
                 roles=['agent'])
    db.session.add(agent)
    db.session.commit()
    print(f'new agent {agent.username} apikey {apikey}')
Beispiel #7
0
def reset_password(username):
    """reset password for username"""

    user = User.query.filter(User.username == username).one_or_none()
    if not user:
        current_app.logger.error('no such user')
        sys.exit(1)

    new_password = PWS.generate()
    user.password = PWS.hash(new_password)
    db.session.commit()
    print(f'new password "{user.username}:{new_password}"')
Beispiel #8
0
def client_in_roles(clnt, roles):
    """create user role and login client to role(s)"""

    password = PWS.generate()
    user = User(username='******', password=PWS.hash(password), active=True, roles=roles)
    db.session.add(user)
    db.session.commit()

    form = clnt.get(url_for('auth.login_route')).form
    form['username'] = user.username
    form['password'] = password
    form.submit()
    return clnt
Beispiel #9
0
def selenium_in_roles(sclnt, roles):
    """create user role and login selenium to role(s)"""

    tmp_password = PWS.generate()
    tmp_user = User(username='******', password=PWS.hash(tmp_password), active=True, roles=roles)
    db.session.add(tmp_user)
    db.session.commit()

    sclnt.get(url_for('auth.login_route', _external=True))
    sclnt.find_element_by_xpath('//form//input[@name="username"]').send_keys(tmp_user.username)
    sclnt.find_element_by_xpath('//form//input[@name="password"]').send_keys(tmp_password)
    sclnt.find_element_by_xpath('//form//input[@type="submit"]').click()
    webdriver_waituntil(sclnt, EC.presence_of_element_located((By.XPATH, '//a[text()="Logout"]')))

    return sclnt
Beispiel #10
0
def test_profile_changepassword_route(cl_user):
    """user profile change password"""

    cur_password = PWS().generate()
    new_password = PWS().generate()
    user = User.query.filter(User.username == 'pytest_user').one()
    user.password = cur_password
    db.session.commit()

    form = cl_user.get(url_for('auth.profile_changepassword_route')).form
    form['current_password'] = cur_password
    form['password1'] = 'AlongPassword1'
    form['password2'] = 'AlongPassword2'
    response = form.submit()
    assert response.status_code == HTTPStatus.OK
    assert response.lxml.xpath(
        '//div[@class="invalid-feedback" and text()="Passwords does not match."]'
    )

    form = cl_user.get(url_for('auth.profile_changepassword_route')).form
    form['current_password'] = cur_password
    form['password1'] = 'weak'
    form['password2'] = 'weak'
    response = form.submit()
    assert response.status_code == HTTPStatus.OK
    assert response.lxml.xpath(
        '//div[@class="invalid-feedback" and contains(text(), "Password too short.")]'
    )

    form = cl_user.get(url_for('auth.profile_changepassword_route')).form
    form['current_password'] = '******'
    form['password1'] = new_password
    form['password2'] = new_password
    response = form.submit()
    assert response.status_code == HTTPStatus.OK
    assert response.lxml.xpath(
        '//script[contains(text(), "toastr[\'error\'](\'Invalid current password.\');")]'
    )

    form = cl_user.get(url_for('auth.profile_changepassword_route')).form
    form['current_password'] = cur_password
    form['password1'] = new_password
    form['password2'] = new_password
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND
    user = User.query.filter(User.username == 'pytest_user').one()
    assert PWS.compare(PWS.hash(new_password, PWS.get_salt(user.password)),
                       user.password)
Beispiel #11
0
def test_addagent_command(runner):
    """add agent command test"""

    result = runner.invoke(command, ['add-agent'])
    assert result.exit_code == 0
    new_apikey = result.output.strip().split(' ')[-1]
    assert User.query.first().apikey == PWS.hash_simple(new_apikey)
Beispiel #12
0
def test_unauthorized(client, user_factory):
    """test for not logged in, redirect and final login"""

    password = PWS.generate()
    user = user_factory.create(password=PWS.hash(password))

    response = client.get(url_for('auth.profile_route'))
    assert response.status_code == HTTPStatus.FOUND
    assert '/auth/login?next=' in response.headers['Location']

    form = response.follow().form
    form['username'] = user.username
    form['password'] = password
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND
    assert url_for('auth.profile_route') in response.headers['Location']
Beispiel #13
0
def test_user_edit_route(cl_admin, user):
    """user edit route test"""

    password = PWS.generate()

    form = cl_admin.get(url_for('auth.user_edit_route', user_id=user.id)).form
    form['username'] = f'{form["username"].value}_edited'
    form['new_password'] = password
    form['roles'] = []
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    tuser = User.query.filter(User.username == form['username'].value).one()
    assert tuser.username == form['username'].value
    assert PWS.compare(PWS.hash(password, PWS.get_salt(tuser.password)), tuser.password)
    assert not user.roles
Beispiel #14
0
def profile_changepassword_route():
    """user profile change password"""

    form = UserChangePasswordForm()
    if form.validate_on_submit():
        user = User.query.filter(User.id == current_user.id).one()

        if not PWS.compare(PWS.hash(form.current_password.data, PWS.get_salt(user.password)), user.password):
            flash('Invalid current password.', 'error')
        else:
            user.password = PWS.hash(form.password1.data)
            db.session.commit()
            flash('Password changed.', 'info')
            return redirect(url_for('auth.profile_route'))

    return render_template('auth/profile/changepassword.html', form=form)
Beispiel #15
0
def test_user_add_route(cl_admin, user_factory):
    """user add route test"""

    password = PWS.generate()
    auser = user_factory.build()

    form = cl_admin.get(url_for('auth.user_add_route')).form
    form['username'] = auser.username
    form['roles'] = auser.roles
    form['active'] = auser.active
    form['new_password'] = password
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    tuser = User.query.filter(User.username == auser.username).one()
    assert tuser.username == auser.username
    assert PWS.compare(PWS.hash(password, PWS.get_salt(tuser.password)), tuser.password)
    assert tuser.active == auser.active
    assert tuser.roles == auser.roles
Beispiel #16
0
def load_user_from_request(req):
    """api authentication; load user form request"""

    auth_header = req.headers.get('Authorization')
    if auth_header:
        apikey = auth_header.replace('Apikey ', '', 1)
        if apikey:
            return User.query.filter(
                User.active, User.apikey == PWS.hash_simple(apikey)).first()
    return None
Beispiel #17
0
def test_user_add_route(cl_admin):
    """user add route test"""

    tmp_password = PWS().generate()
    test_user = create_test_user()

    form = cl_admin.get(url_for('auth.user_add_route')).form
    form['username'] = test_user.username
    form['password'] = tmp_password
    form['roles'] = test_user.roles
    form['active'] = test_user.active
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    user = User.query.filter(User.username == test_user.username).one()
    assert user.username == test_user.username
    assert PWS.compare(PWS.hash(tmp_password, PWS.get_salt(user.password)),
                       user.password)
    assert user.active == test_user.active
    assert user.roles == test_user.roles
Beispiel #18
0
def user_edit_route(user_id):
    """edit task"""

    user = User.query.get(user_id)
    form = UserForm(obj=user)

    if form.validate_on_submit():
        form.populate_obj(user)
        if form.new_password.data:
            user.password = PWS.hash(form.new_password.data)
        db.session.commit()
        return redirect(url_for('auth.user_list_route'))

    return render_template('auth/user/addedit.html', form=form)
Beispiel #19
0
def test_login(client, user_factory):
    """test login"""

    password = PWS.generate()
    user = user_factory.create(password=PWS.hash(password))

    form = client.get(url_for('auth.login_route')).form
    form['username'] = user.username
    form['password'] = '******'
    response = form.submit()
    assert response.status_code == HTTPStatus.OK
    assert response.lxml.xpath(
        '//script[contains(text(), "toastr[\'error\'](\'Invalid credentials.\');")]'
    )

    form = client.get(url_for('auth.login_route')).form
    form['username'] = user.username
    form['password'] = password
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    response = client.get(url_for('index_route'))
    assert response.lxml.xpath('//a[text()="Logout"]')
Beispiel #20
0
def user_add_route():
    """add user"""

    form = UserForm()

    if form.validate_on_submit():
        user = User()
        form.populate_obj(user)
        if form.new_password.data:
            user.password = PWS.hash(form.new_password.data)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('auth.user_list_route'))

    return render_template('auth/user/addedit.html', form=form)
Beispiel #21
0
    def apikey(self, value):
        """apikey setter"""

        self._apikey = PWS.hash_simple(value) if value else None
Beispiel #22
0
def strong_password(form, field):
    """validate password field"""

    pwsr = PWS.check_strength(field.data)
    if not pwsr.is_strong:
        raise ValidationError(pwsr.message)