Exemplo n.º 1
0
def admin_users_edit(gen):
    user = User.query.filter_by(gen=gen).first()
    user.role = User.get_role(user)
    user.user_status = User.get_status(user)

    form = EditForm()
    form.role.default = user.user_role
    form.role.process(request.form)

    form.status.default = user.status
    form.status.process(request.form)

    if form.is_submitted():
        print("submitted")
        if form.validate():
            print("valid")
        print(form.errors)

    if form.validate_on_submit():
        if form.photo.data:
            form.photo.data.save(dir + '/app/static/img/photo/%s.png' % user.gen)
        form.save_user()
        return redirect(url_for("admin_users_list"))

    return render_template('admin/users/edit.html', user=user, form=form)
Exemplo n.º 2
0
def create_admin_user():
    session = db.session()
    admin = User('0000001', 'admin', 'admin', role.admin, status.active)
    user = User('0000002', 'user', 'user', role.user, status.active)
    session.add(admin)
    session.add(user)
    session.commit()
Exemplo n.º 3
0
def sync_edm(context, refresh=False):
    """
    Sync the users from the EDM onto the local Hudson
    """
    from app.modules.users.models import User

    User.edm_sync_all(refresh=refresh)
def init_users():
    with db.session.begin():
        root_user = User(username='******',
                         email='root@localhost',
                         password='******',
                         is_active=True,
                         is_regular_user=True,
                         is_admin=True)
        db.session.add(root_user)
        docs_user = User(username='******',
                         email='documentation@localhost',
                         password='******',
                         is_active=False)
        db.session.add(docs_user)
        regular_user = User(username='******',
                            email='user@localhost',
                            password='******',
                            is_active=True,
                            is_regular_user=True)
        db.session.add(regular_user)
        internal_user = User(username='******',
                             email='internal@localhost',
                             password='******',
                             is_active=True,
                             is_internal=True)
        db.session.add(internal_user)
    return root_user, docs_user, regular_user
Exemplo n.º 5
0
def admin_users_list():
    user_list = User.query.order_by(User.id)

    # Конвертирование ид роли и статуса в название
    users = []
    for item in user_list:
        item.role = User.get_role(item)
        item.user_status = User.get_status(item)
        users.append(item)

    return render_template('admin/users/list.html', user_list=users)
Exemplo n.º 6
0
def create_user(
    context,
    email,
    is_internal=False,
    is_admin=False,
    is_staff=False,
    is_active=True,
):
    """
    Create a new user.
    """
    from app.modules.users.models import User

    password = input('Enter password: ')

    new_user = User(
        password=password,
        email=email,
        is_internal=is_internal,
        is_admin=is_admin,
        is_staff=is_staff,
        is_active=is_active,
    )

    from app.extensions import db

    with db.session.begin():
        db.session.add(new_user)
Exemplo n.º 7
0
def create_oauth2_client(context, email, guid, secret, default_scopes=None):
    """
    Create a new OAuth2 Client associated with a given user (email).
    """
    from app.modules.users.models import User
    from app.modules.auth.models import OAuth2Client

    user = User.find(email=email)

    if user is None:
        raise Exception("User with email '%s' does not exist." % email)

    if default_scopes is None:
        from app.extensions.api import api_v1

        default_scopes = list(
            api_v1.authorizations['oauth2_password']['scopes'].keys())

    oauth2_client = OAuth2Client(
        guid=guid,
        secret=secret,
        user=user,
        default_scopes=default_scopes,
    )

    from app.extensions import db

    with db.session.begin():
        db.session.add(oauth2_client)
Exemplo n.º 8
0
    def get(self, target, path):
        params = {}
        params.update(request.args)
        params.update(request.form)

        request_func = current_app.edm.get_passthrough
        passthrough_kwargs = {'params': params}

        response = _request_passthrough(target, path, request_func,
                                        passthrough_kwargs)

        # private means cannot be read other than admin
        ####@edm_configuration.login_required(oauth_scopes=['configuration:write'])  TODO somehow need to *allow* private if has auth!!!
        data = response.json()
        if (response.ok and 'response' in data
                and 'private' in data['response']
                and data['response']['private']):
            abort(code=HTTPStatus.FORBIDDEN, message='unavailable')

        if path == '__bundle_setup':
            data = response.json()
            data['response']['configuration'][
                'site.adminUserInitialized'] = User.admin_user_initialized()
            return data

        return response
Exemplo n.º 9
0
def test_encounter_add_owner(db):

    from app.modules.users.models import User
    from app.modules.encounters.models import Encounter

    test_user = User(
        email='testuser@localhost',
        password='******',
        full_name='Gregor Samsa ',
    )

    test_encounter = Encounter(title='New Test Encounter A', )

    with db.session.begin():
        db.session.add(test_encounter)
        db.session.add(test_user)

    db.session.refresh(test_encounter)
    db.session.refresh(test_user)

    assert test_encounter.get_owner() is None

    # need to set up association object, but this works
    test_user.owned_encounters.append(test_encounter)

    with db.session.begin():
        db.session.add(test_encounter)
        db.session.add(test_user)

    db.session.refresh(test_encounter)
    db.session.refresh(test_user)

    assert test_encounter.get_owner() is not None
    assert test_encounter.get_owner().guid == test_user.guid
Exemplo n.º 10
0
def create_user(
        context,
        username,
        email,
        is_internal=False,
        is_admin=False,
        is_regular_user=True,
        is_active=True
    ):
    """
    Create a new user.
    """
    from app.modules.users.models import User

    password = input("Enter password: ")

    new_user = User(
        username=username,
        password=password,
        email=email,
        is_internal=is_internal,
        is_admin=is_admin,
        is_regular_user=is_regular_user,
        is_active=is_active
    )

    from app.extensions import db
    db.session.add(new_user)
    db.session.commit()
Exemplo n.º 11
0
def referral_login(email=None, password=None, remember=None, refer=None, *args, **kwargs):
    # pylint: disable=unused-argument

    """
    This endpoint is the landing page for the logged-in user
    """
    if email is None:
        email = request.form.get('email', None)
    if password is None:
        password = request.form.get('password', None)
    if remember is None:
        remember = request.form.get('remember', None)
        remember = remember in ['true', 'on']
    if refer is None:
        refer = flask.request.args.get('next', request.form.get('next', None))

    if refer in ['origin']:
        refer = request.referrer

    if refer is not None:
        if not _is_safe_url(refer):
            log.error('User gave insecure next URL: %r' % (refer,))
            refer = None

    failure_refer = 'frontend.home'

    user = User.find(email=email, password=password)

    redirect = _url_for(failure_refer)
    if user is not None:
        if True not in [user.in_alpha, user.in_beta, user.is_staff, user.is_admin]:
            log.warning(
                'User %r had a valid login, but is not a staff or beta member.',
            )
            redirect = _url_for(failure_refer)
        else:
            status = login_user(user, remember=remember)

            if status:
                # User logged in organically.
                log.info(
                    'Logged in User (remember = %s): %r'
                    % (
                        remember,
                        user,
                    )
                )
                create_session_oauth2_token()

                if refer is not None:
                    log.info('Sending user to requested next: %r' % (refer,))
                    redirect = refer
            else:
                log.warning('Username or password unrecognized.')
                redirect = _url_for(failure_refer)
    else:
        log.warning('Username or password unrecognized.')
        redirect = _url_for(failure_refer)

    return flask.redirect(redirect)
def setup():
    adminUser = User(email='*****@*****.**',
                     username='******',
                     first_name='Omni',
                     last_name='Potent',
                     password='******')

    db.session.add(adminUser)
    testUser = User(email='*****@*****.**',
                    username='******',
                    first_name='Chaos',
                    last_name='Monkey',
                    password='******')

    db.session.add(testUser)
    role = Role(name='Admin', description='All powerful')
    db.session.add(role)
    db.session.commit()
Exemplo n.º 13
0
def generate_user_instance(
    user_guid=None,
    email=None,
    password=None,
    full_name='First Middle Last',
    created=None,
    updated=None,
    is_active=True,
    is_staff=False,
    is_admin=False,
    is_internal=False,
    in_alpha=True,
):
    """
    Returns:
        user_instance (User) - an not committed to DB instance of a User model.
    """
    # pylint: disable=too-many-arguments
    from app.modules.users.models import User

    if user_guid is None:
        user_guid = uuid.uuid4()

    if email is None:
        email = '%s@localhost' % (email, )

    if password is None:
        password = security.generate_random(128)

    user_instance = User(
        guid=user_guid,
        full_name=full_name,
        password=password,
        email=email,
        created=created or datetime.now(),
        updated=updated or datetime.now(),
        is_active=is_active,
        is_staff=is_staff,
        is_admin=is_admin,
        is_internal=is_internal,
        in_alpha=in_alpha,
    )
    user_instance.password_secret = password
    return user_instance
def init_users():
    root_user = User(username='******',
                     email='root@localhost',
                     password='******',
                     is_active=True,
                     is_admin=True)
    db.session.add(root_user)
    docs_user = User(username='******',
                     email='documentation@localhost',
                     password='******',
                     is_active=False)
    db.session.add(docs_user)
    regular_user = User(username='******',
                        email='user@localhost',
                        password='******',
                        is_active=True)
    db.session.add(regular_user)
    db.session.commit()
    return root_user, docs_user, regular_user
Exemplo n.º 15
0
def init_users():
    from app.modules.users.models import User

    with db.session.begin():
        root_user = User(
            email='root@localhost',
            password='******',
            is_active=True,
            is_admin=True,
        )
        db.session.add(root_user)

        docs_user = User(
            email='documentation@localhost',
            password='******',
            is_active=True,
        )
        db.session.add(docs_user)

        staff_member = User(
            email='staff@localhost',
            password='******',
            is_active=True,
            is_staff=True,
        )
        db.session.add(staff_member)

        regular_user = User(
            email='test@localhost',
            password='******',
            is_active=True,
        )
        db.session.add(regular_user)

        internal_user = User(
            email='internal@localhost',
            password='******',
            is_active=True,
            is_internal=True,
        )
        db.session.add(internal_user)

    return docs_user
Exemplo n.º 16
0
def create_admin_user(email=None,
                      password=None,
                      repeat_password=None,
                      *args,
                      **kwargs):
    """
    This endpoint creates the initial admin user if none exists
    """
    message = None

    if User.admin_user_initialized():
        message = 'This function is disabled. Admin user exists.'
    else:
        log.info('Attempting to create first run admin user.')
        if email is None:
            email = request.form.get('email', None)
        if password is None:
            password = request.form.get('password', None)
        if repeat_password is None:
            repeat_password = request.form.get('repeat_password', None)

        if password == repeat_password:
            if None not in [email, password, repeat_password]:
                admin = User.ensure_user(
                    email,
                    password,
                    is_admin=True,
                    update=True,
                )
                if admin.is_admin:
                    message = 'Success creating startup admin user.'
                    # update configuration value for admin user created
                    return flask.redirect(_url_for('backend.home'))
                else:
                    message = 'We failed to create or update the user as an admin.'
            else:
                message = 'You must specify all fields.'
        else:
            message = 'The password fields do not match.'

    if message is not None:
        flash(message)
Exemplo n.º 17
0
    def post():
        exist_user = User.query.filter_by(email=request.json['email']).first()
        if exist_user:
            return {'message': {'email': 'EMAIL_IS_ALREADY_EXIST'}}, 400

        user = User(**request.json)
        db.session.add(user)
        db.session.commit()
        login_user(user)

        return {'message': 'signup ok'}
Exemplo n.º 18
0
def generate_user_instance(
        user_id=None,
        username="******",
        password=None,
        email=None,
        first_name="First Name",
        middle_name="Middle Name",
        last_name="Last Name",
        created=None,
        updated=None,
        is_active=True,
        is_readonly=False,
        is_admin=False
):
    """
    Returns:
        user_instance (User) - an not committed to DB instance of a User model.
    """
    # pylint: disable=too-many-arguments
    from app.modules.users.models import User
    if password is None:
        password = '******' % username
    user_instance = User(
        id=user_id,
        username=username,
        first_name=first_name,
        middle_name=middle_name,
        last_name=last_name,
        password=password,
        email=email or '*****@*****.**' % username,
        created=created or datetime.now(),
        updated=updated or datetime.now(),
        is_active=is_active,
        is_readonly=is_readonly,
        is_admin=is_admin,
    )
    user_instance.password_secret = password
    return user_instance
Exemplo n.º 19
0
def profile():
    try:
        m_users = User()
        m_user = current_user
        # html or Json response
        if request_wants_json():
            return jsonify(data=m_user)
        else:
            return render_template("users/show.html", user=m_user, app=app)

    except Exception, ex:
        print("------------ ERROR  ------------\n" + str(ex.message))
        flash(str(ex.message), category="warning")
        abort(404)
Exemplo n.º 20
0
    def _process_members(self, members):
        from app.modules.users.models import User

        for member in members:
            log.info('Adding Member ID %s' % (member.id, ))
            user, is_new = User.ensure_edm_obj(member.id)
            if user not in self.members:
                enrollment = OrganizationUserMembershipEnrollment(
                    organization=self,
                    user=user,
                )

                with db.session.begin():
                    self.user_membership_enrollments.append(enrollment)
Exemplo n.º 21
0
def create_submission_from_path(
    context,
    path,
    email,
    description=None,
):
    """
    Create a new submission via a local file or folder path.

    Command Line:
    > invoke app.submissions.create-submission-from-path --path tests/submissions/test-000/ --email [email protected]
    """
    from app.modules.users.models import User
    from app.modules.submissions.models import Submission, SubmissionMajorType
    from app.extensions import db
    import socket

    user = User.find(email=email)

    if user is None:
        raise Exception("User with email '%s' does not exist." % email)

    absolute_path = os.path.abspath(os.path.expanduser(path))
    print('Attempting to import path: %r' % (absolute_path, ))

    if not os.path.exists(path):
        raise IOError('The path %r does not exist.' % (absolute_path, ))

    with db.session.begin():
        args = {
            'owner_guid': user.guid,
            'major_type': SubmissionMajorType.filesystem,
            'description': description,
        }
        submission = Submission(**args)
        db.session.add(submission)

    db.session.refresh(submission)

    repo, project = submission.ensure_repository()

    submission.git_copy_path(absolute_path)

    hostname = socket.gethostname()
    submission.git_commit('Initial commit via CLI on host %r' % (hostname, ))

    submission.git_push()

    print('Created and pushed new submission: %r' % (submission, ))
def flask_app():
    app = create_app(config_name='testing')
    from app import db

    with app.app_context():
        db.create_all()
        user = User(email='*****@*****.**',
                    username='******',
                    first_name='Chaos',
                    last_name='Monkey',
                    password='******')
        db.session.add(user)
        role = Role(name='Admin', description='All powerful')
        db.session.add(role)
        db.session.commit()
        yield app
        db.drop_all()
Exemplo n.º 23
0
def register():
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        # TODO перенести в форму регистрации
        user = User(login=form.login.data,
                    gen=form.gen.data,
                    password=generate_password_hash(form.password.data))

        try:
            db.session.add(user)
            db.session.commit()
        except IntegrityError:
            return render_template("users/register.html",
                                   form=form,
                                   error=True)

        # Автологин после регистрации
        login_user(user)
        return redirect(url_for('index'))
    return render_template("users/register.html", form=form)
Exemplo n.º 24
0
def promote_to_admin(
    context,
    email,
):
    """
    Promote a given user (email) to administrator permissions
    """
    from app.modules.users.models import User

    user = User.find(email=email)

    if user is None:
        print("User with email '%s' does not exist." % email)
        print('\nNo updates applied.')
        return

    if user.is_admin:
        print('The given user is already an administrator:\n\t%r' % (user, ))
        print('\nNo updates applied.')
        return

    user.is_admin = True

    print('Found user:\n\t%r' % (user, ))
    answer = input(
        'Are you sure you want to promote the above found user to a site administrator? [Y / N]: '
    )
    answer = answer.strip().lower()

    if answer not in ['y', 'yes']:
        print('Confirmation failed.')
        print('\nNo updates applied.')

    from app.extensions import db

    with db.session.begin():
        db.session.merge(user)
    db.session.refresh(user)

    assert user.is_admin
    print('\nThe user was successfully promoted to an administrator.')
Exemplo n.º 25
0
    def post(self, args, team):
        """
        Add a new member to a team.
        """
        with api.commit_or_abort(
                default_error_message="Failed to update team details."
            ):
            user_id = args.pop('user_id')
            #user = User.query.get(user_id)
            user = User.objects(user_id=user_id).first()
            if user is None:
                abort(
                    code=HTTPStatus.NOT_FOUND,
                    message="User with id %d does not exist" % user_id
                )

            team_member = TeamMember(team=team, user=user, **args)
            team_member.save()
            #db.session.add(team_member)

        return team_member
Exemplo n.º 26
0
    def post(self, args):
        """
        Log-in via a new OAuth2 Session.
        """
        email = args['email']
        password = args['password']

        user = User.find(email=email, password=password)

        failure = None
        if user is not None:
            if True not in [
                    user.in_alpha, user.in_beta, user.is_staff, user.is_admin
            ]:
                failure = 'Account Not Authorized'
            else:
                status = login_user(user, remember=False)

                if status:
                    log.info('Logged in User via API: %r' % (user, ))
                    create_session_oauth2_token()
                else:
                    failure = 'Account Disabled'
        else:
            failure = 'Account Not Found'

        if failure is None:
            response = {
                'success': True,
                'message': 'Session Created',
            }
            code = HTTPStatus.OK
        else:
            response = {
                'success': False,
                'message': failure,
            }
            code = HTTPStatus.UNAUTHORIZED

        return response, code
Exemplo n.º 27
0
def login(*args, **kwargs):
    if request.method == 'GET':  # Note: it is critical to not have the action parameter on the form
        return '''
               Please log in to access your account
               <form method='POST'>
                <input type='text' name='email' id='email' placeholder='email'></input>
                <input type='password' name='pw' id='pw' placeholder='password'></input>
                <input type='submit' name='submit'></input>
               </form>
               '''

    email = request.form['email']
    user = User.query.get(email)
    if request.form['pw']:
        user = User.find_with_password(request.form['email'], request.form['pw'])
        flask_login.login_user(user)
        next = request.args.get("next")
        if next is None:
            next = 'auth/protected'
        return redirect(next)

    return 'Bad login'
Exemplo n.º 28
0
def clone_submission_from_gitlab(
    context,
    guid,
    email,
):
    """
    Clone an existing submission from the external GitLab submission archive

    Command Line:
    > invoke app.submissions.clone-submission-from-gitlab --guid 290950fb-49a8-496a-adf4-e925010f79ce --email [email protected]
    """
    from app.modules.users.models import User
    from app.modules.submissions.models import Submission

    user = User.find(email=email)

    if user is None:
        raise Exception("User with email '%s' does not exist." % email)

    from app import create_app

    app = create_app()
    submission = Submission.query.get(guid)

    if submission is not None:
        print('Submission is already cloned locally:\n\t%s' % (submission, ))
        app.sub.ensure_repository(submission)
        return

    submission = app.sub.ensure_submission(guid, owner=user)

    if submission is None:
        raise ValueError('Could not find submission in GitLab using GUID %r' %
                         (guid, ))

    print('Cloned submission from GitLab:')
    print('\tSubmission: %r' % (submission, ))
    print('\tLocal Path: %r' % (submission.get_absolute_path(), ))
def authorize(*args, **kwargs):
    # pylint: disable=unused-argument
    """
    This endpoint asks user if he grants access to his data to the requesting
    application.
    """
    # TODO: improve implementation. This implementation is broken because we
    # don't use cookies, so there is no session which client could carry on.
    # OAuth2 server should probably be deployed on a separate domain, so we
    # can implement a login page and store cookies with a session id.
    # ALTERNATIVELY, authorize page can be implemented as SPA (single page
    # application)
    from flask_login import login_user

    user = current_user()
    if request.method == 'GET':
        try:
            grant = oauth2.validate_consent_request(end_user=user)
        except OAuth2Error as error:
            return error.error
        return render_template('authorize.html', user=user, grant=grant)
    if not user and 'username' in request.form:
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.find_with_password(username, password)
        if user:
            login_user(user)

    if request.form['confirm']:
        grant_user = user
    else:
        grant_user = None
    with db.session.begin():
        response = oauth2.create_authorization_response(grant_user=grant_user)

    return response or None
Exemplo n.º 30
0
 def _usergetter(self, username, password, client, request):
     # pylint: disable=method-hidden,unused-argument
     # Avoid circular dependencies
     from app.modules.users.models import User
     return User.find_with_password(username, password)