Exemple #1
0
def new_user():
    """ Create a new user.
    """
    form = forms.NewUserForm()
    if form.validate_on_submit():

        username = form.user.data
        if pagure.lib.search_user(SESSION, username=username):
            flask.flash('Username already taken.', 'error')
            return flask.redirect(flask.request.url)

        email = form.email_address.data
        if pagure.lib.search_user(SESSION, email=email):
            flask.flash('Email address already taken.', 'error')
            return flask.redirect(flask.request.url)

        form.password.data = generate_hashed_value(form.password.data)

        token = pagure.lib.login.id_generator(40)

        user = model.User()
        user.token = token
        form.populate_obj(obj=user)
        user.default_email = form.email_address.data
        SESSION.add(user)
        SESSION.flush()

        emails = [email.email for email in user.emails]
        if form.email_address.data not in emails:
            useremail = model.UserEmail(
                user_id=user.id,
                email=form.email_address.data)
            SESSION.add(useremail)
            SESSION.flush()

        try:
            SESSION.commit()
            send_confirmation_email(user)
            flask.flash(
                'User created, please check your email to activate the '
                'account')
        except SQLAlchemyError as err:  # pragma: no cover
            SESSION.rollback()
            flask.flash('Could not create user.')
            APP.logger.debug('Could not create user.')
            APP.logger.exception(err)

        return flask.redirect(flask.url_for('auth_login'))

    return flask.render_template(
        'login/user_new.html',
        form=form,
    )
Exemple #2
0
def change_password():
    """ Method to change the password for local auth users.
    """

    form = forms.ChangePasswordForm()
    user_obj = pagure.lib.query.search_user(
        flask.g.session, username=flask.g.fas_user.username
    )

    if not user_obj:
        flask.abort(404, description="User not found")

    if form.validate_on_submit():

        try:
            password_checks = check_password(
                form.old_password.data,
                user_obj.password,
                seed=pagure.config.config.get("PASSWORD_SEED", None),
            )
        except pagure.exceptions.PagureException as err:
            _log.exception(err)
            flask.flash(
                "Could not update your password, either user or password "
                "could not be checked",
                "error",
            )
            return flask.redirect(flask.url_for("auth_login"))

        if password_checks:
            user_obj.password = generate_hashed_value(form.password.data)
            flask.g.session.add(user_obj)

        else:
            flask.flash(
                "Could not update your password, either user or password "
                "could not be checked",
                "error",
            )
            return flask.redirect(flask.url_for("auth_login"))

        try:
            flask.g.session.commit()
            flask.flash("Password changed")
        except SQLAlchemyError:  # pragma: no cover
            flask.g.session.rollback()
            flask.flash("Could not set the new password.", "error")
            _log.exception("Password change  - Error setting new password.")

        return flask.redirect(flask.url_for("auth_login"))

    return flask.render_template("login/password_recover.html", form=form)
Exemple #3
0
def change_password():
    """ Method to change the password for local auth users.
    """

    form = forms.ChangePasswordForm()
    user_obj = pagure.lib.search_user(
        SESSION, username=flask.g.fas_user.username)

    if not user_obj:
        flask.abort(404, 'User not found')

    if form.validate_on_submit():

        try:
            password_checks = check_password(
                form.old_password.data, user_obj.password,
                seed=APP.config.get('PASSWORD_SEED', None))
        except pagure.exceptions.PagureException as err:
            APP.logger.exception(err)
            flask.flash(
                'Could not update your password, either user or password '
                'could not be checked', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        if password_checks:
            user_obj.password = generate_hashed_value(form.password.data)
            SESSION.add(user_obj)

        else:
            flask.flash(
                'Could not update your password, either user or password '
                'could not be checked', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        try:
            SESSION.commit()
            flask.flash(
                'Password changed')
        except SQLAlchemyError as err:  # pragma: no cover
            SESSION.rollback()
            flask.flash('Could not set the new password.', 'error')
            APP.logger.debug(
                'Password change  - Error setting new password.')
            APP.logger.exception(err)

        return flask.redirect(flask.url_for('auth_login'))

    return flask.render_template(
        'login/password_recover.html',
        form=form,
    )
Exemple #4
0
def new_user():
    """ Create a new user.
    """
    form = forms.NewUserForm()
    if form.validate_on_submit():

        username = form.user.data
        if pagure.lib.query.search_user(flask.g.session, username=username):
            flask.flash("Username already taken.", "error")
            return flask.redirect(flask.request.url)

        email = form.email_address.data
        if pagure.lib.query.search_user(flask.g.session, email=email):
            flask.flash("Email address already taken.", "error")
            return flask.redirect(flask.request.url)

        form.password.data = generate_hashed_value(form.password.data)

        token = pagure.lib.login.id_generator(40)

        user = model.User()
        user.token = token
        form.populate_obj(obj=user)
        user.default_email = form.email_address.data
        flask.g.session.add(user)
        flask.g.session.flush()

        try:
            pagure.lib.query.add_email_to_user(
                flask.g.session, user, form.email_address.data
            )
            flask.g.session.commit()
            send_confirmation_email(user)
            flask.flash(
                "User created, please check your email to activate the "
                "account"
            )
        except pagure.exceptions.PagureException as err:
            flask.flash(str(err), "error")
            _log.exception(err)
        except SQLAlchemyError:  # pragma: no cover
            flask.g.session.rollback()
            flask.flash("Could not create user.")
            _log.exception("Could not create user.")

        return flask.redirect(flask.url_for("auth_login"))

    return flask.render_template("login/user_new.html", form=form)
Exemple #5
0
def reset_password(token):
    """ Method to allow a user to reset his/her password.
    """
    form = forms.ResetPasswordForm()

    user_obj = pagure.lib.search_user(SESSION, token=token)
    if not user_obj:
        flask.flash('No user associated with this token.', 'error')
        return flask.redirect(flask.url_for('auth_login'))
    elif not user_obj.token:
        flask.flash(
            'Invalid user, this user never asked for a password change',
            'error')
        return flask.redirect(flask.url_for('auth_login'))

    if form.validate_on_submit():

        user_obj.password = generate_hashed_value(form.password.data)

        user_obj.token = None
        SESSION.add(user_obj)

        try:
            SESSION.commit()
            flask.flash(
                'Password changed')
        except SQLAlchemyError as err:  # pragma: no cover
            SESSION.rollback()
            flask.flash('Could not set the new password.', 'error')
            APP.logger.debug(
                'Password lost change - Error setting password.')
            APP.logger.exception(err)

        return flask.redirect(flask.url_for('auth_login'))

    return flask.render_template(
        'login/password_reset.html',
        form=form,
        token=token,
    )
Exemple #6
0
def reset_password(token):
    """ Method to allow a user to reset his/her password.
    """
    form = forms.ResetPasswordForm()

    user_obj = pagure.lib.search_user(flask.g.session, token=token)
    if not user_obj:
        flask.flash('No user associated with this token.', 'error')
        return flask.redirect(flask.url_for('auth_login'))
    elif not user_obj.token:
        flask.flash(
            'Invalid user, this user never asked for a password change',
            'error')
        return flask.redirect(flask.url_for('auth_login'))

    if form.validate_on_submit():

        user_obj.password = generate_hashed_value(form.password.data)

        user_obj.token = None
        flask.g.session.add(user_obj)

        try:
            flask.g.session.commit()
            flask.flash('Password changed')
        except SQLAlchemyError:  # pragma: no cover
            flask.g.session.rollback()
            flask.flash('Could not set the new password.', 'error')
            _log.exception('Password lost change - Error setting password.')

        return flask.redirect(flask.url_for('auth_login'))

    return flask.render_template(
        'login/password_reset.html',
        form=form,
        token=token,
    )
Exemple #7
0
def reset_password(token):
    """ Method to allow a user to reset his/her password.
    """
    form = forms.ResetPasswordForm()

    user_obj = pagure.lib.query.search_user(flask.g.session, token=token)
    if not user_obj:
        flask.flash("No user associated with this token.", "error")
        return flask.redirect(flask.url_for("auth_login"))
    elif not user_obj.token:
        flask.flash(
            "Invalid user, this user never asked for a password change",
            "error",
        )
        return flask.redirect(flask.url_for("auth_login"))

    if form.validate_on_submit():

        user_obj.password = generate_hashed_value(form.password.data)

        user_obj.token = None
        flask.g.session.add(user_obj)

        try:
            flask.g.session.commit()
            flask.flash("Password changed")
        except SQLAlchemyError:  # pragma: no cover
            flask.g.session.rollback()
            flask.flash("Could not set the new password.", "error")
            _log.exception("Password lost change - Error setting password.")

        return flask.redirect(flask.url_for("auth_login"))

    return flask.render_template(
        "login/password_reset.html", form=form, token=token
    )
Exemple #8
0
def insert_data(session, username, user_email):
    _config['EMAIL_SEND'] = False
    _config['TESTING'] = True

    # Populate with default statuses
    create_default_status(session)
    print('Default statuses populated')

    ######################################
    # tags
    item = pagure.lib.model.Tag(tag='tag1', )
    session.add(item)
    session.commit()

    ######################################
    # Users
    # Create a couple of users
    pingou = item = pagure.lib.model.User(
        user='******',
        fullname='PY C',
        password=generate_hashed_value(u'testing123'),
        token=None,
        default_email='*****@*****.**',
    )
    session.add(item)
    session.commit()
    print("User created: {} <{}>, {}".format(item.user, item.default_email,
                                             'testing123'))

    foo = item = pagure.lib.model.User(
        user='******',
        fullname='foo bar',
        password=generate_hashed_value(u'testing123'),
        token=None,
        default_email='*****@*****.**',
    )
    session.add(item)
    session.commit()
    print("User created: {} <{}>, {}".format(item.user, item.default_email,
                                             'testing123'))

    you = item = pagure.lib.model.User(
        user=username,
        fullname=username,
        password=generate_hashed_value(u'testing123'),
        token=None,
        default_email=user_email,
    )
    session.add(item)
    session.commit()
    print("User created: {} <{}>, {}".format(item.user, item.default_email,
                                             'testing123'))

    ######################################
    # pagure_group
    item = pagure.lib.model.PagureGroup(
        group_name='admin',
        group_type='admin',
        user_id=pingou.id,
        display_name='admin',
        description='Admin Group',
    )
    session.add(item)
    session.commit()
    print('Created "admin" group. Pingou is a member.')

    # Add a couple of groups so that we can list them
    item = pagure.lib.model.PagureGroup(
        group_name='group',
        group_type='user',
        user_id=pingou.id,
        display_name='group group',
        description='this is a group group',
    )
    session.add(item)
    session.commit()
    print('Created "group" group. Pingou is a member.')

    item = pagure.lib.model.PagureGroup(
        group_name='rel-eng',
        group_type='user',
        user_id=pingou.id,
        display_name='Release Engineering',
        description='The group of release engineers',
    )
    session.add(item)
    session.commit()
    print('Created "rel-eng" group. Pingou is a member.')
    ######################################
    # projects

    import shutil
    # delete folder from local instance to start from a clean slate
    if os.path.exists(_config['GIT_FOLDER']):
        shutil.rmtree(_config['GIT_FOLDER'])

    # Create projects
    item = project1 = pagure.lib.model.Project(
        user_id=pingou.id,
        name='test',
        is_fork=False,
        parent_id=None,
        description='test project #1',
        hook_token='aaabbbccc',
    )
    item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate']
    session.add(item)
    session.flush()
    tests.create_locks(session, item)

    item = project2 = pagure.lib.model.Project(
        user_id=pingou.id,
        name='test2',
        is_fork=False,
        parent_id=None,
        description='test project #2',
        hook_token='aaabbbddd',
    )
    item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate']
    session.add(item)

    item = project3 = pagure.lib.model.Project(
        user_id=pingou.id,
        name='test3',
        is_fork=False,
        parent_id=None,
        description='namespaced test project',
        hook_token='aaabbbeee',
        namespace='somenamespace',
    )
    item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate']
    session.add(item)

    session.commit()

    tests.create_projects_git(_config['GIT_FOLDER'], bare=True)
    add_content_git_repo(os.path.join(_config['GIT_FOLDER'], 'test.git'))
    tests.add_readme_git_repo(os.path.join(_config['GIT_FOLDER'], 'test.git'))

    # Add some content to the git repo
    add_content_git_repo(
        os.path.join(_config['GIT_FOLDER'], 'forks', 'pingou', 'test.git'))
    tests.add_readme_git_repo(
        os.path.join(_config['GIT_FOLDER'], 'forks', 'pingou', 'test.git'))
    tests.add_commit_git_repo(os.path.join(_config['GIT_FOLDER'], 'forks',
                                           'pingou', 'test.git'),
                              ncommits=10)

    ######################################
    # user_emails
    item = pagure.lib.model.UserEmail(user_id=pingou.id,
                                      email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=pingou.id,
                                      email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=foo.id, email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=you.id, email=user_email)
    session.add(item)

    session.commit()

    ######################################
    # user_emails_pending
    email_pend = pagure.lib.model.UserEmailPending(
        user_id=pingou.id,
        email='[email protected]',
        token='abcdef',
    )
    session.add(email_pend)
    session.commit()

    ######################################
    # issues
    # Add an issue and tag it so that we can list them
    item = pagure.lib.model.Issue(
        id=1001,
        uid='foobar',
        project_id=project1.id,
        title='Problem with jenkins build',
        content='For some reason the tests fail at line:24',
        user_id=pingou.id,
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=1002,
        uid='foobar2',
        project_id=project1.id,
        title='Unit tests failing',
        content='Need to fix code for the unit tests to '
        'pass so jenkins build can complete.',
        user_id=pingou.id,
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=1003,
        uid='foobar3',
        project_id=project1.id,
        title='Segfault during execution',
        content='Index out of bounds for variable i?',
        user_id=you.id,
    )
    session.add(item)
    session.commit()

    ######################################
    # pagure_user_group
    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="rel-eng",
                                           group_type=None)
    item = pagure.lib.model.PagureUserGroup(user_id=pingou.id,
                                            group_id=group.id)
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="admin",
                                           group_type=None)

    item = pagure.lib.model.PagureUserGroup(user_id=you.id, group_id=group.id)
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="group",
                                           group_type=None)

    item = pagure.lib.model.PagureUserGroup(user_id=foo.id, group_id=group.id)
    session.add(item)
    session.commit()

    ######################################
    # projects_groups
    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="rel-eng",
                                           group_type=None)
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    item = pagure.lib.model.ProjectGroup(project_id=repo.id,
                                         group_id=group.id,
                                         access="commit")
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="admin",
                                           group_type=None)
    repo = pagure.lib.query.get_authorized_project(session, 'test2')
    item = pagure.lib.model.ProjectGroup(project_id=repo.id,
                                         group_id=group.id,
                                         access="admin")
    session.add(item)
    session.commit()

    ######################################
    # pull_requests
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    forked_repo = pagure.lib.query.get_authorized_project(session, 'test')
    req = pagure.lib.query.new_pull_request(session=session,
                                            repo_from=forked_repo,
                                            branch_from='master',
                                            repo_to=repo,
                                            branch_to='master',
                                            title='Fixing code for unittest',
                                            user=username)
    session.commit()

    ######################################
    # tokens
    tests.create_tokens(session, user_id=pingou.id, project_id=project1.id)

    ######################################
    # user_projects
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    item = pagure.lib.model.ProjectUser(project_id=repo.id,
                                        user_id=foo.id,
                                        access="commit")
    session.add(item)
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, 'test2')
    item = pagure.lib.model.ProjectUser(project_id=repo.id,
                                        user_id=you.id,
                                        access="commit")
    session.add(item)
    session.commit()

    ######################################
    # issue_comments
    item = pagure.lib.model.IssueComment(
        user_id=pingou.id,
        issue_uid='foobar',
        comment='We may need to adjust the unittests instead of the code.',
    )
    session.add(item)
    session.commit()

    ######################################
    # issue_to_issue
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    all_issues = pagure.lib.query.search_issues(session, repo)
    pagure.lib.query.add_issue_dependency(session, all_issues[0],
                                          all_issues[1], 'pingou')

    ######################################
    # pull_request_comments
    user = pagure.lib.query.search_user(session, username='******')
    # only 1 pull request available atm
    pr = pagure.lib.query.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestComment(
        pull_request_uid=pr.uid,
        user_id=user.id,
        comment="+1 for me. Btw, could you rebase before you merge?",
        notification=0)
    session.add(item)
    session.commit()

    ######################################
    # pull_request_flags
    # only 1 pull request available atm
    pr = pagure.lib.query.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestFlag(uid="random_pr_flag_uid",
                                            pull_request_uid=pr.uid,
                                            user_id=pingou.id,
                                            username=pingou.user,
                                            percent=80,
                                            comment="Jenkins build passes",
                                            url=str(pr.id),
                                            status="Open")
    session.add(item)
    session.commit()

    ######################################
    # tags_issues
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    issues = pagure.lib.query.search_issues(session, repo)
    item = pagure.lib.model.TagIssue(
        issue_uid=issues[0].uid,
        tag='tag1',
    )
    session.add(item)
    session.commit()

    ######################################
    # tokens_acls
    tests.create_tokens_acl(session)

    ######################################
    # Fork a project
    # delete fork data
    fork_proj_location = "forks/foo/test.git"
    try:
        shutil.rmtree(os.path.join(_config['GIT_FOLDER'], fork_proj_location))
    except:
        print('git folder already deleted')

    try:
        shutil.rmtree(os.path.join(_config['DOCS_FOLDER'], fork_proj_location))
    except:
        print('docs folder already deleted')

    try:
        shutil.rmtree(
            os.path.join(_config['TICKETS_FOLDER'], fork_proj_location))
    except:
        print('tickets folder already deleted')

    try:
        shutil.rmtree(
            os.path.join(_config['REQUESTS_FOLDER'], fork_proj_location))
    except:
        print('requests folder already deleted')

    repo = pagure.lib.query.get_authorized_project(session, 'test')
    result = pagure.lib.query.fork_project(session, 'foo', repo)
    if result == 'Repo "test" cloned to "foo/test"':
        session.commit()
Exemple #9
0
def do_login():
    """ Log the user in user.
    """
    form = forms.LoginForm()
    next_url = flask.request.args.get('next_url')
    if not next_url or next_url == 'None':
        next_url = flask.url_for('index')

    if form.validate_on_submit():
        username = form.username.data
        user_obj = pagure.lib.search_user(SESSION, username=username)
        if not user_obj:
            flask.flash('Username or password invalid.', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        try:
            password_checks = check_password(
                form.password.data, user_obj.password,
                seed=APP.config.get('PASSWORD_SEED', None))
        except pagure.exceptions.PagureException as err:
            APP.logger.exception(err)
            flask.flash('Username or password of invalid format.', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        if not password_checks:
            flask.flash('Username or password invalid.', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        elif user_obj.token:
            flask.flash(
                'Invalid user, did you confirm the creation with the url '
                'provided by email?', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        else:

            if not user_obj.password.startswith('$2$'):
                user_obj.password = generate_hashed_value(form.password.data)
                SESSION.add(user_obj)

            visit_key = pagure.lib.login.id_generator(40)
            now = datetime.datetime.utcnow()
            expiry = now + datetime.timedelta(days=30)
            session = model.PagureUserVisit(
                user_id=user_obj.id,
                user_ip=flask.request.remote_addr,
                visit_key=visit_key,
                expiry=expiry,
            )
            SESSION.add(session)
            try:
                SESSION.commit()
                flask.g.fas_user = user_obj
                flask.g.fas_session_id = visit_key
                flask.g.fas_user.login_time = now
                flask.flash('Welcome %s' % user_obj.username)
            except SQLAlchemyError as err:  # pragma: no cover
                flask.flash(
                    'Could not set the session in the db, '
                    'please report this error to an admin', 'error')
                APP.logger.exception(err)

        return flask.redirect(next_url)
    else:
        flask.flash('Insufficient information provided', 'error')
    return flask.redirect(flask.url_for('auth_login'))
Exemple #10
0
def do_login():
    """ Log in the user.
    """
    logout()

    form = forms.LoginForm()
    next_url = flask.request.form.get("next_url")
    if not next_url or next_url == "None":
        next_url = flask.url_for("ui_ns.index")

    if form.validate_on_submit():
        username = form.username.data
        user_obj = pagure.lib.query.search_user(flask.g.session,
                                                username=username)
        if not user_obj:
            flask.flash("Username or password invalid.", "error")
            return flask.redirect(flask.url_for("auth_login"))

        try:
            password_checks = check_password(
                form.password.data,
                user_obj.password,
                seed=pagure.config.config.get("PASSWORD_SEED", None),
            )
        except pagure.exceptions.PagureException as err:
            _log.exception(err)
            flask.flash("Username or password of invalid format.", "error")
            return flask.redirect(flask.url_for("auth_login"))

        if not password_checks:
            flask.flash("Username or password invalid.", "error")
            return flask.redirect(flask.url_for("auth_login"))

        elif user_obj.token:
            flask.flash(
                "Invalid user, did you confirm the creation with the url "
                "provided by email?",
                "error",
            )
            return flask.redirect(flask.url_for("auth_login"))

        else:
            password = user_obj.password
            if not isinstance(password, six.text_type):
                password = password.decode("utf-8")
            if not password.startswith("$2$"):
                user_obj.password = generate_hashed_value(form.password.data)
                flask.g.session.add(user_obj)
                flask.g.session.flush()

            visit_key = pagure.lib.login.id_generator(40)
            now = datetime.datetime.utcnow()
            expiry = now + datetime.timedelta(days=30)
            session = model.PagureUserVisit(
                user_id=user_obj.id,
                user_ip=flask.request.remote_addr,
                visit_key=visit_key,
                expiry=expiry,
            )
            flask.g.session.add(session)
            try:
                flask.g.session.commit()
                flask.g.fas_user = user_obj
                flask.g.fas_session_id = visit_key
                flask.g.fas_user.login_time = now
                flask.flash("Welcome %s" % user_obj.username)
            except SQLAlchemyError as err:  # pragma: no cover
                flask.flash(
                    "Could not set the session in the db, "
                    "please report this error to an admin",
                    "error",
                )
                _log.exception(err)

        return flask.redirect(next_url)
    else:
        flask.flash("Insufficient information provided", "error")
    return flask.redirect(flask.url_for("auth_login"))
Exemple #11
0
def do_login():
    """ Log in the user.
    """
    form = forms.LoginForm()
    next_url = flask.request.form.get('next_url')
    if not next_url or next_url == 'None':
        next_url = flask.url_for('index')

    if form.validate_on_submit():
        username = form.username.data
        user_obj = pagure.lib.search_user(SESSION, username=username)
        if not user_obj:
            flask.flash('Username or password invalid.', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        try:
            password_checks = check_password(form.password.data,
                                             user_obj.password,
                                             seed=APP.config.get(
                                                 'PASSWORD_SEED', None))
        except pagure.exceptions.PagureException as err:
            _log.exception(err)
            flask.flash('Username or password of invalid format.', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        if not password_checks:
            flask.flash('Username or password invalid.', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        elif user_obj.token:
            flask.flash(
                'Invalid user, did you confirm the creation with the url '
                'provided by email?', 'error')
            return flask.redirect(flask.url_for('auth_login'))

        else:

            if not user_obj.password.startswith('$2$'):
                user_obj.password = generate_hashed_value(form.password.data)
                SESSION.add(user_obj)

            visit_key = pagure.lib.login.id_generator(40)
            now = datetime.datetime.utcnow()
            expiry = now + datetime.timedelta(days=30)
            session = model.PagureUserVisit(
                user_id=user_obj.id,
                user_ip=flask.request.remote_addr,
                visit_key=visit_key,
                expiry=expiry,
            )
            SESSION.add(session)
            try:
                SESSION.commit()
                flask.g.fas_user = user_obj
                flask.g.fas_session_id = visit_key
                flask.g.fas_user.login_time = now
                flask.flash('Welcome %s' % user_obj.username)
            except SQLAlchemyError as err:  # pragma: no cover
                flask.flash(
                    'Could not set the session in the db, '
                    'please report this error to an admin', 'error')
                _log.exception(err)

        return flask.redirect(next_url)
    else:
        flask.flash('Insufficient information provided', 'error')
    return flask.redirect(flask.url_for('auth_login'))
Exemple #12
0
def insert_data(session, username, user_email):
    _config["EMAIL_SEND"] = False
    _config["TESTING"] = True

    ######################################
    # tags
    item = pagure.lib.model.Tag(tag="tag1")
    session.add(item)
    session.commit()

    ######################################
    # Users
    # Create a couple of users
    pingou = item = pagure.lib.model.User(
        user="******",
        fullname="PY C",
        password=generate_hashed_value("testing123"),
        token=None,
        default_email="*****@*****.**",
    )
    session.add(item)
    session.commit()
    print(
        "User created: {} <{}>, {}".format(
            item.user, item.default_email, "testing123"
        )
    )

    foo = item = pagure.lib.model.User(
        user="******",
        fullname="foo bar",
        password=generate_hashed_value("testing123"),
        token=None,
        default_email="*****@*****.**",
    )
    session.add(item)
    session.commit()
    print(
        "User created: {} <{}>, {}".format(
            item.user, item.default_email, "testing123"
        )
    )

    you = item = pagure.lib.model.User(
        user=username,
        fullname=username,
        password=generate_hashed_value("testing123"),
        token=None,
        default_email=user_email,
    )
    session.add(item)
    session.commit()
    print(
        "User created: {} <{}>, {}".format(
            item.user, item.default_email, "testing123"
        )
    )

    ######################################
    # pagure_group
    item = pagure.lib.model.PagureGroup(
        group_name="admin",
        group_type="admin",
        user_id=pingou.id,
        display_name="admin",
        description="Admin Group",
    )
    session.add(item)
    session.commit()
    print('Created "admin" group. Pingou is a member.')

    # Add a couple of groups so that we can list them
    item = pagure.lib.model.PagureGroup(
        group_name="group",
        group_type="user",
        user_id=pingou.id,
        display_name="group group",
        description="this is a group group",
    )
    session.add(item)
    session.commit()
    print('Created "group" group. Pingou is a member.')

    item = pagure.lib.model.PagureGroup(
        group_name="rel-eng",
        group_type="user",
        user_id=pingou.id,
        display_name="Release Engineering",
        description="The group of release engineers",
    )
    session.add(item)
    session.commit()
    print('Created "rel-eng" group. Pingou is a member.')
    ######################################
    # projects

    import shutil

    # delete folder from local instance to start from a clean slate
    if os.path.exists(_config["GIT_FOLDER"]):
        shutil.rmtree(_config["GIT_FOLDER"])

    # Create projects
    item = project1 = pagure.lib.model.Project(
        user_id=pingou.id,
        name="test",
        is_fork=False,
        parent_id=None,
        description="test project #1",
        hook_token="aaabbbccc",
    )
    item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
    session.add(item)
    session.flush()
    tests.create_locks(session, item)

    item = project2 = pagure.lib.model.Project(
        user_id=pingou.id,
        name="test2",
        is_fork=False,
        parent_id=None,
        description="test project #2",
        hook_token="aaabbbddd",
    )
    item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
    session.add(item)

    item = project3 = pagure.lib.model.Project(
        user_id=pingou.id,
        name="test3",
        is_fork=False,
        parent_id=None,
        description="namespaced test project",
        hook_token="aaabbbeee",
        namespace="somenamespace",
    )
    item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
    session.add(item)

    session.commit()

    tests.create_projects_git(_config["GIT_FOLDER"], bare=True)
    add_content_git_repo(os.path.join(_config["GIT_FOLDER"], "test.git"))
    tests.add_readme_git_repo(os.path.join(_config["GIT_FOLDER"], "test.git"))

    # Add some content to the git repo
    add_content_git_repo(
        os.path.join(_config["GIT_FOLDER"], "forks", "pingou", "test.git")
    )
    tests.add_readme_git_repo(
        os.path.join(_config["GIT_FOLDER"], "forks", "pingou", "test.git")
    )
    tests.add_commit_git_repo(
        os.path.join(_config["GIT_FOLDER"], "forks", "pingou", "test.git"),
        ncommits=10,
    )

    ######################################
    # user_emails
    item = pagure.lib.model.UserEmail(
        user_id=pingou.id, email="*****@*****.**"
    )
    session.add(item)

    item = pagure.lib.model.UserEmail(
        user_id=pingou.id, email="*****@*****.**"
    )
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=foo.id, email="*****@*****.**")
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=you.id, email=user_email)
    session.add(item)

    session.commit()

    ######################################
    # user_emails_pending
    email_pend = pagure.lib.model.UserEmailPending(
        user_id=pingou.id, email="[email protected]", token="abcdef"
    )
    session.add(email_pend)
    session.commit()

    ######################################
    # issues
    # Add an issue and tag it so that we can list them
    item = pagure.lib.model.Issue(
        id=1001,
        uid="foobar",
        project_id=project1.id,
        title="Problem with jenkins build",
        content="For some reason the tests fail at line:24",
        user_id=pingou.id,
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=1002,
        uid="foobar2",
        project_id=project1.id,
        title="Unit tests failing",
        content="Need to fix code for the unit tests to "
        "pass so jenkins build can complete.",
        user_id=pingou.id,
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=1003,
        uid="foobar3",
        project_id=project1.id,
        title="Segfault during execution",
        content="Index out of bounds for variable i?",
        user_id=you.id,
    )
    session.add(item)
    session.commit()

    ######################################
    # pagure_user_group
    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="rel-eng", group_type=None
    )
    item = pagure.lib.model.PagureUserGroup(
        user_id=pingou.id, group_id=group.id
    )
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="admin", group_type=None
    )

    item = pagure.lib.model.PagureUserGroup(user_id=you.id, group_id=group.id)
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="group", group_type=None
    )

    item = pagure.lib.model.PagureUserGroup(user_id=foo.id, group_id=group.id)
    session.add(item)
    session.commit()

    ######################################
    # projects_groups
    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="rel-eng", group_type=None
    )
    repo = pagure.lib.query.get_authorized_project(session, "test")
    item = pagure.lib.model.ProjectGroup(
        project_id=repo.id, group_id=group.id, access="commit"
    )
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="admin", group_type=None
    )
    repo = pagure.lib.query.get_authorized_project(session, "test2")
    item = pagure.lib.model.ProjectGroup(
        project_id=repo.id, group_id=group.id, access="admin"
    )
    session.add(item)
    session.commit()

    ######################################
    # pull_requests
    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Fixing code for unittest",
        user=username,
        status="Open",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="add very nice README",
        user=username,
        status="Open",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Add README",
        user=username,
        status="Closed",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Fix some containers",
        user=username,
        status="Merged",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Fix pull request statuses",
        user=username,
        status="Closed",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Fixing UI of issue",
        user=username,
        status="Merged",
    )
    session.commit()

    #####################################
    # tokens
    tests.create_tokens(session, user_id=pingou.id, project_id=project1.id)

    ######################################
    # user_projects
    repo = pagure.lib.query.get_authorized_project(session, "test")
    item = pagure.lib.model.ProjectUser(
        project_id=repo.id, user_id=foo.id, access="commit"
    )
    session.add(item)
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test2")
    item = pagure.lib.model.ProjectUser(
        project_id=repo.id, user_id=you.id, access="commit"
    )
    session.add(item)
    session.commit()

    ######################################
    # issue_comments
    item = pagure.lib.model.IssueComment(
        user_id=pingou.id,
        issue_uid="foobar",
        comment="We may need to adjust the unittests instead of the code.",
    )
    session.add(item)
    session.commit()

    ######################################
    # issue_to_issue
    repo = pagure.lib.query.get_authorized_project(session, "test")
    all_issues = pagure.lib.query.search_issues(session, repo)
    pagure.lib.query.add_issue_dependency(
        session, all_issues[0], all_issues[1], "pingou"
    )

    ######################################
    # pull_request_comments
    user = pagure.lib.query.search_user(session, username="******")
    # only 1 pull request available atm
    pr = pagure.lib.query.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestComment(
        pull_request_uid=pr.uid,
        user_id=user.id,
        comment="+1 for me. Btw, could you rebase before you merge?",
        notification=0,
    )
    session.add(item)
    session.commit()

    ######################################
    # pull_request_flags
    # only 1 pull request available atm
    pr = pagure.lib.query.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestFlag(
        uid="random_pr_flag_uid",
        pull_request_uid=pr.uid,
        user_id=pingou.id,
        username=pingou.user,
        percent=80,
        comment="Jenkins build passes",
        url=str(pr.id),
        status="success",
    )
    session.add(item)
    session.commit()

    pr = pagure.lib.query.get_pull_request_of_user(session, "foo")[1]
    item = pagure.lib.model.PullRequestFlag(
        uid="oink oink uid",
        pull_request_uid=pr.uid,
        user_id=pingou.id,
        username=pingou.user,
        percent=80,
        comment="Jenkins does not pass",
        url=str(pr.id),
        status="failure",
    )
    session.add(item)
    session.commit()

    ######################################
    # pull_request_assignee
    pr = pagure.lib.query.search_pull_requests(session, requestid="1006")
    pr.assignee_id = pingou.id
    session.commit()

    pr = pagure.lib.query.search_pull_requests(session, requestid="1007")
    pr.assignee_id = you.id
    session.commit()

    pr = pagure.lib.query.search_pull_requests(session, requestid="1004")
    pr.assignee_id = foo.id
    session.commit()

    ######################################
    # tags_issues
    repo = pagure.lib.query.get_authorized_project(session, "test")
    issues = pagure.lib.query.search_issues(session, repo)
    item = pagure.lib.model.TagIssue(issue_uid=issues[0].uid, tag="tag1")
    session.add(item)
    session.commit()

    ######################################
    # tokens_acls
    tests.create_tokens_acl(session)

    ######################################
    # Fork a project
    # delete fork data
    fork_proj_location = "forks/foo/test.git"
    try:
        shutil.rmtree(os.path.join(_config["GIT_FOLDER"], fork_proj_location))
    except:
        print("git folder already deleted")

    try:
        shutil.rmtree(os.path.join(_config["DOCS_FOLDER"], fork_proj_location))
    except:
        print("docs folder already deleted")

    try:
        shutil.rmtree(
            os.path.join(_config["TICKETS_FOLDER"], fork_proj_location)
        )
    except:
        print("tickets folder already deleted")

    try:
        shutil.rmtree(
            os.path.join(_config["REQUESTS_FOLDER"], fork_proj_location)
        )
    except:
        print("requests folder already deleted")

    repo = pagure.lib.query.get_authorized_project(session, "test")
    result = pagure.lib.query.fork_project(session, "foo", repo)
    if result == 'Repo "test" cloned to "foo/test"':
        session.commit()
Exemple #13
0
def do_login():
    """ Log in the user.
    """
    logout()

    form = forms.LoginForm()
    next_url = flask.request.form.get("next_url")
    if not next_url or next_url == "None":
        next_url = flask.url_for("ui_ns.index")

    if form.validate_on_submit():
        username = form.username.data
        user_obj = pagure.lib.query.search_user(
            flask.g.session, username=username
        )
        if not user_obj:
            flask.flash("Username or password invalid.", "error")
            return flask.redirect(flask.url_for("auth_login"))

        try:
            password_checks = check_password(
                form.password.data,
                user_obj.password,
                seed=pagure.config.config.get("PASSWORD_SEED", None),
            )
        except pagure.exceptions.PagureException as err:
            _log.exception(err)
            flask.flash("Username or password of invalid format.", "error")
            return flask.redirect(flask.url_for("auth_login"))

        if not password_checks:
            flask.flash("Username or password invalid.", "error")
            return flask.redirect(flask.url_for("auth_login"))

        elif user_obj.token:
            flask.flash(
                "Invalid user, did you confirm the creation with the url "
                "provided by email?",
                "error",
            )
            return flask.redirect(flask.url_for("auth_login"))

        else:
            password = user_obj.password
            if not isinstance(password, six.text_type):
                password = password.decode("utf-8")
            if not password.startswith("$2$"):
                user_obj.password = generate_hashed_value(form.password.data)
                flask.g.session.add(user_obj)
                flask.g.session.flush()

            visit_key = pagure.lib.login.id_generator(40)
            now = datetime.datetime.utcnow()
            expiry = now + datetime.timedelta(days=30)
            session = model.PagureUserVisit(
                user_id=user_obj.id,
                user_ip=flask.request.remote_addr,
                visit_key=visit_key,
                expiry=expiry,
            )
            flask.g.session.add(session)
            try:
                flask.g.session.commit()
                flask.g.fas_user = user_obj
                flask.g.fas_session_id = visit_key
                flask.g.fas_user.login_time = now
                flask.flash("Welcome %s" % user_obj.username)
            except SQLAlchemyError as err:  # pragma: no cover
                flask.flash(
                    "Could not set the session in the db, "
                    "please report this error to an admin",
                    "error",
                )
                _log.exception(err)

        return flask.redirect(next_url)
    else:
        flask.flash("Insufficient information provided", "error")
    return flask.redirect(flask.url_for("auth_login"))