Пример #1
0
def do_registrar():
    """
    """
    _auth = Auth()
    if not _auth.is_login:
        errors = [] #errores 
        #validacion de campos vacios
        _username = request.forms.get('username')
        if _username == "":
            errors.append("El campo Usuario esta vacio")

        #validacion de contrasenias
        _password = request.forms.get('password')
        repassword = request.forms.get('repassword')
        if len(_password) < 8 or len(_password) >= 16:
            errors.append("la contrasenia debe tener entre 8 y 16 caracteres")
        if _password != repassword:
            errors.append("Las contrasenias no coinciden")

        _name = request.forms.get('name')
        if _name == "":
            errors.append("El campo Nombre esta vacio")
        
        _email = request.forms.get('email')
        if _email == "":
            errors.append("El campo Email esta vacio")

        if len(errors) == 0:
            #validacion de que no exista el usuario
            query = db.GqlQuery("SELECT * FROM User WHERE username = :1", _username)        
            if query.count() != 0:
                errors.append("El nombre de usuarios \"%s\" ya existe" %_username)
                form_error = True

            else:            
                user = User(
                    username = _username,
                    password = _password,
                    name = _name,
                    email = _email,
                )
                user.put()
                return template("auth/registrar-ok.html")

        else:
            form_error = True
        #si llego hasta aqui hay algun tipo de errors        
        data = {
            "errors" : errors,
            "form_error": form_error,
            "username": _username,
            "name": _name,
            "email": _email,
        }
        return template("auth/registrar.html", data)

    else:
        message = "Error ya has iniciado Session con la cuenta \"%s\" " %_auth.is_login()
        message += "en caso de querer proceder por fabor cierra la session actual."
        return template("message.html", {'message': message} )
Пример #2
0
def index():
    #pagina de inicio
    _auth = Auth() 
    if (_auth.is_login()):
        is_login = True
    else:
        is_login = False
    return template('home.html', {'is_login':is_login })
Пример #3
0
def listado():
    _auth = Auth()
    if _auth.is_login():
        data = {}
        user = db.GqlQuery("SELECT * FROM User WHERE username = :1", _auth.is_login()).fetch(1)[0]
        data['series'] = Serie.all().filter("user="******"series/listado.html", data)
    else:
        return template("sin-permisos.html")
Пример #4
0
def login():
    """
        Iniciar Session
    """
    _auth = Auth()
    if not _auth.is_login():
        return template('auth/login.html')
    else:
        message = "Error ya has iniciado Session con la cuenta \"%s\" " %_auth.is_login()
        message += "en caso de querer proceder por fabor cierra la session actual."
        return template("message.html", {'message': message} )
Пример #5
0
def do_login():
    """
        Captura los datos de la vista para iniciar session
    """
    _auth = Auth()
    usr = request.forms.get('username')
    pwd = request.forms.get('password')

    if _auth.login(usr, pwd):
        redirect('/')
    else:
        return template('auth/login.html', {"login_error": True})
Пример #6
0
def do_registrar():
    _auth = Auth()
    if _auth.is_login():
        #field validation
        _name = request.forms.get('name')
        _day = request.forms.get('day')
        _url = request.forms.get('url')
        _chapter_url = request.forms.get('chapter_url')
        _num_chapters = request.forms.get('mun_chapters')
        _old_chapter = request.forms.get('old_chapter')

        #el usuario existe se supone que esta logueado sino cagada jaaj
        _user = db.GqlQuery("SELECT * FROM User WHERE username = :1", _auth.is_login()).fetch(1)[0]
        
        if _num_chapters <= _old_chapter:
            _old_chapter = _num_chapters
            _enabled = False
        else:
            _enabled = True

        serie = Serie(
            user = _user,
            name = _name,
            day = _day,
            url = _url,
            chapter_url = _chapter_url,
            num_chapters = int(_num_chapters),
            old_chapter = int(_old_chapter), #ultimo capitulo que salio    
            enabled = _enabled
        )
        serie.put()
       
        # Registro los capitulos
        n = int(_old_chapter) + 1
        for num in range(1, n):
            chapter = Chapter(
                serie = serie,
                number = num,
                url = serie.chapter_url %num,
                show = False
            )
            chapter.put()

        return "Serie Registrada"

        #return template("series/registrar.html")
    else:
        return template("sin-permisos.html")
Пример #7
0
 def test_from_kwargs(self):
     user = UserFactory()
     request_args = {'view_only': 'mykey'}
     kwargs = {'user': user}
     auth_obj = Auth.from_kwargs(request_args, kwargs)
     assert_equal(auth_obj.user, user)
     assert_equal(auth_obj.private_key, request_args['view_only'])
Пример #8
0
        def wrapped(*args, **kwargs):
            response = None
            kwargs['project'], kwargs['node'] = _kwargs_to_nodes(kwargs)
            node = kwargs['node'] or kwargs['project']

            kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)
            user = kwargs['auth'].user

            if 'api_node' in kwargs:
                api_node = kwargs['api_node']
            else:
                api_node = get_api_key()
                kwargs['api_node'] = api_node

            key = request.args.get('view_only', '').strip('/')
            #if not login user check if the key is valid or the other privilege

            kwargs['auth'].private_key = key
            if not node.is_public or not include_public:
                if key not in node.private_link_keys_active:
                    if not check_can_access(node=node, user=user,
                            api_node=api_node, key=key):
                        url = '/login/?next={0}'.format(request.path)
                        redirect_url = check_key_expired(key=key, node=node, url=url)
                        response = redirect(redirect_url)

            return response or func(*args, **kwargs)
Пример #9
0
        def wrapped(*args, **kwargs):
            response = None
            _inject_nodes(kwargs)
            node = kwargs['node']

            kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)
            user = kwargs['auth'].user

            key = request.args.get('view_only', '').strip('/')
            #if not login user check if the key is valid or the other privilege

            kwargs['auth'].private_key = key
            link_anon = None
            if not include_view_only_anon:
                from website.models import PrivateLink
                try:
                    link_anon = PrivateLink.find_one(Q('key', 'eq', key)).anonymous
                except ModularOdmException:
                    pass

            if not node.is_public or not include_public:
                if not include_view_only_anon and link_anon:
                    if not check_can_access(node=node, user=user):
                        raise HTTPError(http.UNAUTHORIZED)
                elif key not in node.private_link_keys_active:
                    if not check_can_access(node=node, user=user, key=key):
                        redirect_url = check_key_expired(key=key, node=node, url=request.url)
                        if request.headers.get('Content-Type') == 'application/json':
                            raise HTTPError(http.UNAUTHORIZED)
                        else:
                            response = redirect(cas.get_login_url(redirect_url))

            return response or func(*args, **kwargs)
Пример #10
0
        def wrapped(*args, **kwargs):
            _inject_nodes(kwargs)

            kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)

            response = check_contributor_auth(kwargs['node'], kwargs['auth'], include_public, include_view_only_anon)

            return response or func(*args, **kwargs)
Пример #11
0
        def wrapped(*args, **kwargs):
            response = None
            target = None
            guid = Guid.load(kwargs.get('guid'))
            if guid:
                target = getattr(guid, 'referent', None)
            else:
                _inject_nodes(kwargs)

            target = target or kwargs.get('node')

            kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)

            response = check_contributor_auth(target, kwargs['auth'], include_public, include_view_only_anon)

            return response or func(*args, **kwargs)
Пример #12
0
        def wrapped(*args, **kwargs):
            # Ensure `project` and `node` kwargs
            _inject_nodes(kwargs)
            node = kwargs["node"]

            kwargs["auth"] = Auth.from_kwargs(request.args.to_dict(), kwargs)
            user = kwargs["auth"].user

            # User must be logged in
            if user is None:
                raise HTTPError(http.UNAUTHORIZED)

            # User must have permissions
            if not node.has_permission(user, permission):
                raise HTTPError(http.FORBIDDEN)

            # Call view function
            return func(*args, **kwargs)
Пример #13
0
        def wrapped(*args, **kwargs):
            response = None
            _inject_nodes(kwargs)
            node = kwargs['node']

            kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)
            user = kwargs['auth'].user

            key = request.args.get('view_only', '').strip('/')
            #if not login user check if the key is valid or the other privilege

            kwargs['auth'].private_key = key
            if not node.is_public or not include_public:
                if key not in node.private_link_keys_active:
                    if not check_can_access(node=node, user=user, key=key):
                        redirect_url = check_key_expired(key=key, node=node, url=request.url)
                        response = redirect(cas.get_login_url(redirect_url))

            return response or func(*args, **kwargs)
Пример #14
0
        def wrapped(*args, **kwargs):
            # Ensure `project` and `node` kwargs
            if kwargs.get('nid') or kwargs.get('pid'):
                _inject_nodes(kwargs)
            target = kwargs.get('node') or getattr(Guid.load(kwargs.get('guid')), 'referent', None)

            kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)
            user = kwargs['auth'].user

            # User must be logged in
            if user is None:
                raise HTTPError(http.UNAUTHORIZED)

            # User must have permissions
            if not target.has_permission(user, permission):
                raise HTTPError(http.FORBIDDEN)

            # Call view function
            return func(*args, **kwargs)
Пример #15
0
def _view_registries_landing_page(campaign=None, **kwargs):
    """Landing page for the various registrations"""
    auth = kwargs['auth'] = Auth.from_kwargs(request.args.to_dict(), kwargs)
    is_logged_in = kwargs['auth'].logged_in
    if is_logged_in:
        registerable_nodes = [
            node for node
            in auth.user.contributor_to
            if node.has_permission(user=auth.user, permission='admin')
        ]
        has_projects = bool(registerable_nodes)
    else:
        has_projects = False

    return {
        'is_logged_in': is_logged_in,
        'has_draft_registrations': bool(utils.drafts_for_user(auth.user, campaign)),
        'has_projects': has_projects,
        'campaign_long': utils.REG_CAMPAIGNS.get(campaign),
        'campaign_short': campaign

    }
Пример #16
0
        def wrapped(*args, **kwargs):
            response = None
            _inject_nodes(kwargs)
            node = kwargs["node"]

            kwargs["auth"] = Auth.from_kwargs(request.args.to_dict(), kwargs)
            user = kwargs["auth"].user

            key = request.args.get("view_only", "").strip("/")
            # if not login user check if the key is valid or the other privilege

            kwargs["auth"].private_key = key
            if not node.is_public or not include_public:
                if key not in node.private_link_keys_active:
                    if not check_can_access(node=node, user=user, key=key):
                        redirect_url = check_key_expired(key=key, node=node, url=request.url)
                        if request.headers.get("Content-Type") == "application/json":
                            raise HTTPError(http.UNAUTHORIZED)
                        else:
                            response = redirect(cas.get_login_url(redirect_url))

            return response or func(*args, **kwargs)
Пример #17
0
 def test_must_be_logged_in_decorator_with_user(self, mock_from_kwargs):
     user = UserFactory()
     mock_from_kwargs.return_value = Auth(user=user)
     protected()
Пример #18
0
def analyze_failed_registration_nodes():
    """ If we can just retry the archive, but we can only do that if the
    ORIGINAL node hasn't changed.
    """
    # Get the registrations that are messed up
    failed_registration_nodes = find_failed_registrations()

    # Build up a list of dictionaries with info about these failed nodes
    failed_registration_info = []
    for broken_registration in failed_registration_nodes:
        unacceptable_node_logs_after_date = list(
            broken_registration.registered_from.get_aggregate_logs_queryset(
                Auth(broken_registration.registered_from.creator)).filter(
                    date__gt=broken_registration.registered_date).exclude(
                        action__in=fa.LOG_WHITELIST).exclude(
                            action__in=fa.LOG_GREYLIST).values_list('action',
                                                                    flat=True))

        # Does it have any addons?
        addon_list = [
            addon for addon in ADDONS_REQUESTED
            if broken_registration.registered_from.has_addon(addon)
            and addon not in {'osfstorage', 'wiki'}
        ]
        has_addons = bool(addon_list)

        # Any registrations succeeded after the stuck one?
        # Not sure why broken_registration.registered_from.registrations was always 0 locally...
        succeeded_registrations_after_failed = []
        for other_reg in Registration.find(
                Q('registered_from', 'eq', broken_registration.registered_from)
                & Q('registered_date', 'gt',
                    broken_registration.registered_date)):
            if other_reg.sanction:
                if other_reg.sanction.is_approved:
                    succeeded_registrations_after_failed.append(other_reg._id)
            else:
                succeeded_registrations_after_failed.append(other_reg._id)

        can_be_reset = fa.verify(broken_registration)
        logger.info('Found broken registration {}'.format(
            broken_registration._id))
        failed_registration_info.append({
            'registration':
            broken_registration._id,
            'registered_date':
            broken_registration.registered_date,
            'original_node':
            broken_registration.registered_from._id,
            'logs_on_original_after_registration_date':
            unacceptable_node_logs_after_date,
            'has_addons':
            has_addons,
            'addon_list':
            addon_list,
            'succeeded_registrations_after_failed':
            succeeded_registrations_after_failed,
            'can_be_reset':
            can_be_reset,
            'registered_from_public':
            broken_registration.registered_from.is_public,
        })

    return failed_registration_info
Пример #19
0
 def after_delete(self, node, user):
     self.deauthorize(Auth(user=user), add_log=True)
     self.save()
Пример #20
0
def registrar():
    _auth = Auth()
    if _auth.is_login():
        return template("series/registrar.html")
    else:
        return template("sin-permisos.html")
Пример #21
0
 def test_serialize_node_summary_for_registration_uses_correct_date_format(
         self):
     reg = RegistrationFactory()
     res = serialize_node_summary(reg, auth=Auth(reg.creator))
     assert_equal(res['registered_date'],
                  reg.registered_date.strftime('%Y-%m-%d %H:%M UTC'))
Пример #22
0
def debug():
    """
        Vista Para Pruebas
    """
    a = Auth()
    return str(a.is_login()),'-', str(a.is_admin())
Пример #23
0
 def test_after_delete(self):
     self.project.remove_node(Auth(user=self.project.creator))
     # Ensure that changes to node settings have been saved
     self.node_settings.reload()
     assert_true(self.node_settings.user_settings is None)
     assert_true(self.node_settings.folder is None)
Пример #24
0
def resolve_guid(guid, suffix=None):
    """Load GUID by primary key, look up the corresponding view function in the
    routing table, and return the return value of the view function without
    changing the URL.

    :param str guid: GUID primary key
    :param str suffix: Remainder of URL after the GUID
    :return: Return value of proxied view function
    """
    try:
        # Look up
        guid_object = Guid.load(guid)
    except KeyError as e:
        if e.message == 'osfstorageguidfile':  # Used when an old detached OsfStorageGuidFile object is accessed
            raise HTTPError(http.NOT_FOUND)
        else:
            raise e
    if guid_object:
        # verify that the object implements a GuidStoredObject-like interface. If a model
        #   was once GuidStoredObject-like but that relationship has changed, it's
        #   possible to have referents that are instances of classes that don't
        #   have a deep_url attribute or otherwise don't behave as
        #   expected.
        if not hasattr(guid_object.referent, 'deep_url'):
            sentry.log_message(
                'Guid resolved to an object with no deep_url', dict(guid=guid)
            )
            raise HTTPError(http.NOT_FOUND)
        referent = guid_object.referent
        if referent is None:
            logger.error('Referent of GUID {0} not found'.format(guid))
            raise HTTPError(http.NOT_FOUND)
        if not referent.deep_url:
            raise HTTPError(http.NOT_FOUND)

        # Handle file `/download` shortcut with supported types.
        if suffix and suffix.rstrip('/').lower() == 'download':
            file_referent = None
            if isinstance(referent, PreprintService) and referent.primary_file:
                if not referent.is_published:
                    # TODO: Ideally, permissions wouldn't be checked here.
                    # This is necessary to prevent a logical inconsistency with
                    # the routing scheme - if a preprint is not published, only
                    # admins and moderators should be able to know it exists.
                    auth = Auth.from_kwargs(request.args.to_dict(), {})
                    group_helper = GroupHelper(referent.provider)
                    admin_group = group_helper.get_group('admin')
                    mod_group = group_helper.get_group('moderator')
                    # Check if user isn't a nonetype or that the user has admin/moderator permissions
                    if auth.user is None or not (referent.node.has_permission(auth.user, permissions.ADMIN) or (mod_group.user_set.all() | admin_group.user_set.all()).filter(id=auth.user.id).exists()):
                        raise HTTPError(http.NOT_FOUND)
                file_referent = referent.primary_file
            elif isinstance(referent, BaseFileNode) and referent.is_file:
                file_referent = referent

            if file_referent:
                # Extend `request.args` adding `action=download`.
                request.args = request.args.copy()
                request.args.update({'action': 'download'})
                # Do not include the `download` suffix in the url rebuild.
                url = _build_guid_url(urllib.unquote(file_referent.deep_url))
                return proxy_url(url)

        # Handle Ember Applications
        if isinstance(referent, PreprintService):
            if referent.provider.domain_redirect_enabled:
                # This route should always be intercepted by nginx for the branded domain,
                # w/ the exception of `<guid>/download` handled above.
                return redirect(referent.absolute_url, http.MOVED_PERMANENTLY)

            if PROXY_EMBER_APPS:
                resp = requests.get(EXTERNAL_EMBER_APPS['preprints']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT)
                return Response(stream_with_context(resp.iter_content()), resp.status_code)

            return send_from_directory(preprints_dir, 'index.html')

        if isinstance(referent, BaseFileNode) and referent.is_file and referent.node.is_quickfiles:
            if referent.is_deleted:
                raise HTTPError(http.GONE)
            if PROXY_EMBER_APPS:
                resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT)
                return Response(stream_with_context(resp.iter_content()), resp.status_code)

            return send_from_directory(ember_osf_web_dir, 'index.html')

        if isinstance(referent, Node) and not referent.is_registration and suffix:
            page = suffix.strip('/').split('/')[0]
            flag_name = 'ember_project_{}_page'.format(page)
            request.user = _get_current_user() or MockUser()

            if waffle.flag_is_active(request, flag_name):
                use_ember_app()

        url = _build_guid_url(urllib.unquote(referent.deep_url), suffix)
        return proxy_url(url)

    # GUID not found; try lower-cased and redirect if exists
    guid_object_lower = Guid.load(guid.lower())
    if guid_object_lower:
        return redirect(
            _build_guid_url(guid.lower(), suffix)
        )

    # GUID not found
    raise HTTPError(http.NOT_FOUND)
Пример #25
0
 def test_must_have_addon_user_true(self, mock_current_user):
     mock_current_user.return_value = Auth(self.project.creator)
     self.project.creator.add_addon('github')
     decorated = must_have_addon('github', 'user')(needs_addon_view)
     res = decorated()
     assert_equal(res, 'openaddon')
Пример #26
0
 def test_logged_in(self):
     user = UserFactory()
     auth_obj = Auth(user=user)
     assert_true(auth_obj.logged_in)
     auth2 = Auth(user=None)
     assert_false(auth2.logged_in)
Пример #27
0
 def test_after_delete(self):
     self.node.remove_node(Auth(user=self.node.creator))
     # Ensure that changes to node settings have been saved
     self.node_settings.reload()
     assert_is_none(self.node_settings.user_settings)
     assert_is_none(self.node_settings.folder_id)
Пример #28
0
def resolve_guid(guid, suffix=None):
    """Load GUID by primary key, look up the corresponding view function in the
    routing table, and return the return value of the view function without
    changing the URL.

    :param str guid: GUID primary key
    :param str suffix: Remainder of URL after the GUID
    :return: Return value of proxied view function
    """
    try:
        # Look up
        guid_object = Guid.load(guid)
    except KeyError as e:
        if e.message == 'osfstorageguidfile':  # Used when an old detached OsfStorageGuidFile object is accessed
            raise HTTPError(http.NOT_FOUND)
        else:
            raise e
    if guid_object:
        # verify that the object implements a GuidStoredObject-like interface. If a model
        #   was once GuidStoredObject-like but that relationship has changed, it's
        #   possible to have referents that are instances of classes that don't
        #   have a deep_url attribute or otherwise don't behave as
        #   expected.
        if not hasattr(guid_object.referent, 'deep_url'):
            sentry.log_message(
                'Guid resolved to an object with no deep_url', dict(guid=guid)
            )
            raise HTTPError(http.NOT_FOUND)
        referent = guid_object.referent
        if referent is None:
            logger.error('Referent of GUID {0} not found'.format(guid))
            raise HTTPError(http.NOT_FOUND)
        if not referent.deep_url:
            raise HTTPError(http.NOT_FOUND)

        # Handle file `/download` shortcut with supported types.
        if suffix and suffix.rstrip('/').lower() == 'download':
            file_referent = None
            if isinstance(referent, PreprintService) and referent.primary_file:
                if not referent.is_published:
                    # TODO: Ideally, permissions wouldn't be checked here.
                    # This is necessary to prevent a logical inconsistency with
                    # the routing scheme - if a preprint is not published, only
                    # admins should be able to know it exists.
                    auth = Auth.from_kwargs(request.args.to_dict(), {})
                    if not referent.node.has_permission(auth.user, permissions.ADMIN):
                        raise HTTPError(http.NOT_FOUND)
                file_referent = referent.primary_file
            elif isinstance(referent, BaseFileNode) and referent.is_file:
                file_referent = referent

            if file_referent:
                # Extend `request.args` adding `action=download`.
                request.args = request.args.copy()
                request.args.update({'action': 'download'})
                # Do not include the `download` suffix in the url rebuild.
                url = _build_guid_url(urllib.unquote(file_referent.deep_url))
                return proxy_url(url)

        # Handle Ember Applications
        if isinstance(referent, PreprintService):
            if referent.provider.domain_redirect_enabled:
                # This route should always be intercepted by nginx for the branded domain,
                # w/ the exception of `<guid>/download` handled above.
                return redirect(referent.absolute_url, http.MOVED_PERMANENTLY)

            return send_from_directory(preprints_dir, 'index.html')
        url = _build_guid_url(urllib.unquote(referent.deep_url), suffix)
        return proxy_url(url)

    # GUID not found; try lower-cased and redirect if exists
    guid_object_lower = Guid.load(guid.lower())
    if guid_object_lower:
        return redirect(
            _build_guid_url(guid.lower(), suffix)
        )

    # GUID not found
    raise HTTPError(http.NOT_FOUND)
Пример #29
0
 def setUp(self):
     super(TestValidProject, self).setUp()
     self.project = ProjectFactory()
     self.node = NodeFactory()
     self.auth = Auth(user=self.project.creator)
Пример #30
0
def create_waterbutler_log(payload, **kwargs):
    with TokuTransaction():
        try:
            auth = payload['auth']
            action = LOG_ACTION_MAP[payload['action']]
        except KeyError:
            raise HTTPError(httplib.BAD_REQUEST)

        user = User.load(auth['id'])
        if user is None:
            raise HTTPError(httplib.BAD_REQUEST)

        auth = Auth(user=user)
        node = kwargs['node'] or kwargs['project']

        if action in (NodeLog.FILE_MOVED, NodeLog.FILE_COPIED):

            for bundle in ('source', 'destination'):
                for key in ('provider', 'materialized', 'name', 'nid'):
                    if key not in payload[bundle]:
                        raise HTTPError(httplib.BAD_REQUEST)

            dest = payload['destination']
            src = payload['source']

            if src is not None and dest is not None:
                dest_path = dest['materialized']
                src_path = src['materialized']
                if dest_path.endswith('/') and src_path.endswith('/'):
                    dest_path = os.path.dirname(dest_path)
                    src_path = os.path.dirname(src_path)
                if (os.path.split(dest_path)[0] == os.path.split(src_path)[0]
                        and dest['provider'] == src['provider']
                        and dest['nid'] == src['nid']
                        and dest['name'] != src['name']):
                    action = LOG_ACTION_MAP['rename']

            destination_node = node  # For clarity
            source_node = Node.load(payload['source']['nid'])

            source = source_node.get_addon(payload['source']['provider'])
            destination = node.get_addon(payload['destination']['provider'])

            payload['source'].update({
                'materialized':
                payload['source']['materialized'].lstrip('/'),
                'addon':
                source.config.full_name,
                'url':
                source_node.web_url_for(
                    'addon_view_or_download_file',
                    path=payload['source']['path'].lstrip('/'),
                    provider=payload['source']['provider']),
                'node': {
                    '_id': source_node._id,
                    'url': source_node.url,
                    'title': source_node.title,
                }
            })

            payload['destination'].update({
                'materialized':
                payload['destination']['materialized'].lstrip('/'),
                'addon':
                destination.config.full_name,
                'url':
                destination_node.web_url_for(
                    'addon_view_or_download_file',
                    path=payload['destination']['path'].lstrip('/'),
                    provider=payload['destination']['provider']),
                'node': {
                    '_id': destination_node._id,
                    'url': destination_node.url,
                    'title': destination_node.title,
                }
            })

            payload.update({
                'node': destination_node._id,
                'project': destination_node.parent_id,
            })

            if not payload.get('errors'):
                destination_node.add_log(action=action,
                                         auth=auth,
                                         params=payload)

            if payload.get('email') is True or payload.get('errors'):
                mails.send_mail(
                    user.username,
                    mails.FILE_OPERATION_FAILED
                    if payload.get('errors') else mails.FILE_OPERATION_SUCCESS,
                    action=payload['action'],
                    source_node=source_node,
                    destination_node=destination_node,
                    source_path=payload['source']['materialized'],
                    destination_path=payload['source']['materialized'],
                    source_addon=payload['source']['addon'],
                    destination_addon=payload['destination']['addon'],
                )

            if payload.get('error'):
                # Action failed but our function succeeded
                # Bail out to avoid file_signals
                return {'status': 'success'}

        else:
            try:
                metadata = payload['metadata']
                node_addon = node.get_addon(payload['provider'])
            except KeyError:
                raise HTTPError(httplib.BAD_REQUEST)

            if node_addon is None:
                raise HTTPError(httplib.BAD_REQUEST)

            metadata['path'] = metadata['path'].lstrip('/')

            node_addon.create_waterbutler_log(auth, action, metadata)

    with TokuTransaction():
        file_signals.file_updated.send(node=node,
                                       user=user,
                                       event_type=action,
                                       payload=payload)

    return {'status': 'success'}
Пример #31
0
 def test_must_be_logged_in_decorator_with_no_user(self, mock_from_kwargs):
     mock_from_kwargs.return_value = Auth()
     resp = protected()
     assert_true(isinstance(resp, BaseResponse))
     login_url = cas.get_login_url(service_url='http://localhost/')
     assert_equal(login_url, resp.headers.get('location'))
Пример #32
0
 def test_must_have_addon_user_false(self, mock_current_user):
     mock_current_user.return_value = Auth(self.project.creator)
     self.project.creator.delete_addon('github')
     decorated = must_have_addon('github', 'user')(needs_addon_view)
     with assert_raises(HTTPError):
         decorated()
Пример #33
0
    def test__get_readable_descendants_masked_by_permissions(self):
        # Users should be able to see through components they do not have
        # permissions to.
        # Users should not be able to see through links to nodes they do not
        # have permissions to.
        #
        #                   1(AB)
        #                  /  |  \
        #                 *   |   \
        #                /    |    \
        #             2(A)  4(B)    7(A)
        #               |     |     |    \
        #               |     |     |     \
        #             3(AB) 5(B)    8(AB) 9(B)
        #                     |
        #                     |
        #                   6(A)
        #
        #
        userA = UserFactory(fullname='User A')
        userB = UserFactory(fullname='User B')

        project1 = ProjectFactory(creator=self.user, title='One')
        project1.add_contributor(userA,
                                 auth=Auth(self.user),
                                 permissions=['read'])
        project1.add_contributor(userB,
                                 auth=Auth(self.user),
                                 permissions=['read'])

        component2 = ProjectFactory(creator=self.user, title='Two')
        component2.add_contributor(userA,
                                   auth=Auth(self.user),
                                   permissions=['read'])

        component3 = ProjectFactory(creator=self.user, title='Three')
        component3.add_contributor(userA,
                                   auth=Auth(self.user),
                                   permissions=['read'])
        component3.add_contributor(userB,
                                   auth=Auth(self.user),
                                   permissions=['read'])

        component4 = ProjectFactory(creator=self.user, title='Four')
        component4.add_contributor(userB,
                                   auth=Auth(self.user),
                                   permissions=['read'])

        component5 = ProjectFactory(creator=self.user, title='Five')
        component5.add_contributor(userB,
                                   auth=Auth(self.user),
                                   permissions=['read'])

        component6 = ProjectFactory(creator=self.user, title='Six')
        component6.add_contributor(userA,
                                   auth=Auth(self.user),
                                   permissions=['read'])

        component7 = ProjectFactory(creator=self.user, title='Seven')
        component7.add_contributor(userA,
                                   auth=Auth(self.user),
                                   permissions=['read'])

        component8 = ProjectFactory(creator=self.user, title='Eight')
        component8.add_contributor(userA,
                                   auth=Auth(self.user),
                                   permissions=['read'])
        component8.add_contributor(userB,
                                   auth=Auth(self.user),
                                   permissions=['read'])

        component9 = ProjectFactory(creator=self.user, title='Nine')
        component9.add_contributor(userB,
                                   auth=Auth(self.user),
                                   permissions=['read'])

        project1.add_pointer(component2, Auth(self.user))
        NodeRelation.objects.create(parent=project1, child=component4)
        NodeRelation.objects.create(parent=project1, child=component7)
        NodeRelation.objects.create(parent=component2, child=component3)
        NodeRelation.objects.create(parent=component4, child=component5)
        NodeRelation.objects.create(parent=component5, child=component6)
        NodeRelation.objects.create(parent=component7, child=component8)
        NodeRelation.objects.create(parent=component7, child=component9)

        nodes, all_readable = _get_readable_descendants(auth=Auth(userA),
                                                        node=project1)
        assert_equal(len(nodes), 3)
        assert_false(all_readable)

        for node in nodes:
            assert_in(node.title, ['Two', 'Six', 'Seven'])

        nodes, all_readable = _get_readable_descendants(auth=Auth(userB),
                                                        node=project1)
        assert_equal(len(nodes), 3)
        assert_false(all_readable)
        for node in nodes:
            assert_in(node.title, ['Four', 'Eight', 'Nine'])
Пример #34
0
def create_waterbutler_log(payload, **kwargs):
    with transaction.atomic():
        try:
            auth = payload['auth']
            # Don't log download actions
            if payload['action'] in DOWNLOAD_ACTIONS:
                guid = Guid.load(payload['metadata'].get('nid'))
                if guid:
                    node = guid.referent
                return {'status': 'success'}

            user = OSFUser.load(auth['id'])
            if user is None:
                raise HTTPError(http_status.HTTP_400_BAD_REQUEST)

            action = LOG_ACTION_MAP[payload['action']]
        except KeyError:
            raise HTTPError(http_status.HTTP_400_BAD_REQUEST)

        auth = Auth(user=user)
        node = kwargs.get('node') or kwargs.get('project') or Preprint.load(
            kwargs.get('nid')) or Preprint.load(kwargs.get('pid'))

        if action in (NodeLog.FILE_MOVED, NodeLog.FILE_COPIED):

            for bundle in ('source', 'destination'):
                for key in ('provider', 'materialized', 'name', 'nid'):
                    if key not in payload[bundle]:
                        raise HTTPError(http_status.HTTP_400_BAD_REQUEST)

            dest = payload['destination']
            src = payload['source']

            if src is not None and dest is not None:
                dest_path = dest['materialized']
                src_path = src['materialized']
                if dest_path.endswith('/') and src_path.endswith('/'):
                    dest_path = os.path.dirname(dest_path)
                    src_path = os.path.dirname(src_path)
                if (os.path.split(dest_path)[0] == os.path.split(src_path)[0]
                        and dest['provider'] == src['provider']
                        and dest['nid'] == src['nid']
                        and dest['name'] != src['name']):
                    action = LOG_ACTION_MAP['rename']

            destination_node = node  # For clarity
            source_node = AbstractNode.load(src['nid']) or Preprint.load(
                src['nid'])

            # We return provider fullname so we need to load node settings, if applicable
            source = None
            if hasattr(source_node, 'get_addon'):
                source = source_node.get_addon(payload['source']['provider'])
            destination = None
            if hasattr(node, 'get_addon'):
                destination = node.get_addon(
                    payload['destination']['provider'])

            payload['source'].update({
                'materialized':
                payload['source']['materialized'].lstrip('/'),
                'addon':
                source.config.full_name if source else 'osfstorage',
                'url':
                source_node.web_url_for(
                    'addon_view_or_download_file',
                    path=payload['source']['path'].lstrip('/'),
                    provider=payload['source']['provider']),
                'node': {
                    '_id': source_node._id,
                    'url': source_node.url,
                    'title': source_node.title,
                }
            })

            payload['destination'].update({
                'materialized':
                payload['destination']['materialized'].lstrip('/'),
                'addon':
                destination.config.full_name if destination else 'osfstorage',
                'url':
                destination_node.web_url_for(
                    'addon_view_or_download_file',
                    path=payload['destination']['path'].lstrip('/'),
                    provider=payload['destination']['provider']),
                'node': {
                    '_id': destination_node._id,
                    'url': destination_node.url,
                    'title': destination_node.title,
                }
            })

            if not payload.get('errors'):
                destination_node.add_log(action=action,
                                         auth=auth,
                                         params=payload)

            if payload.get('email') is True or payload.get('errors'):
                mails.send_mail(
                    user.username,
                    mails.FILE_OPERATION_FAILED
                    if payload.get('errors') else mails.FILE_OPERATION_SUCCESS,
                    action=payload['action'],
                    source_node=source_node,
                    destination_node=destination_node,
                    source_path=payload['source']['materialized'],
                    source_addon=payload['source']['addon'],
                    destination_addon=payload['destination']['addon'],
                    osf_support_email=settings.OSF_SUPPORT_EMAIL)

            if payload.get('errors'):
                # Action failed but our function succeeded
                # Bail out to avoid file_signals
                return {'status': 'success'}

        else:
            node.create_waterbutler_log(auth, action, payload)

    with transaction.atomic():
        file_signals.file_updated.send(target=node,
                                       user=user,
                                       event_type=action,
                                       payload=payload)

    return {'status': 'success'}
Пример #35
0
 def setUp(self):
     super(TestReportAbuse, self).setUp()
     self.comment = CommentFactory()
     self.auth = Auth(user=self.comment.user)
Пример #36
0
 def test_does_not_have_key(self, mock_from_kwargs):
     mock_from_kwargs.return_value = Auth(user=None)
     res = self.app.get('/project/{0}'.format(self.project._primary_key),
                        {'key': None})
     assert_is_redirect(res)