Ejemplo n.º 1
0
def register(request):
    """The registration view.

    Note that usernames will always be lowercased. Email domains are lowercased while
    the first part remains case-sensitive.
    """
    if 'pass_auth' not in request.template_env.globals:
        redirect_name = hook_handle('auth_no_pass_redirect')
        if redirect_name:
            return redirect(request, 'mediagoblin.plugins.{0}.register'.format(
                redirect_name))
        else:
            return redirect(request, 'index')

    register_form = hook_handle("auth_get_registration_form", request)

    if request.method == 'POST' and register_form.validate():
        # TODO: Make sure the user doesn't exist already
        user = register_user(request, register_form)

        if user:
            # redirect the user to their homepage... there will be a
            # message waiting for them to verify their email
            return redirect(
                request, 'mediagoblin.user_pages.user_home',
                user=user.username)

    return render_to_response(
        request,
        'mediagoblin/auth/register.html',
        {'register_form': register_form,
         'post_url': request.urlgen('mediagoblin.auth.register')})
Ejemplo n.º 2
0
def register(request):
    """The registration view.

    Note that usernames will always be lowercased. Email domains are lowercased while
    the first part remains case-sensitive.
    """
    if 'pass_auth' not in request.template_env.globals:
        redirect_name = hook_handle('auth_no_pass_redirect')
        if redirect_name:
            return redirect(
                request,
                'mediagoblin.plugins.{0}.register'.format(redirect_name))
        else:
            return redirect(request, 'index')

    register_form = hook_handle("auth_get_registration_form", request)

    if request.method == 'POST' and register_form.validate():
        # TODO: Make sure the user doesn't exist already
        user = register_user(request, register_form)

        if user:
            # redirect the user to their homepage... there will be a
            # message waiting for them to verify their email
            return redirect(request,
                            'mediagoblin.user_pages.user_home',
                            user=user.username)

    return render_to_response(
        request, 'mediagoblin/auth/register.html', {
            'register_form': register_form,
            'post_url': request.urlgen('mediagoblin.auth.register')
        })
Ejemplo n.º 3
0
def sniff_media(media):
    '''
    Iterate through the enabled media types and find those suited
    for a certain file.
    '''

    try:
        return get_media_type_and_manager(media.filename)
    except FileTypeNotSupported:
        _log.info(
            'No media handler found by file extension. Doing it the expensive way...'
        )
        # Create a temporary file for sniffers suchs as GStreamer-based
        # Audio video
        media_file = tempfile.NamedTemporaryFile()
        media_file.write(media.stream.read())
        media.stream.seek(0)

        media_type = hook_handle('sniff_handler', media_file, media=media)
        if media_type:
            _log.info('{0} accepts the file'.format(media_type))
            return media_type, hook_handle(('media_manager', media_type))
        else:
            _log.debug('{0} did not accept the file'.format(media_type))

    raise FileTypeNotSupported(
        # TODO: Provide information on which file types are supported
        _(u'Sorry, I don\'t support that file type :('))
Ejemplo n.º 4
0
def sniff_media(media_file, filename):
    '''
    Iterate through the enabled media types and find those suited
    for a certain file.
    '''

    try:
        return get_media_type_and_manager(filename)
    except FileTypeNotSupported:
        _log.info('No media handler found by file extension. Doing it the expensive way...')
        # Create a temporary file for sniffers suchs as GStreamer-based
        # Audio video
        tmp_media_file = tempfile.NamedTemporaryFile()
        tmp_media_file.write(media_file.read())
        tmp_media_file.seek(0)
        media_file.seek(0)

        media_type = hook_handle('sniff_handler', tmp_media_file, filename)
        if media_type:
            _log.info('{0} accepts the file'.format(media_type))
            return media_type, hook_handle(('media_manager', media_type))
        else:
            _log.debug('{0} did not accept the file'.format(media_type))

    raise FileTypeNotSupported(
        # TODO: Provide information on which file types are supported
        _(u'Sorry, I don\'t support that file type :('))
Ejemplo n.º 5
0
def check_login_simple(username, password):
    user = auth.get_user(username=username)
    if not user:
        _log.info("User %r not found", username)
        hook_handle("auth_fake_login_attempt")
        return None
    if not auth.check_password(password, user.pw_hash):
        _log.warn("Wrong password for %r", username)
        return None
    _log.info("Logging %r in", username)
    return user
Ejemplo n.º 6
0
def check_login_simple(username, password):
    user = auth.get_user(username=username)
    if not user:
        _log.info("User %r not found", username)
        hook_handle("auth_fake_login_attempt")
        return None
    if not auth.check_password(password, user.pw_hash):
        _log.warn("Wrong password for %r", username)
        return None
    _log.info("Logging %r in", username)
    return user
Ejemplo n.º 7
0
def login(request):
    """
    MediaGoblin login view.

    If you provide the POST with 'next', it'll redirect to that view.
    """
    if 'pass_auth' not in request.template_env.globals:
        redirect_name = hook_handle('auth_no_pass_redirect')
        if redirect_name:
            return redirect(
                request, 'mediagoblin.plugins.{0}.login'.format(redirect_name))
        else:
            return redirect(request, 'index')

    login_form = hook_handle("auth_get_login_form", request)

    login_failed = False

    if request.method == 'POST':

        if login_form.validate():
            user = check_login_simple(login_form.username.data,
                                      login_form.password.data)

            if user:
                # set up login in session
                if login_form.stay_logged_in.data:
                    request.session['stay_logged_in'] = True
                request.session['user_id'] = six.text_type(user.id)
                request.session.save()

                if request.form.get('next'):
                    return redirect(request, location=request.form['next'])
                else:
                    return redirect(request, "index")

            login_failed = True
            remote_addr = (request.access_route and request.access_route[-1]
                           or request.remote_addr)
            _log.warn("Failed login attempt from %r", remote_addr)

    return render_to_response(
        request, 'mediagoblin/auth/login.html', {
            'login_form': login_form,
            'next': request.GET.get('next') or request.form.get('next'),
            'login_failed': login_failed,
            'post_url': request.urlgen('mediagoblin.auth.login'),
            'allow_registration': mg_globals.app_config["allow_registration"]
        })
Ejemplo n.º 8
0
def setup_plugin():
    _log.info('Setting up lepturecaptcha...')

    config = pluginapi.get_config('mediagoblin.plugins.lepturecaptcha')
    if config:
        if config.get('CAPTCHA_SECRET_PHRASE') == 'changeme':
            configuration_error = 'You must configure the captcha secret phrase.'
            raise ImproperlyConfigured(configuration_error)

    pluginapi.register_template_path(os.path.join(PLUGIN_DIR, 'templates'))

    pluginapi.register_template_hooks(
        {'register_captcha': 'mediagoblin/plugins/lepturecaptcha/captcha_challenge.html'})

    # Create dummy request object to find register_form.
    environ = create_environ('/foo', 'http://localhost:8080/')
    request = Request(environ)
    register_form = pluginapi.hook_handle("auth_get_registration_form", request)
    del request

    # Add plugin-specific fields to register_form class.
    register_form_class = register_form.__class__
    register_form_class.captcha_response = captcha_forms.CaptchaStringField('CAPTCHA response', id='captcha_response', name='captcha_response')
    register_form_class.captcha_hash = wtforms.HiddenField('')
    register_form_class.remote_address = wtforms.HiddenField('')

    _log.info('Done setting up lepturecaptcha!')
Ejemplo n.º 9
0
def setup_plugin():
    _log.info('Setting up recaptcha...')

    config = pluginapi.get_config('mediagoblin.plugins.recaptcha')
    if config:
        if config.get('RECAPTCHA_SITE_KEY') == 'domainsitekey':
            configuration_error = 'You must configure the recaptcha plugin site key.'
            raise ImproperlyConfigured(configuration_error)
        if config.get('RECAPTCHA_SECRET_KEY') == 'domainsecretkey':
            configuration_error = 'You must configure the recaptcha plugin secret key.'
            raise ImproperlyConfigured(configuration_error)

    pluginapi.register_template_path(os.path.join(PLUGIN_DIR, 'templates'))

    pluginapi.register_template_hooks({
        'register_captcha':
        'mediagoblin/plugins/recaptcha/captcha_challenge.html'
    })

    # Create dummy request object to find register_form.
    environ = create_environ('/foo', 'http://localhost:8080/')
    request = Request(environ)
    register_form = pluginapi.hook_handle("auth_get_registration_form",
                                          request)
    del request

    # Add plugin-specific fields to register_form class.
    register_form_class = register_form.__class__
    register_form_class.g_recaptcha_response = captcha_forms.RecaptchaHiddenField(
        'reCAPTCHA', id='g-recaptcha-response', name='g-recaptcha-response')
    register_form_class.remote_address = wtforms.HiddenField('')

    _log.info('Done setting up recaptcha!')
Ejemplo n.º 10
0
def sniff_media_contents(media_file, filename):
    '''
    Check media contents using 'expensive' scanning. For example, for video it
    is checking the contents using gstreamer
    :param media_file: file-like object with 'name' attribute
    :param filename: expected filename of the media
    '''
    media_type = hook_handle('sniff_handler', media_file, filename)
    if media_type:
        _log.info('{0} accepts the file'.format(media_type))
        return media_type, hook_handle(('media_manager', media_type))
    else:
        _log.debug('{0} did not accept the file'.format(media_type))
        raise FileTypeNotSupported(
            # TODO: Provide information on which file types are supported
            _(u'Sorry, I don\'t support that file type :('))
Ejemplo n.º 11
0
def type_match_handler(media_file, filename):
    '''Check media file by name and then by content

    Try to find the media type based on the file name, extension
    specifically. After that, if media type is one of supported ones, check the
    contents of the file
    '''
    if filename.find('.') > 0:
        # Get the file extension
        ext = os.path.splitext(filename)[1].lower()

        # Omit the dot from the extension and match it against
        # the media manager
        hook_result = hook_handle('type_match_handler', ext[1:])
        if hook_result:
            _log.info('Info about file found, checking further')
            MEDIA_TYPE, Manager, sniffer = hook_result
            if not sniffer:
                _log.debug('sniffer is None, plugin trusts the extension')
                return MEDIA_TYPE, Manager
            _log.info('checking the contents with sniffer')
            try:
                sniffer(media_file)
                _log.info('checked, found')
                return MEDIA_TYPE, Manager
            except Exception as e:
                _log.info('sniffer says it will not accept the file')
                _log.debug(e)
                raise
        else:
            _log.info('No plugins handled extension {0}'.format(ext))
    else:
        _log.info('File {0} has no known file extension, let\'s hope '
                  'the sniffers get it.'.format(filename))
    raise TypeNotFound(_(u'Sorry, I don\'t support that file type :('))
Ejemplo n.º 12
0
def sniff_media_contents(media_file, filename):
    '''
    Check media contents using 'expensive' scanning. For example, for video it
    is checking the contents using gstreamer
    :param media_file: file-like object with 'name' attribute
    :param filename: expected filename of the media
    '''
    media_type = hook_handle('sniff_handler', media_file, filename)
    if media_type:
        _log.info('{0} accepts the file'.format(media_type))
        return media_type, hook_handle(('media_manager', media_type))
    else:
        _log.debug('{0} did not accept the file'.format(media_type))
        raise FileTypeNotSupported(
            # TODO: Provide information on which file types are supported
            _(u'Sorry, I don\'t support that file type :('))
Ejemplo n.º 13
0
def type_match_handler(media_file, filename):
    '''Check media file by name and then by content

    Try to find the media type based on the file name, extension
    specifically. After that, if media type is one of supported ones, check the
    contents of the file
    '''
    if os.path.basename(filename).find('.') > 0:
        # Get the file extension
        ext = os.path.splitext(filename)[1].lower()

        # Omit the dot from the extension and match it against
        # the media manager
        hook_result = hook_handle('type_match_handler', ext[1:])
        if hook_result:
            _log.info('Info about file found, checking further')
            MEDIA_TYPE, Manager, sniffer = hook_result
            if not sniffer:
                _log.debug('sniffer is None, plugin trusts the extension')
                return MEDIA_TYPE, Manager
            _log.info('checking the contents with sniffer')
            try:
                sniffer(media_file)
                _log.info('checked, found')
                return MEDIA_TYPE, Manager
            except Exception as e:
                _log.info('sniffer says it will not accept the file')
                _log.debug(e)
                raise
        else:
            _log.info('No plugins handled extension {0}'.format(ext))
    else:
        _log.info('File {0} has no known file extension, let\'s hope '
                'the sniffers get it.'.format(filename))
    raise TypeNotFound(_(u'Sorry, I don\'t support that file type :('))
Ejemplo n.º 14
0
def load_context(url):
    """
    A self-aware document loader.  For those contexts MediaGoblin
    stores internally, load them from disk.
    """
    if url in _CONTEXT_CACHE:
        return _CONTEXT_CACHE[url]

    # See if it's one of our basic ones
    document = BUILTIN_CONTEXTS.get(url, None)

    # No?  See if we have an internal schema for this
    if document is None:
        document = hook_handle(("context_url_data", url))

    # Okay, if we've gotten a document by now... let's package it up
    if document is not None:
        document = {'contextUrl': None,
                    'documentUrl': url,
                    'document': document}

    # Otherwise, use jsonld.load_document
    else:
        document = jsonld.load_document(url)

    # cache
    _CONTEXT_CACHE[url] = document
    return document
Ejemplo n.º 15
0
def load_context(url):
    """
    A self-aware document loader.  For those contexts MediaGoblin
    stores internally, load them from disk.
    """
    if url in _CONTEXT_CACHE:
        return _CONTEXT_CACHE[url]

    # See if it's one of our basic ones
    document = BUILTIN_CONTEXTS.get(url, None)

    # No?  See if we have an internal schema for this
    if document is None:
        document = hook_handle(("context_url_data", url))

    # Okay, if we've gotten a document by now... let's package it up
    if document is not None:
        document = {
            'contextUrl': None,
            'documentUrl': url,
            'document': document
        }

    # Otherwise, use jsonld.load_document
    else:
        document = jsonld.load_document(url)

    # cache
    _CONTEXT_CACHE[url] = document
    return document
Ejemplo n.º 16
0
def login(request):
    """
    MediaGoblin login view.

    If you provide the POST with 'next', it'll redirect to that view.
    """
    if 'pass_auth' not in request.template_env.globals:
        redirect_name = hook_handle('auth_no_pass_redirect')
        if redirect_name:
            return redirect(request, 'mediagoblin.plugins.{0}.login'.format(
                redirect_name))
        else:
            return redirect(request, 'index')

    login_form = hook_handle("auth_get_login_form", request)

    login_failed = False

    if request.method == 'POST':

        if login_form.validate():
            user = check_login_simple(
                login_form.username.data,
                login_form.password.data)

            if user:
                # set up login in session
                if login_form.stay_logged_in.data:
                    request.session['stay_logged_in'] = True
                request.session['user_id'] = six.text_type(user.id)
                request.session.save()

                if request.form.get('next'):
                    return redirect(request, location=request.form['next'])
                else:
                    return redirect(request, "index")

            login_failed = True

    return render_to_response(
        request,
        'mediagoblin/auth/login.html',
        {'login_form': login_form,
         'next': request.GET.get('next') or request.form.get('next'),
         'login_failed': login_failed,
         'post_url': request.urlgen('mediagoblin.auth.login'),
         'allow_registration': mg_globals.app_config["allow_registration"]})
Ejemplo n.º 17
0
def feature_template(media, feature_type):
    """
    Get the feature template for this media
    """
    template_name = hook_handle(
        ("feature_%s_template" % feature_type, media.media_type))

    if template_name is None:
        return "/archivalook/feature_displays/default_%s.html" % feature_type

    return template_name
Ejemplo n.º 18
0
def get_processing_manager_for_type(media_type):
    """
    Get the appropriate media manager for this type
    """
    manager_class = hook_handle(('reprocess_manager', media_type))
    if not manager_class:
        raise ProcessingManagerDoesNotExist(
            "A processing manager does not exist for {0}".format(media_type))
    manager = manager_class()

    return manager
Ejemplo n.º 19
0
def get_media_type_and_manager(filename):
    '''
    Try to find the media type based on the file name, extension
    specifically. This is used as a speedup, the sniffing functionality
    then falls back on more in-depth bitsniffing of the source file.
    '''
    if filename.find('.') > 0:
        # Get the file extension
        ext = os.path.splitext(filename)[1].lower()

        # Omit the dot from the extension and match it against
        # the media manager
        if hook_handle('get_media_type_and_manager', ext[1:]):
            return hook_handle('get_media_type_and_manager', ext[1:])
    else:
        _log.info('File {0} has no file extension, let\'s hope the sniffers get it.'.format(
            filename))

    raise FileTypeNotSupported(
        _(u'Sorry, I don\'t support that file type :('))
Ejemplo n.º 20
0
def get_media_type_and_manager(filename):
    '''
    Try to find the media type based on the file name, extension
    specifically. This is used as a speedup, the sniffing functionality
    then falls back on more in-depth bitsniffing of the source file.
    '''
    if filename.find('.') > 0:
        # Get the file extension
        ext = os.path.splitext(filename)[1].lower()

        # Omit the dot from the extension and match it against
        # the media manager
        if hook_handle('get_media_type_and_manager', ext[1:]):
            return hook_handle('get_media_type_and_manager', ext[1:])
    else:
        _log.info(
            'File {0} has no file extension, let\'s hope the sniffers get it.'.
            format(filename))

    raise FileTypeNotSupported(_(u'Sorry, I don\'t support that file type :('))
Ejemplo n.º 21
0
def get_processing_manager_for_type(media_type):
    """
    Get the appropriate media manager for this type
    """
    manager_class = hook_handle(('reprocess_manager', media_type))
    if not manager_class:
        raise ProcessingManagerDoesNotExist(
            "A processing manager does not exist for {0}".format(media_type))
    manager = manager_class()

    return manager
Ejemplo n.º 22
0
    def media_manager(self):
        """Returns the MEDIA_MANAGER of the media's media_type

        Raises FileTypeNotSupported in case no such manager is enabled
        """
        manager = hook_handle(('media_manager', self.media_type))
        if manager:
            return manager(self)

        # Not found?  Then raise an error
        raise FileTypeNotSupported(
            "MediaManager not in enabled types. Check media_type plugins are"
            " enabled in config?")
Ejemplo n.º 23
0
    def media_manager(self):
        """Returns the MEDIA_MANAGER of the media's media_type

        Raises FileTypeNotSupported in case no such manager is enabled
        """
        manager = hook_handle(('media_manager', self.media_type))
        if manager:
            return manager(self)

        # Not found?  Then raise an error
        raise FileTypeNotSupported(
            "MediaManager not in enabled types. Check media_type plugins are"
            " enabled in config?")
Ejemplo n.º 24
0
def test_hook_handle():
    """
    Test the hook_handle method
    """
    cfg = build_config(CONFIG_ALL_CALLABLES)

    mg_globals.app_config = cfg['mediagoblin']
    mg_globals.global_config = cfg

    setup_plugins()

    # Just one hook provided
    call_log = []
    assert pluginapi.hook_handle(
        "just_one", call_log) == "Called just once"
    assert call_log == ["expect this one call"]

    # Nothing provided and unhandled not okay
    call_log = []
    pluginapi.hook_handle(
        "nothing_handling", call_log) == None
    assert call_log == []

    # Nothing provided and unhandled okay
    call_log = []
    assert pluginapi.hook_handle(
        "nothing_handling", call_log, unhandled_okay=True) is None
    assert call_log == []
    
    # Multiple provided, go with the first!
    call_log = []
    assert pluginapi.hook_handle(
        "multi_handle", call_log) == "the first returns"
    assert call_log == ["Hi, I'm the first"]

    # Multiple provided, one has CantHandleIt
    call_log = []
    assert pluginapi.hook_handle(
        "multi_handle_with_canthandle",
        call_log) == "the second returns"
    assert call_log == ["Hi, I'm the second"]
Ejemplo n.º 25
0
def test_hook_handle():
    """
    Test the hook_handle method
    """
    cfg = build_config(CONFIG_ALL_CALLABLES)

    mg_globals.app_config = cfg['mediagoblin']
    mg_globals.global_config = cfg

    setup_plugins()

    # Just one hook provided
    call_log = []
    assert pluginapi.hook_handle("just_one", call_log) == "Called just once"
    assert call_log == ["expect this one call"]

    # Nothing provided and unhandled not okay
    call_log = []
    pluginapi.hook_handle("nothing_handling", call_log) == None
    assert call_log == []

    # Nothing provided and unhandled okay
    call_log = []
    assert pluginapi.hook_handle(
        "nothing_handling", call_log, unhandled_okay=True) is None
    assert call_log == []

    # Multiple provided, go with the first!
    call_log = []
    assert pluginapi.hook_handle("multi_handle",
                                 call_log) == "the first returns"
    assert call_log == ["Hi, I'm the first"]

    # Multiple provided, one has CantHandleIt
    call_log = []
    assert pluginapi.hook_handle("multi_handle_with_canthandle",
                                 call_log) == "the second returns"
    assert call_log == ["Hi, I'm the second"]
Ejemplo n.º 26
0
def get_user(**kwargs):
    """ Takes a kwarg such as username and returns a user object """
    return hook_handle("auth_get_user", **kwargs)
Ejemplo n.º 27
0
def root_view(request):
    """
    Proxies to the real root view that's displayed
    """
    view = hook_handle("frontpage_view") or default_root_view
    return view(request)
Ejemplo n.º 28
0
def root_view(request):
    """
    Proxies to the real root view that's displayed
    """
    view = hook_handle("frontpage_view") or default_root_view
    return view(request)
Ejemplo n.º 29
0
def check_password(raw_pass, stored_hash, extra_salt=None):
    return hook_handle("auth_check_password", raw_pass, stored_hash,
                       extra_salt)
Ejemplo n.º 30
0
def gen_password_hash(raw_pass, extra_salt=None):
    return hook_handle("auth_gen_password_hash", raw_pass, extra_salt)
Ejemplo n.º 31
0
def check_auth_enabled():
    if not hook_handle('authentication'):
        _log.warning('No authentication is enabled')
        return False
    else:
        return True
Ejemplo n.º 32
0
def check_auth_enabled():
    if not hook_handle('authentication'):
        _log.warning('No authentication is enabled')
        return False
    else:
        return True
Ejemplo n.º 33
0
def check_password(raw_pass, stored_hash, extra_salt=None):
    return hook_handle("auth_check_password",
                       raw_pass, stored_hash, extra_salt)
Ejemplo n.º 34
0
def gen_password_hash(raw_pass, extra_salt=None):
    return hook_handle("auth_gen_password_hash", raw_pass, extra_salt)
Ejemplo n.º 35
0
def get_user(**kwargs):
    """ Takes a kwarg such as username and returns a user object """
    return hook_handle("auth_get_user", **kwargs)