Ejemplo n.º 1
0
def login(context, request):
    email = urllib.unquote(request.matchdict['email'])
    user = User.get(request.db_session, email)

    # non-admin users cannot check if another user has permissions on a
    # given instance
    if authenticated_userid(request) != email and \
        'admin' not in effective_principals(request):
        return generate_empty_response(HTTPForbidden(), request, 403)

    try:
        # the domain could be an alias. We need the instance domain
        domain = Alias.get(request.db_session,
                           request.params['domain'])\
                      .instance.domain

    except NoResultFound:
        domain = request.params['domain']

    except KeyError:
        log.error('No domain in request for users.login')
        return generate_empty_response(HTTPForbidden(), request, 403)

    instance = Instance.get_by_domain(request.db_session, domain)
    if not user.can_access(instance):
        log.error('%s cannot login on %s', email, domain)
        return generate_empty_response(HTTPForbidden(), request, 403)

    return user.to_dict()
Ejemplo n.º 2
0
def empty_instance_groups(context, request):
    domain = request.matchdict['domain']
    group = Group.get(request.db_session, domain)
    instance = Instance.get_by_domain(request.db_session, domain)
    instance.groups = [group]
    request.db_session.commit()
    raise HTTPNoContent()
Ejemplo n.º 3
0
def restore(context, request):

    # FIXME: re-enable when restore issues are sorted out
    raise NotImplementedError()

    domain = request.matchdict['domain']
    instance = Instance.get_by_domain(request.db_session, domain)
    archive = request.params.get('archive')
    archive_name = request.params.get('archive_name')

    if archive and archive_name:
        raise ParamsError('archive and archive_name are mutually exclusive')

    elif archive_name and not archive:
        raise ParamsError('missing both archive and archive name')

    elif archive:
        # TODO handle archive upload
        raise NotImplementedError()

    if not archive_name.endswith("tar.gz"):
        archive_name = "{}.tar.gz".format(archive_name)

    archives = Environment.settings['paths.archives']
    archive_path = os.path.join(archives, archive_name)
    if not os.path.exists(archive_path):
        raise ParamsError('{} is not a valid archive'.format(archive_name))

    return request.submit_task('instance.restore', id=instance.id,
                               archive_name=archive_name)
Ejemplo n.º 4
0
def update(context, request):
    domain = request.matchdict['domain']
    # prefer 404 upon 400, so try first to get the instance
    params = dict(request.params)
    params.pop('action', '')

    instance = Instance.get_by_domain(request.db_session, domain)
    if request.method == 'DELETE':
        taskname = 'instance.delete'
        params['archive'] = True if request.params.get('archive') else ''

    elif 'action' not in request.params:
        raise ParamsError('No action provided')

    elif request.params['action'] in ('enable', 'disable', 'reload', 'kill',
                                      'sentence', 'flush_cache', 'archive',
                                      'migrate', 'switch_environment',
                                      'rewrite', 'change_domain'):
        taskname = "instance.{}".format(request.params['action'])

    else:
        raise ParamsError('invalid action {}'.format(request.params['action']))

    try:
        if request.params['action'] == 'change_domain':
            check_domain_not_used(request, params['domain'])
    except KeyError:
        pass

    return request.submit_task(taskname, id=instance.id, **params)
Ejemplo n.º 5
0
def update(context, request):

    params = dict()
    domain = request.matchdict['domain']
    Alias.get(request.db_session, domain)

    try:
        if "destination" in request.params:
            params['instance_id'] = Instance.get_by_domain(
                                            request.db_session,
                                            request.params['destination']).id
        if "new_domain" in request.params:
            check_domain_not_used(request, request.params['new_domain'])
            params['new_domain'] = validate_hostname(
                                             request.params['new_domain'])

    except NoResultFound:
        raise ParamsError("No instance for domain {}"\
                          .format(request.params['destination']))

    if not params:
        raise ParamsError("Missing update fields")

    params['domain'] = domain
    return request.submit_task('alias.update', **params)
Ejemplo n.º 6
0
def instance_group_info(context, request):
    domain = request.matchdict['domain']
    group = request.matchdict['group']
    instance = Instance.get_by_domain(request.db_session, domain)
    if not group.name in (g.name for g in instance.groups):
        raise NoResultFound()

    return group.to_dict()
Ejemplo n.º 7
0
def allowed_users_for_instance(context, request):
    domain = request.matchdict['domain']
    instance = Instance.get_by_domain(request.db_session, domain)

    res = {}
    for user in User.all(request.db_session):
        if user.can_access(instance):
            res[user.email] = user.to_dict()

    return res
Ejemplo n.º 8
0
def create(context, request):
    try:
        domain = request.params['domain']
        now = datetime.datetime.now().strftime('%Y%m%d-%H.%M.%S')
        default_name = "{}-{}".format(domain, now)
        name = request.params.get('name', default_name)
        name.replace(":", ".")

    except KeyError as e:
        raise ParamsError(e)

    instance = Instance.get_by_domain(request.db_session, domain)
    return request.submit_task('instance.archive', id=instance.id,
                                name=name)
Ejemplo n.º 9
0
def remove_group_from_instance(context, request):
    domain = request.matchdict['domain']
    group_name = request.matchdict['group']
    instance = Instance.get_by_domain(request.db_session, domain)
    try:
        group = Group.get(request.db_session, group_name)

    except NoResultFound:
        raise HTTPNoContent()

    if group.name == domain:
        raise HTTPConflict(headers={'X-Request-Error': \
                            "group {} cannot be removed".format(group_name)})

    instance.groups = [g for g in instance.groups if g.name != group.name]
    request.db_session.commit()
    raise HTTPNoContent()
Ejemplo n.º 10
0
def create(context, request):
    try:
        domain = request.params['domain']
        instance = Instance.get_by_domain(request.db_session,
                                          request.params['destination'])
        check_domain_not_used(request, domain)

    except KeyError as e:
        raise ParamsError(e)

    except NoResultFound:
        raise ParamsError('No instance for domain {}'\
                        .format(request.params['destination']))

    else:
        params = dict(domain=domain, instance_id=instance.id)
        return request.submit_task('alias.create', **params)
Ejemplo n.º 11
0
def add_group_to_instance(context, request):
    domain = request.matchdict['domain']
    group_name = request.matchdict['group']
    instance = Instance.get_by_domain(request.db_session, domain)
    try:
        group = Group.get(request.db_session, group_name)

    except NoResultFound:
        raise HTTPPreconditionFailed(
                                headers={'X-Request-Error': 'No such group {}'\
                                                        .format(group_name)}
              )

    if group_name in (g.name for g in instance.groups):
        raise HTTPNoContent()

    instance.groups.append(group)
    request.db_session.commit()
    raise HTTPNoContent()
Ejemplo n.º 12
0
def set_instance_groups(context, request):
    domain = request.matchdict['domain']
    request_groups = set(request.params.getall('groups'))
    if domain not in request_groups:
        request_groups.add(domain)

    instance = Instance.get_by_domain(request.db_session, domain)
    groups = Group.search(
                request.db_session,
                filters=(Group.name.in_(request_groups), )
             )
    if len(groups) != len(request_groups):
        raise HTTPPreconditionFailed(
                headers={'X-Request-Error': 'Invalid groups {}'\
                                            .format(','.join(request_groups))})

    instance.groups = groups
    request.db_session.commit()
    raise HTTPNoContent()
Ejemplo n.º 13
0
def create(context, request):
    try:
        source = validate_hostname(request.params['source'])
        instance = Instance.get_by_domain(request.db_session,
                                        request.params['destination'])
        http_code = request.params.get('http_code', 301)
        target_path = request.params.get('target_path', '')

        check_domain_not_used(request, source)

    except KeyError as e:
        raise ParamsError(e)

    except NoResultFound:
        raise ParamsError('No instance for domain {}'\
                        .format(request.params['destination']))

    else:
        params = dict(source=source, instance_id=instance.id,
                      http_code=http_code, target_path=target_path)
        return request.submit_task('redirect.create', **params)
Ejemplo n.º 14
0
def deploy(context, request):
    try:
        params = dict(
            domain=request.params['domain'],
            owner_email=request.params['owner_email'],
            environment_name=request.params['environment_name'],
            technical_contact_email=request.params.get(
                                   'technical_contact_email',
                                   request.params['owner_email']),
            theme_name=request.params.get('theme_name'),
            default_language=request.params.get('default_language', u'it'),
            database_password=request.params.get('database_password'),
            enabled=True if request.params.get('enabled') else False,
            verbose=True if request.params.get('verbose') else False,
        )
        check_domain_not_used(request, params['domain'])
        params['domain'] = validate_hostname(params['domain'])
        # try to get the instance, as it MUST not exists
        Instance.get_by_domain(request.db_session, params['domain'])

    except KeyError as e:
        log.exception("Error validating params")
        raise ParamsError(e)

    except NoResultFound:
        # no instance found, validate relations.
        try:
            field = 'owner_email'
            cls = 'user'
            User.log.debug("Validating owner %s", params[field])
            owner = User.get(request.db_session, params[field])
            if not owner:
                raise NoResultFound()
            if params['technical_contact_email'] != params['owner_email']:
                field = 'technical_contact_email'
                User.log.debug("Validating contact %s", params[field])
                ctc = User.get(request.db_session, params[field])
                if not ctc:
                    raise NoResultFound()

            field = 'environment_name'
            cls = 'environment'
            Environment.log.debug("validating environment %s", params[field])
            env = Environment.get(request.db_session, params[field])
            if not env:
                raise NoResultFound()

            field = 'theme_name'
            cls = 'theme'
            if params[field]:
                Theme.log.debug("Validating theme %s", params[field])
                theme = Theme.get(request.db_session, params[field])
                if not theme:
                    raise NoResultFound()

        except NoResultFound:
            raise ParamsError('{} "{}" for {} not found'\
                              .format(cls.title(), params[field], field))

        else:
            log.info("Submitting task")
            # relations exists, submit tasks
            return request.submit_task('instance.deploy', **params)

    else:
        # found instance, conflict
        error = 'instance for domain {} already exists'\
                .format(params['domain'])
        raise HTTPConflict(headers={'X-Request-Error': error})
Ejemplo n.º 15
0
def list_instance_groups(context, request):
    domain = request.matchdict['domain']
    instance = Instance.get_by_domain(request.db_session, domain)
    return {g.name: g.to_dict() for g in instance.groups}
Ejemplo n.º 16
0
def info(context, request):
    domain = request.matchdict['domain']
    instance = Instance.get_by_domain(request.db_session, domain)
    return instance.to_dict(paths=True)