Beispiel #1
0
def set_best_lang(check_session=True):
    """
    Get the best language/locale for the current user. This means that first
    the session will be checked, and then in the absence of an explicitly-set
    language, we will try to guess it from the browser settings and only
    after that fall back to the server's default.
    """
    if not has_request_context():
        return 'en_GB' if current_app.config['TESTING'] else HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
    elif 'lang' in g:
        return g.lang
    elif check_session and session.lang is not None:
        return session.lang

    # try to use browser language
    preferred = [x.replace('-', '_') for x in request.accept_languages.values()]
    resolved_lang = negotiate_locale(preferred, list(get_all_locales()), aliases=LOCALE_ALIASES)

    if not resolved_lang:
        if current_app.config['TESTING']:
            return 'en_GB'

        with DBMgr.getInstance().global_connection():
            # fall back to server default
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            resolved_lang = minfo.getLang()

    # As soon as we looked up a language, cache it during the request.
    # This will be returned when accessing `session.lang` since there's code
    # which reads the language from there and might fail (e.g. by returning
    # lazy strings) if it's not set.
    g.lang = resolved_lang
    return resolved_lang
Beispiel #2
0
    def _sendErrorEmail(self, e):
        ty, ex, tb = sys.exc_info()
        tracebackList = traceback.format_list(traceback.extract_tb(tb))
        text = _("""
                    Offline website creation for the [event:%s] had caused 
                    an error while running the task.

                    - Request from user: %s <%s>

                    - Details of the exception: 
                        %s

                    - Traceback:

                        %s

                    --

                    <Indico support> indico-project @ cern.ch
                    """) % (self._conf.getId(), self._toUser.getFullName(),
                            self._toUser.getEmail(), e,
                            "\n".join(tracebackList))
        maildata = {
            "fromAddr":
            HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail(),
            "toList":
            [HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail()],
            "subject": _("[Indico] Error in task: Offline website creation"),
            "body": text
        }
        GenericMailer.send(GenericNotification(maildata))
Beispiel #3
0
def set_best_lang():
    """
    Get the best language/locale for the current user. This means that first
    the session will be checked, and then in the absence of an explicitly-set
    language, we will try to guess it from the browser settings and only
    after that fall back to the server's default.
    """

    if not has_request_context():
        return 'en_GB' if current_app.config['TESTING'] else HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
    elif session.lang is not None:
        return session.lang

    # try to use browser language
    preferred = [x.replace('-', '_') for x in request.accept_languages.values()]
    resolved_lang = negotiate_locale(preferred, list(get_all_locales()), aliases=LOCALE_ALIASES)

    if not resolved_lang:
        if current_app.config['TESTING']:
            return 'en_GB'

        with DBMgr.getInstance().global_connection():
            # fall back to server default
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            resolved_lang = minfo.getLang()

    session.lang = resolved_lang
    return resolved_lang
Beispiel #4
0
def set_best_lang():
    """
    Get the best language/locale for the current user. This means that first
    the session will be checked, and then in the absence of an explicitly-set
    language, we will try to guess it from the browser settings and only
    after that fall back to the server's default.
    """

    if not has_request_context():
        return 'en_GB' if current_app.config[
            'TESTING'] else HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
    elif session.lang is not None:
        return session.lang

    # try to use browser language
    preferred = [
        x.replace('-', '_') for x in request.accept_languages.values()
    ]
    resolved_lang = negotiate_locale(preferred,
                                     list(get_all_locales()),
                                     aliases=LOCALE_ALIASES)

    if not resolved_lang:
        if current_app.config['TESTING']:
            return 'en_GB'

        with DBMgr.getInstance().global_connection():
            # fall back to server default
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            resolved_lang = minfo.getLang()

    session.lang = resolved_lang
    return resolved_lang
Beispiel #5
0
    def __init__( self, rh ):
        config = Config.getInstance()
        db_connected = DBMgr.getInstance().isConnected()

        self._rh = rh
        self._locTZ = ""

        self._asset_env = Environment(config.getHtdocsDir(), '')

        if db_connected:
            debug = HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive()
        else:
            debug = False

        # This is done in order to avoid the problem sending the error report because the DB is not connected.
        if db_connected:
            info = HelperMaKaCInfo.getMaKaCInfoInstance()
            self._asset_env.debug = info.isDebugActive()

        self._dir = config.getTPLDir()
        self._asset_env.debug = debug

        if db_connected:
            css_file = config.getCssStylesheetName()
        else:
            css_file = 'Default.css'

        # register existing assets
        assets.register_all_js(self._asset_env)
        assets.register_all_css(self._asset_env, css_file)

        #store page specific CSS and JS
        self._extraCSS = []
        self._extraJS = []
Beispiel #6
0
 def __init__(self):
     self._newsItems = []
     self._p_changed = 1
     self._newsCounter = Counter()
     self._recentDays = 14 #days to keep a 'New' tag on recent news items
     # fetch all news from the previous location.
     self.addNewsItem(NewsItem( _("Previous news"), HelperMaKaCInfo.getMaKaCInfoInstance().getNews(), "general"))
Beispiel #7
0
class sendLoginInfo:
    
    def __init__( self, user ):
        self._user = user
    
    def send (self ):
        idList = self._user.getIdentityList()
        logins = []
        for id in idList:
            try:
                pw = id.password
            except AttributeError, e:
                pw = _(" Sorry, you are using your NICE credentials to login into Indico. Please contact the CERN helpdesk in case you do not remember your password ([email protected]).")
            logins.append( [id.getAuthenticatorTag(), id.getLogin(),pw])
        if logins == []:
            text = _("Sorry, we did not find your login.\nPlease, create one here:\n%s")%urlHandlers.UHUserDetails.getURL(self._user)
        else:
            text = _("Please, find your login and password:"******"\n\n==================\n"
                text += _("system:%s\n")%l[0]
                text += _("Login:%s\n")%l[1]
                text += _("Password:%s\n")%l[2]
                text += "==================\n"
        maildata = { "fromAddr": "Indico Mailer<%s>"%HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail(), "toList": [self._user.getEmail()], "subject": _("[%s] Login Information")%getSubjectIndicoTitle(), "body": text }
        GenericMailer.send(GenericNotification(maildata))
 def getFromAddr(self):
     # TODO: There will be on "from address" from a conference, but what if there are more different conferences
     supEmail = self._psList[0].getConference().getSupportInfo().getEmail(returnNoReply=True)
     if self._forceIndicoFromAddress or supEmail.strip() == "":
         info = HelperMaKaCInfo.getMaKaCInfoInstance()
         return "%s <%s>".format(info.getTitle(), Config.getInstance().getSupportEmail())
     return supEmail
Beispiel #9
0
 def timezone(self):
     if '_timezone' in self:
         return self['_timezone']
     if '_avatarId' not in self:
         return 'LOCAL'
     with DBMgr.getInstance().global_connection():
         return HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
def _run(args):
    _setup(args)

    formatter = logging.Formatter("%(asctime)s %(name)s - %(levelname)s %(filename)s:%(lineno)s: %(message)s")

    root = logging.getLogger('')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    root.addHandler(handler)

    dbi = DBMgr.getInstance(max_disconnect_poll=40)
    dbi.startRequest()

    info = HelperMaKaCInfo.getMaKaCInfoInstance()
    useRBDB = info.getRoomBookingModuleActive()

    if useRBDB:
        DALManager.connect()

    sm = SchedulerModule.getDBInstance()
    t = sm.getTaskById(args.taskid)

    t.plugLogger(logging.getLogger('console.run/%s' % args.taskid))
    t.run()

    if useRBDB:
        DALManager.commit()
        DALManager.disconnect()
    dbi.endRequest()
Beispiel #11
0
 def getVars(self):
     vars = wcomponents.WTemplated.getVars(self)
     vars["mode"] = self._mode
     vars["isModeSelect"] = self._mode == Evaluation._SELECT_SUBMITTERS
     vars["submissions"] = self._conf.getEvaluation().getSubmissions()
     vars["utils"] = utils
     vars[
         "actionUrl"] = urlHandlers.UHConfModifEvaluationResultsSubmittersActions.getURL(
             self._conf)
     if self._mode == Evaluation._REMOVE_SUBMITTERS:
         vars["inputCheckboxName"] = "removedSubmitters"
         vars["inputSubmitStyle"] = 'style="color:#ee0000"'
         vars[
             "submitConfirm"] = """onsubmit="javascript:return confirmation();" """
     elif self._mode == Evaluation._SELECT_SUBMITTERS:
         vars["inputCheckboxName"] = "selectedSubmitters"
         vars["inputSubmitStyle"] = ''
         vars["submitConfirm"] = ''
     else:
         if HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive():
             raise Exception("Evaluation - unknown mode (given: %s)" %
                             self._mode)
         vars["inputCheckboxName"] = "unknownMode"
         vars["inputSubmitStyle"] = ''
         vars["submitConfirm"] = ''
     return vars
Beispiel #12
0
def _run(args):
    _setup(args)

    formatter = logging.Formatter(
        "%(asctime)s %(name)s - %(levelname)s %(filename)s:%(lineno)s: %(message)s"
    )

    root = logging.getLogger('')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    root.addHandler(handler)

    dbi = DBMgr.getInstance(max_disconnect_poll=40)
    dbi.startRequest()

    info = HelperMaKaCInfo.getMaKaCInfoInstance()
    useRBDB = info.getRoomBookingModuleActive()

    if useRBDB:
        DALManager.connect()

    sm = SchedulerModule.getDBInstance()
    t = sm.getTaskById(args.taskid)

    t.plugLogger(logging.getLogger('console.run/%s' % args.taskid))
    t.run()

    if useRBDB:
        DALManager.commit()
        DALManager.disconnect()
    dbi.endRequest()
Beispiel #13
0
def register_instance(contact, email):
    organisation = HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
    payload = {'url': Config.getInstance().getBaseURL(),
               'contact': contact,
               'email': email,
               'organisation': organisation}
    response = requests.post(_url, data=dumps(payload), headers=_headers, timeout=TIMEOUT)
    try:
        response.raise_for_status()
    except HTTPError as err:
        logger.error('failed to register the server to the community hub, got: %s', err.message)
        settings.set('joined', False)
        raise
    except Timeout:
        logger.error('failed to register: timeout while contacting the community hub')
        settings.set('joined', False)
        raise
    except RequestException as err:
        logger.error('unexpected exception while registering the server with the Community Hub: %s', err.message)
        raise

    json_response = response.json()
    if 'uuid' not in json_response:
        logger.error('invalid json reply from the community hub: uuid missing')
        settings.set('joined', False)
        raise ValueError('invalid json reply from the community hub: uuid missing')

    settings.set_multi({
        'joined': True,
        'uuid': json_response['uuid'],
        'contact_name': payload['contact'],
        'contact_email': payload['email']
    })
    logger.info('successfully registered the server to the community hub')
Beispiel #14
0
 def timezone(self):
     if '_timezone' in self:
         return self['_timezone']
     if '_avatarId' not in self:
         return 'LOCAL'
     with DBMgr.getInstance().global_connection():
         return HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
Beispiel #15
0
 def _process(self):
     if self._target.isClosed():
         p = conferences.WPConferenceModificationClosed(self, self._target)
     else:
         if (self._target.getId() == "default"):
             p = admins.WPPosterTemplateDesign(self, self._target,
                                               self.__templateId,
                                               self.__new)
         else:
             if self.__new == True and self.__baseTemplate != 'blank':
                 dconf = HelperMaKaCInfo.getMaKaCInfoInstance(
                 ).getDefaultConference()
                 templMan = self._target.getPosterTemplateManager()
                 newId = self.__templateId
                 dconf.getPosterTemplateManager().getTemplateById(
                     self.__baseTemplate).clone(templMan, newId)
                 url = urlHandlers.UHConfModifPosterPrinting().getURL(
                     self._target)
                 self._redirect(url)
                 return
             else:
                 p = conferences.WPConfModifPosterDesign(
                     self, self._target, self.__templateId, self.__new,
                     self.__baseTemplate)
     return p.display()
Beispiel #16
0
    def _process_POST(self):
        if User.has_rows():
            return redirect(url_for('misc.index'))
        setup_form = BootstrapForm(request.form)
        if not setup_form.validate():
            flash(_("Some fields are invalid. Please, correct them and submit the form again."), 'error')
            return redirect(url_for('bootstrap.index'))

        # Creating new user
        user = User()
        user.first_name = to_unicode(setup_form.first_name.data)
        user.last_name = to_unicode(setup_form.last_name.data)
        user.affiliation = to_unicode(setup_form.affiliation.data)
        user.email = to_unicode(setup_form.email.data)
        user.is_admin = True

        identity = Identity(provider='indico', identifier=setup_form.username.data, password=setup_form.password.data)
        user.identities.add(identity)

        db.session.add(user)
        db.session.flush()

        user.settings.set('timezone', Config.getInstance().getDefaultTimezone())
        user.settings.set('lang', to_unicode(setup_form.language.data))

        login_user(user, identity)
        full_name = user.full_name  # needed after the session closes

        transaction.commit()

        # Configuring server's settings
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        minfo.setOrganisation(setup_form.affiliation.data)
        minfo.setLang(setup_form.language.data)

        message = get_template_module('bootstrap/flash_messages.html').bootstrap_success(name=full_name)
        flash(Markup(message), 'success')

        # Activate instance tracking
        if setup_form.enable_tracking.data:
            contact_name = setup_form.contact_name.data
            contact_email = setup_form.contact_email.data

            try:
                register_instance(contact_name, contact_email)
            except (HTTPError, ValueError) as err:
                message = get_template_module('bootstrap/flash_messages.html').community_error(err=err)
                category = 'error'
            except Timeout:
                message = get_template_module('bootstrap/flash_messages.html').community_timeout()
                category = 'error'
            except RequestException as exc:
                message = get_template_module('bootstrap/flash_messages.html').community_exception(exc=exc)
                category = 'error'
            else:
                message = get_template_module('bootstrap/flash_messages.html').community_success()
                category = 'success'
            flash(Markup(message), category)

        return redirect(url_for('misc.index'))
Beispiel #17
0
    def _process_POST(self):
        if User.query.has_rows():
            return redirect(url_for_index())
        setup_form = BootstrapForm(request.form)
        if not setup_form.validate():
            flash(_("Some fields are invalid. Please, correct them and submit the form again."), 'error')
            return redirect(url_for('bootstrap.index'))

        # Creating new user
        user = User()
        user.first_name = to_unicode(setup_form.first_name.data)
        user.last_name = to_unicode(setup_form.last_name.data)
        user.affiliation = to_unicode(setup_form.affiliation.data)
        user.email = to_unicode(setup_form.email.data)
        user.is_admin = True

        identity = Identity(provider='indico', identifier=setup_form.username.data, password=setup_form.password.data)
        user.identities.add(identity)

        db.session.add(user)
        db.session.flush()

        user.settings.set('timezone', Config.getInstance().getDefaultTimezone())
        user.settings.set('lang', session.lang or Config.getInstance().getDefaultLocale())

        login_user(user, identity)
        full_name = user.full_name  # needed after the session closes

        transaction.commit()

        # Configuring server's settings
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        minfo.setOrganisation(setup_form.affiliation.data)

        message = get_template_module('bootstrap/flash_messages.html').bootstrap_success(name=full_name)
        flash(Markup(message), 'success')

        # Activate instance tracking
        if setup_form.enable_tracking.data:
            contact_name = setup_form.contact_name.data
            contact_email = setup_form.contact_email.data

            try:
                register_instance(contact_name, contact_email)
            except (HTTPError, ValueError) as err:
                message = get_template_module('bootstrap/flash_messages.html').community_error(err=err)
                category = 'error'
            except Timeout:
                message = get_template_module('bootstrap/flash_messages.html').community_timeout()
                category = 'error'
            except RequestException as exc:
                message = get_template_module('bootstrap/flash_messages.html').community_exception(exc=exc)
                category = 'error'
            else:
                message = get_template_module('bootstrap/flash_messages.html').community_success()
                category = 'success'
            flash(Markup(message), category)

        return redirect(url_for_index())
Beispiel #18
0
 def __init__(self):
     info = HelperMaKaCInfo.getMaKaCInfoInstance()
     self._plugin_asset_env = PluginEnvironment('Collaboration', os.path.dirname(__file__), '/Collaboration')
     self._plugin_asset_env.debug = info.isDebugActive()
     self._plugin_asset_env.register('collaboration', Bundle('js/Collaboration.js',
                                                                 'js/bookings.js',
                                                                 filters='rjsmin',
                                                                 output="Collaboration_%(version)s.min.js"))
Beispiel #19
0
 def lang(self):
     if '_lang' in self:
         return self['_lang']
     elif self.user:
         return self.user.getLang()
     else:
         with DBMgr.getInstance().global_connection():
             return HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
Beispiel #20
0
 def _process(self):
     language = HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
     stats = {
         'python_version': python_version(),
         'indico_version': MaKaC.__version__,
         'language': language
     }
     return jsonify(stats)
Beispiel #21
0
 def lang(self):
     if '_lang' in self:
         return self['_lang']
     elif self.user:
         return self.user.getLang()
     else:
         with DBMgr.getInstance().global_connection():
             return HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
Beispiel #22
0
    def __init__( self, rh ):
        config = Config.getInstance()
        db_connected = DBMgr.getInstance().isConnected()
        if db_connected:
            debug = HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive()
        else:
            debug = False

        self._rh = rh
        self._locTZ = ""

        url_path = urlparse(config.getBaseURL()).path

        self._asset_env = Environment(os.path.join(config.getHtdocsDir(), 'static', 'assets'),
                                      '{0}/static/assets/'.format(url_path))
        self._asset_env.config['PYSCSS_STATIC_URL'] = '{0}/static/'.format(url_path)
        self._asset_env.config['PYSCSS_LOAD_PATHS'] = [
            os.path.join(config.getHtdocsDir(), 'sass', 'lib', 'compass'),
            os.path.join(config.getHtdocsDir(), 'sass')
        ]
        self._asset_env.config['PYSCSS_DEBUG_INFO'] = debug and Config.getInstance().getSCSSDebugInfo()

        self._asset_env.append_path(config.getHtdocsDir(), '/')
        self._asset_env.append_path(os.path.join(config.getHtdocsDir(), 'css'), '{0}/css'.format(url_path))
        self._asset_env.append_path(os.path.join(config.getHtdocsDir(), 'js'), '{0}/js'.format(url_path))

        # This is done in order to avoid the problem sending the error report because the DB is not connected.
        if db_connected:
            info = HelperMaKaCInfo.getMaKaCInfoInstance()
            self._asset_env.debug = info.isDebugActive()

        self._dir = config.getTPLDir()
        self._asset_env.debug = debug

        if db_connected:
            css_file = config.getCssStylesheetName()
        else:
            css_file = 'Default.css'

        # register existing assets
        assets.register_all_js(self._asset_env)
        assets.register_all_css(self._asset_env, css_file)

        #store page specific CSS and JS
        self._extraCSS = []
        self._extraJS = []
Beispiel #23
0
def getSubjectIndicoTitle():
    minfo=HelperMaKaCInfo.getMaKaCInfoInstance()
    systitle="Indico"
    if minfo.getTitle().strip() != "":
        systitle=minfo.getTitle().strip()
    if minfo.getOrganisation().strip() != "":
        systitle="%s @ %s"%(systitle, minfo.getOrganisation().strip())
    return systitle
Beispiel #24
0
def getSubjectIndicoTitle():
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    systitle = "Indico"
    if minfo.getTitle().strip() != "":
        systitle = minfo.getTitle().strip()
    if minfo.getOrganisation().strip() != "":
        systitle = "%s @ %s" % (systitle, minfo.getOrganisation().strip())
    return systitle
Beispiel #25
0
    def send( self ):
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        name = self._user.getStraightFullName()
        text = """Dear Administrator,
%s has created a new account in Indico.
<%s>
""" % (name,urlHandlers.UHUserDetails.getURL( self._user ))
        maildata = { "fromAddr": "Indico Mailer<%s>" % minfo.getSupportEmail(), "toList": minfo.getAdminEmails(), "subject": _("[Indico] New account creation"), "body": text }
        GenericMailer.send(GenericNotification(maildata))
Beispiel #26
0
 def __init__(self, rh, templateClass):
     WPAdminPlugins.__init__(self, rh, 'livesync', '')
     self._templateClass = templateClass
     info = HelperMaKaCInfo.getMaKaCInfoInstance()
     self._plugin_asset_env = PluginEnvironment('livesync', os.path.dirname(__file__), '/livesync')
     self._plugin_asset_env.debug = info.isDebugActive()
     self._plugin_asset_env.register('livesync', Bundle('js/livesync.js',
                                                        filters='rjsmin',
                                                        output="livesync__%(version)s.min.js"))
Beispiel #27
0
 def __init__(self, rh, templateClass):
     WPAdminPlugins.__init__(self, rh, 'livesync', '')
     self._templateClass = templateClass
     info = HelperMaKaCInfo.getMaKaCInfoInstance()
     self._plugin_asset_env = PluginEnvironment('livesync', os.path.dirname(__file__), '/livesync')
     self._plugin_asset_env.debug = info.isDebugActive()
     self._plugin_asset_env.register('livesync', Bundle('js/livesync.js',
                                                        filters='rjsmin',
                                                        output="livesync__%(version)s.min.js"))
Beispiel #28
0
def _get_remote_ip(req):
    hostIP = str(req.get_remote_ip())

    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    if minfo.useProxy():
        # if we're behind a proxy, use X-Forwarded-For
        return req.headers_in.get("X-Forwarded-For", hostIP).split(", ")[-1]
    else:
        return hostIP
Beispiel #29
0
    def _process_GET(self):
        defaults = FormDefaults(**settings.get_all())
        form = CephalopodForm(request.form, obj=defaults)

        affiliation = HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
        enabled = settings.get('joined')
        instance_url = Config.getInstance().getBaseURL()
        language = HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
        tracker_url = urljoin(Config.getInstance().getTrackerURL(), 'api/instance/{}'.format(settings.get('uuid')))
        return WPCephalopod.render_template('cephalopod.html',
                                            affiliation=affiliation,
                                            enabled=enabled,
                                            form=form,
                                            indico_version=MaKaC.__version__,
                                            instance_url=instance_url,
                                            language=language,
                                            python_version=python_version(),
                                            tracker_url=tracker_url)
Beispiel #30
0
def _get_remote_ip(req):
    hostIP = str(req.get_remote_ip())

    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    if minfo.useProxy():
        # if we're behind a proxy, use X-Forwarded-For
        return req.headers_in.get("X-Forwarded-For", hostIP).split(", ")[-1]
    else:
        return hostIP
Beispiel #31
0
def validateSignature(ak, minfo, signature, timestamp, path, query):
    ttl = HelperMaKaCInfo.getMaKaCInfoInstance().getAPISignatureTTL()
    if not timestamp and not (ak.isPersistentAllowed() and minfo.isAPIPersistentAllowed()):
        raise HTTPAPIError('Signature invalid (no timestamp)', apache.HTTP_FORBIDDEN)
    elif timestamp and abs(timestamp - int(time.time())) > ttl:
        raise HTTPAPIError('Signature invalid (bad timestamp)', apache.HTTP_FORBIDDEN)
    digest = hmac.new(ak.getSignKey(), normalizeQuery(path, query), hashlib.sha1).hexdigest()
    if signature != digest:
        raise HTTPAPIError('Signature invalid', apache.HTTP_FORBIDDEN)
Beispiel #32
0
 def __init__(self):
     self._newsItems = []
     self._p_changed = 1
     self._newsCounter = Counter()
     self._recentDays = 14  #days to keep a 'New' tag on recent news items
     # fetch all news from the previous location.
     self.addNewsItem(
         NewsItem(_("Previous news"),
                  HelperMaKaCInfo.getMaKaCInfoInstance().getNews(),
                  "general"))
Beispiel #33
0
 def __init__(self, booking):
     GenericNotification.__init__(self)
     self._booking = booking
     self._bp = booking._bookingParams
     self._conference = booking.getConference()
     
     self._modifLink = str(booking.getModificationURL())
     
     self.setFromAddr("Indico Mailer<%s>"%HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
     self.setContentType("text/html")
Beispiel #34
0
    def _process_GET(self):
        defaults = FormDefaults(**settings.get_all())
        form = CephalopodForm(request.form, obj=defaults)

        affiliation = HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
        enabled = settings.get('joined')
        instance_url = Config.getInstance().getBaseURL()
        language = HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
        tracker_url = urljoin(Config.getInstance().getTrackerURL(),
                              'api/instance/{}'.format(settings.get('uuid')))
        return WPCephalopod.render_template('cephalopod.html',
                                            affiliation=affiliation,
                                            enabled=enabled,
                                            form=form,
                                            indico_version=MaKaC.__version__,
                                            instance_url=instance_url,
                                            language=language,
                                            python_version=python_version(),
                                            tracker_url=tracker_url)
Beispiel #35
0
def ip_based_acl(dbi, withRBDB, prevVersion):
    """
    Moving from OAI Private Harvesting to a more general IP-based ACL.
    """
    from MaKaC.common.info import IPBasedACLMgr
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    ip_set = set(minfo._oaiPrivateHarvesterList)
    ip_acl_mgr = minfo._ip_based_acl_mgr = IPBasedACLMgr()
    ip_acl_mgr._full_access_acl = ip_set
    dbi.commit()
Beispiel #36
0
    def send( notification ):
        info = HelperMaKaCInfo.getMaKaCInfoInstance()
        fromAddr = "%s <%s>"%(info.getTitle(), info.getSupportEmail())
        toAddr = str(notification.getDestination().getEmail())
        text = """%s
-- 
Indico project <http://cern.ch/indico>
                """%(notification.getMsg())
        maildata = { "fromAddr": fromAddr, "toList": [toAddr], "subject": "[Indico] %s"%notification.getSubject(), "body": text }
        GenericMailer.send(GenericNotification(maildata))
Beispiel #37
0
def ip_based_acl(dbi, withRBDB, prevVersion):
    """
    Moving from OAI Private Harvesting to a more general IP-based ACL.
    """
    from MaKaC.common.info import IPBasedACLMgr
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    ip_set = set(minfo._oaiPrivateHarvesterList)
    ip_acl_mgr = minfo._ip_based_acl_mgr = IPBasedACLMgr()
    ip_acl_mgr._full_access_acl = ip_set
    dbi.commit()
Beispiel #38
0
def sync_instance(contact, email):
    contact = contact or settings.get('contact_name')
    email = email or settings.get('contact_email')
    # registration needed if the instance does not have a uuid
    if not settings.get('uuid'):
        logger.warn(
            'unable to synchronise: missing uuid, registering the server instead'
        )
        register_instance(contact, email)
        return

    organisation = HelperMaKaCInfo.getMaKaCInfoInstance().getOrganisation()
    payload = {
        'enabled': True,
        'url': Config.getInstance().getBaseURL(),
        'contact': contact,
        'email': email,
        'organisation': organisation
    }
    url = urljoin(_url, settings.get('uuid'))
    response = requests.patch(url,
                              data=dumps(payload),
                              headers=_headers,
                              timeout=TIMEOUT)
    try:
        response.raise_for_status()
    except HTTPError as err:
        if err.response.status_code == 404:
            logger.warn(
                'unable to synchronise: the server was not registered, registering the server now'
            )
            register_instance(contact, email)
        else:
            logger.error(
                'failed to synchronise the server with the community hub, got: %s',
                err.message)
            raise
    except Timeout:
        logger.error(
            'failed to synchronise: timeout while contacting the community hub'
        )
        raise
    except RequestException as err:
        logger.error(
            'unexpected exception while synchronizing the server with the Community Hub: %s',
            err.message)
        raise
    else:
        settings.set_multi({
            'joined': True,
            'contact_name': payload['contact'],
            'contact_email': payload['email']
        })
        logger.info(
            'successfully synchronized the server with the community hub')
Beispiel #39
0
 def includeTimetableCSSFiles(cls, obj, params={}):
     """
     Includes additional Css files.
     """
     info = HelperMaKaCInfo.getMaKaCInfoInstance()
     asset_env = PluginEnvironment('importer', os.path.dirname(__file__), 'importer')
     asset_env.debug = info.isDebugActive()
     asset_env.register('importer_css', Bundle('css/importer.css',
                                               filters='cssmin',
                                               output="importer__%(version)s.min.css"))
     params['paths'].extend(asset_env['importer_css'].urls())
    def __init__(self, user, judgement, contribution):
        GenericNotification.__init__(self)
        self.setFromAddr(
            "Indico Mailer<%s>" %
            HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
        self.setToList([user.getEmail()])

        if isinstance(judgement, EditorJudgement):
            self.setSubject(
                """[Indico] The layout of your contribution "%s" (id: %s) has been reviewed"""
                % (contribution.getTitle(), str(contribution.getId())))
            self.setBody("""Dear Indico user,
        
        The layout of your contribution "%s" (id: %s) has been reviewed.
        The judgement was: %s
        
        The comments of the editor were:
        "%s"
        
        Thank you for using our system.
        """ % (contribution.getTitle(), str(contribution.getId()),
               judgement.getJudgement(), judgement.getComments()))

        elif isinstance(judgement, ReviewerJudgement):
            self.setSubject(
                """[Indico] The content of your contribution "%s" (id: %s) has been reviewed"""
                % (contribution.getTitle(), str(contribution.getId())))
            self.setBody("""Dear Indico user,
        
        The content of your contribution "%s" (id: %s) has been reviewed.
        The judgement was: %s
        
        The comments of the reviewer were:
        "%s"
        
        Thank you for using our system.
        """ % (contribution.getTitle(), str(contribution.getId()),
               judgement.getJudgement(), judgement.getComments()))

        elif isinstance(judgement, RefereeJudgement):
            self.setSubject(
                """[Indico] Your contribution "%s" (id: %s) has been completely reviewed by the referee"""
                % (contribution.getTitle(), str(contribution.getId())))
            self.setBody("""Dear Indico user,
        
        Your contribution "%s" (id: %s) has been completely reviewed by the assigned referee.
        The judgement was: %s
        
        The comments of the referee were:
        "%s"
        
        Thank you for using our system.
        """ % (contribution.getTitle(), str(contribution.getId()),
               judgement.getJudgement(), judgement.getComments()))
Beispiel #41
0
    def send( self ):
        minfo=HelperMaKaCInfo.getMaKaCInfoInstance()
        text =  _("""Welcome to Indico,
Your registration has been accepted by the site administrator.

You can now login using the following username: %s

Thank you for using Indico.
                """)%(self._user.getIdentityList()[0].getLogin())
        maildata = { "fromAddr": "Indico Mailer<%s>"%minfo.getSupportEmail(), "toList": [self._user.getEmail()], "subject": _("[%s] Registration accepted")%getSubjectIndicoTitle(), "body": text }
        GenericMailer.send(GenericNotification(maildata))
Beispiel #42
0
def buildAW(ak, req, onlyPublic=False):
    aw = AccessWrapper()
    if ak and not onlyPublic:
        # If we have an authenticated request, require HTTPS
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        # Dirty hack: Google calendar converts HTTP API requests from https to http
        # Therefore, not working with Indico setup (requiring https for HTTP API authenticated)
        if not req.is_https() and minfo.isAPIHTTPSRequired() and req.get_user_agent().find("Googlebot") == -1:
            raise HTTPAPIError('HTTPS is required', apache.HTTP_FORBIDDEN)
        aw.setUser(ak.getUser())
    return aw
Beispiel #43
0
 def readFile(self, id):
     filePath = self.__getFilePath(id)
     try:
         with open(filePath, 'rb') as f:
             return f.read()
     except IOError:
         # In debugging we return an empty file instead of throwing an error
         from MaKaC.common.info import HelperMaKaCInfo
         if not HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive():
             raise
         return ''
Beispiel #44
0
 def includeTimetableJSFiles(cls, obj, params={}):
     """
     Includes additional javascript file.
     """
     info = HelperMaKaCInfo.getMaKaCInfoInstance()
     asset_env = PluginEnvironment('ictp_xlsimporter', os.path.dirname(__file__), '/ictp_xlsimporter')
     asset_env.debug = info.isDebugActive()
     asset_env.register('ictp_xlsimporter_js', Bundle('js/ictp_xlsimporter.js',
                                              filters='rjsmin',
                                              output="ictp_xlsimporter__%(version)s.min.js"))
     params['paths'].extend(asset_env['ictp_xlsimporter_js'].urls())
Beispiel #45
0
def buildAW(ak, onlyPublic=False):
    aw = AccessWrapper()
    if ak and not onlyPublic:
        # If we have an authenticated request, require HTTPS
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        # Dirty hack: Google calendar converts HTTP API requests from https to http
        # Therefore, not working with Indico setup (requiring https for HTTP API authenticated)
        if not request.is_secure and minfo.isAPIHTTPSRequired() and request.user_agent.browser != 'google':
            raise HTTPAPIError('HTTPS is required', 403)
        aw.setUser(ak.getUser())
    return aw
Beispiel #46
0
    def _sendErrorEmail(self, e):
        ty, ex, tb = sys.exc_info()
        tracebackList = traceback.format_list( traceback.extract_tb( tb ) )
        sm = sendMail()
        sm.setFromAddr(HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
        sm.addToAddr(HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
        sm.setSubject("[Indico] Error running a task")
        sm.setText("""

                    - Details of the exception: 
                        %s

                    - Traceback:

                        %s

                    --

                    <Indico support> indico-project @ cern.ch
                    """%(e, "\n".join( tracebackList )) )
        sm.run()
Beispiel #47
0
 def getVars(self):
     minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
     apiMode = minfo.getAPIMode()
     vars = WTemplated.getVars(self)
     vars['avatar'] = self._avatar
     vars['apiKey'] = self._avatar.getAPIKey()
     vars['isAdmin'] = self._rh._getUser().isAdmin()
     vars['signingEnabled'] = apiMode in (API_MODE_SIGNED, API_MODE_ONLYKEY_SIGNED, API_MODE_ALL_SIGNED)
     vars['persistentAllowed'] = minfo.isAPIPersistentAllowed()
     vars['apiPersistentEnableAgreement'] = minfo.getAPIPersistentEnableAgreement()
     vars['apiPersistentDisableAgreement'] = minfo.getAPIPersistentDisableAgreement()
     return vars
Beispiel #48
0
    def __init__(self, booking):
        GenericNotification.__init__(self)
        self._booking = booking
        self._bp = booking._bookingParams
        self._conference = booking.getConference()

        self._modifLink = str(booking.getModificationURL())

        self.setFromAddr(
            "Indico Mailer<%s>" %
            HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
        self.setContentType("text/html")
Beispiel #49
0
    def includeMainJSFiles(self, obj, params={}):
        """
        Includes additional javascript file.
        """
        info = HelperMaKaCInfo.getMaKaCInfoInstance()
        asset_env = PluginEnvironment('search', os.path.dirname(__file__), '/search')
        asset_env.debug = info.isDebugActive()

        asset_env.register('search', Bundle('js/search.js',
                                                           filters='rjsmin',
                                                           output="search__%(version)s.min.js"))
        params['paths'].extend(asset_env['search'].urls())
Beispiel #50
0
 def getVars(self):
     minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
     apiMode = minfo.getAPIMode()
     vars = WTemplated.getVars(self)
     vars['avatar'] = self._avatar
     vars['apiKey'] = self._avatar.getAPIKey()
     vars['isAdmin'] = self._rh._getUser().isAdmin()
     vars['signingEnabled'] = apiMode in (API_MODE_SIGNED, API_MODE_ONLYKEY_SIGNED, API_MODE_ALL_SIGNED)
     vars['persistentAllowed'] = minfo.isAPIPersistentAllowed()
     vars['apiPersistentEnableAgreement'] = minfo.getAPIPersistentEnableAgreement()
     vars['apiPersistentDisableAgreement'] = minfo.getAPIPersistentDisableAgreement()
     return vars
Beispiel #51
0
    def _sendErrorEmail(self, e):
        ty, ex, tb = sys.exc_info()
        tracebackList = traceback.format_list(traceback.extract_tb(tb))
        sm = sendMail()
        sm.setFromAddr(
            HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
        sm.addToAddr(HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
        sm.setSubject("[Indico] Error running a task")
        sm.setText("""

                    - Details of the exception: 
                        %s

                    - Traceback:

                        %s

                    --

                    <Indico support> indico-project @ cern.ch
                    """ % (e, "\n".join(tracebackList)))
        sm.run()
Beispiel #52
0
 def getVars(self):
     minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
     vars = WTemplated.getVars(self)
     vars['apiMode'] = minfo.getAPIMode()
     vars['httpsRequired'] = minfo.isAPIHTTPSRequired()
     vars['persistentAllowed'] = minfo.isAPIPersistentAllowed()
     vars['apiCacheTTL'] = minfo.getAPICacheTTL()
     vars['apiSignatureTTL'] = minfo.getAPISignatureTTL()
     vars['apiPersistentEnableAgreement'] = minfo.getAPIPersistentEnableAgreement()
     vars['apiPersistentDisableAgreement'] = minfo.getAPIPersistentDisableAgreement()
     vars['apiKeyUserAgreement'] = minfo.getAPIKeyUserAgreement()
     vars['apiPersistentUserAgreement'] = minfo.getAPIPersistentUserAgreement()
     return vars
Beispiel #53
0
def buildAW(ak, onlyPublic=False):
    aw = AccessWrapper()
    aw.setIP(str(request.remote_addr))
    if ak and not onlyPublic:
        # If we have an authenticated request, require HTTPS
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        # Dirty hack: Google calendar converts HTTP API requests from https to http
        # Therefore, not working with Indico setup (requiring https for HTTP API authenticated)
        if not request.is_secure and minfo.isAPIHTTPSRequired(
        ) and request.user_agent.browser != 'google':
            raise HTTPAPIError('HTTPS is required', 403)
        aw.setUser(ak.getUser())
    return aw
Beispiel #54
0
def user_revoke(user_id):
    """Revokes administration rights from a given user"""
    avatar = AvatarHolder().getById(user_id)
    if avatar is None:
        error("The user does not exists")
        return
    print_user_info(avatar)
    if not avatar.isAdmin():
        warning("This user does not have administration rights")
        return
    if prompt_bool(cformat("%{yellow}Revoke administration rights from this user?")):
        admin_list = HelperMaKaCInfo.getMaKaCInfoInstance().getAdminList()
        admin_list.revoke(avatar)
        success("Administration rights revoked successfully")