def login(nickname=None,
          password=None,
          login_method=None,
          action='',
          remember_me=False,
          referer=None):

    if CFG_ACCESS_CONTROL_LEVEL_SITE > 0:
        return abort(401)  # page is not authorized

    if action:
        try:
            action, arguments = mail_cookie_check_authorize_action(action)
        except InvenioWebAccessMailCookieError:
            pass
    form = LoginForm(CombinedMultiDict([
        ImmutableMultiDict({'referer': referer} if referer else {}),
        request.values
    ]),
                     csrf_enabled=False)
    try:
        user = None
        if not CFG_EXTERNAL_AUTH_USING_SSO:
            if login_method is 'Local':
                if form.validate_on_submit():
                    user = update_login(nickname, password, remember_me)
            elif login_method in ['openid', 'oauth1', 'oauth2']:
                pass
                req = request.get_legacy_request()
                (iden, nickname, password,
                 msgcode) = webuser.loginUser(req, nickname, password,
                                              login_method)
                if iden:
                    user = update_login(nickname)
            else:
                flash(_('Invalid login method.'), 'error')

        else:
            req = request.get_legacy_request()
            # Fake parameters for p_un & p_pw because SSO takes them from the environment
            (iden, nickname, password,
             msgcode) = webuser.loginUser(req, '', '',
                                          CFG_EXTERNAL_AUTH_USING_SSO)
            if iden:
                user = update_login(nickname)

        if user:
            flash(_("You are logged in as %s.") % user.nickname, "info")
            if referer is not None:
                # Change HTTP method to https if needed.
                referer = referer.replace(CFG_SITE_URL, CFG_SITE_SECURE_URL)
                return redirect(referer)
    except:
        flash(_("Problem with login."), "error")

    current_app.config.update(
        dict((k, v) for k, v in vars(websession_config).iteritems()
             if "CFG_" == k[:4]))

    return render_template('webaccount_login.html', form=form)
    def _traverse(self, req, path, do_head=False, guest_p=True):
        """ Locate the handler of an URI by traversing the elements of
        the path."""

        _debug(req, 'traversing %r' % path)

        component, path = path[0], path[1:]

        name = self._translate(component)

        if name is None:
            obj, path = self._lookup(component, path)
        else:
            obj = getattr(self, name)

        if obj is None:
            _debug(req, 'could not resolve %s' % repr((component, path)))
            raise TraversalError()

        # We have found the next segment. If we know that from this
        # point our subpages are over HTTPS, do the switch.

        if CFG_HAS_HTTPS_SUPPORT and self._force_https and not req.is_https():
            # We need to isolate the part of the URI that is after
            # CFG_SITE_URL, and append that to our CFG_SITE_SECURE_URL.
            original_parts = urlparse.urlparse(req.unparsed_uri)
            plain_prefix_parts = urlparse.urlparse(CFG_SITE_URL)
            secure_prefix_parts = urlparse.urlparse(CFG_SITE_SECURE_URL)

            # Compute the new path
            plain_path = original_parts[2]
            plain_path = secure_prefix_parts[2] + \
                         plain_path[len(plain_prefix_parts[2]):]

            # ...and recompose the complete URL
            final_parts = list(secure_prefix_parts)
            final_parts[2] = plain_path
            final_parts[-3:] = original_parts[-3:]

            target = urlparse.urlunparse(final_parts)
            redirect_to_url(req, target)
        if CFG_EXTERNAL_AUTH_USING_SSO and req.is_https() and guest_p:
            (iden, p_un, dummy, dummy) = loginUser(req, '', '',
                                         CFG_EXTERNAL_AUTH_USING_SSO)
            if len(iden)>0:
                update_Uid(req, p_un)
                guest_p = False

        # Continue the traversal. If there is a path, continue
        # resolving, otherwise call the method as it is our final
        # renderer. We even pass it the parsed form arguments.
        if path:
            if hasattr(obj, '_traverse'):
                return obj._traverse(req, path, do_head, guest_p)
            else:
                raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

        if do_head:
            req.content_type = "text/html; charset=UTF-8"
            raise apache.SERVER_RETURN, apache.DONE

        form = req.form
        if 'ln' not in form and \
                req.uri not in CFG_NO_LANG_RECOGNITION_URIS:
            ln = get_preferred_user_language(req)
            form.add_field('ln', ln)
        result = _check_result(req, obj(req, form))
        return result
Пример #3
0
    def _traverse(self, req, path, do_head=False, guest_p=True):
        """ Locate the handler of an URI by traversing the elements of
        the path."""

        _debug(req, 'traversing %r' % path)

        component, path = path[0], path[1:]

        name = self._translate(component)

        if name is None:
            obj, path = self._lookup(component, path)
        else:
            obj = getattr(self, name)

        if obj is None:
            _debug(req, 'could not resolve %s' % repr((component, path)))
            raise TraversalError()

        # We have found the next segment. If we know that from this
        # point our subpages are over HTTPS, do the switch.

        if CFG_HAS_HTTPS_SUPPORT and self._force_https and not req.is_https():
            # We need to isolate the part of the URI that is after
            # CFG_SITE_URL, and append that to our CFG_SITE_SECURE_URL.
            original_parts = urlparse.urlparse(req.unparsed_uri)
            plain_prefix_parts = urlparse.urlparse(CFG_SITE_URL)
            secure_prefix_parts = urlparse.urlparse(CFG_SITE_SECURE_URL)

            # Compute the new path
            plain_path = original_parts[2]
            plain_path = secure_prefix_parts[2] + \
                         plain_path[len(plain_prefix_parts[2]):]

            # ...and recompose the complete URL
            final_parts = list(secure_prefix_parts)
            final_parts[2] = plain_path
            final_parts[-3:] = original_parts[-3:]

            target = urlparse.urlunparse(final_parts)
            redirect_to_url(req, target)
        if CFG_EXTERNAL_AUTH_USING_SSO and req.is_https() and guest_p:
            (iden, p_un, dummy, dummy) = loginUser(req, '', '',
                                         CFG_EXTERNAL_AUTH_USING_SSO)
            if len(iden)>0:
                update_Uid(req, p_un)
                guest_p = False

        # Continue the traversal. If there is a path, continue
        # resolving, otherwise call the method as it is our final
        # renderer. We even pass it the parsed form arguments.
        if path:
            if hasattr(obj, '_traverse'):
                return obj._traverse(req, path, do_head, guest_p)
            else:
                raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

        if do_head:
            req.content_type = "text/html; charset=UTF-8"
            raise apache.SERVER_RETURN, apache.DONE

        form = req.form
        if 'ln' not in form and \
                req.uri not in CFG_NO_LANG_RECOGNITION_URIS:
            ln = get_preferred_user_language(req)
            form.add_field('ln', ln)
        result = _check_result(req, obj(req, form))
        return result
Пример #4
0
def login(nickname=None, password=None, login_method=None, action='',
          remember_me=False, referer=None):

    if CFG_ACCESS_CONTROL_LEVEL_SITE > 0:
        return abort(401)  # page is not authorized

    if action:
        try:
            action, arguments = mail_cookie_check_authorize_action(action)
        except InvenioWebAccessMailCookieError:
            pass
    form = LoginForm(CombinedMultiDict([ImmutableMultiDict({'referer': referer}
                                        if referer else {}),
                                        request.values]),
                     csrf_enabled=False)
    try:
        user = None
        if not CFG_EXTERNAL_AUTH_USING_SSO:
            if login_method == 'Local':
                if form.validate_on_submit():
                    user = update_login(nickname, password, remember_me)
            elif login_method in ['openid', 'oauth1', 'oauth2']:
                pass
                req = request.get_legacy_request()
                (iden, nickname, password, msgcode) = webuser.loginUser(req, nickname,
                                                                        password,
                                                                        login_method)
                if iden:
                    user = update_login(nickname)
            else:
                flash(_('Invalid login method.'), 'error')

        else:
            req = request.get_legacy_request()
            # Fake parameters for p_un & p_pw because SSO takes them from the environment
            (iden, nickname, password, msgcode) = webuser.loginUser(req, '', '', CFG_EXTERNAL_AUTH_USING_SSO)
            if iden:
                user = update_login(nickname)

        if user:
            flash(_("You are logged in as %s.") % user.nickname, "info")
            if referer is not None:
                from urlparse import urlparse
                # we should not redirect to these URLs after login
                blacklist = [url_for('webaccount.register'),
                             url_for('webaccount.logout'),
                             url_for('webaccount.login')]
                if not urlparse(referer).path in blacklist:
                    # Change HTTP method to https if needed.
                    referer = referer.replace(CFG_SITE_URL, CFG_SITE_SECURE_URL)
                    return redirect(referer)
                return redirect('/')

    except:
        flash(_("Problem with login."), "error")

    current_app.config.update(dict((k, v) for k, v in
                              vars(websession_config).iteritems()
                              if "CFG_" == k[:4]))

    collection = Collection.query.get_or_404(1)

    from invenio.b2share_utils import get_latest_deposits
    latest_deposits = get_latest_deposits()
    # @register_template_context_processor
    #     def index_context():
    #         return dict(
    #             easy_search_form=EasySearchForm(csrf_enabled=False),
    #             format_record=cached_format_record,
    #             get_creation_date=get_creation_date,
    #             unregistered=(not current_user.is_authenticated())
    #         )
    return render_template('webaccount_login.html', form=form, 
                           collection=collection, latest_deposits=latest_deposits)