コード例 #1
0
    def __call__(self):
        """Confirm the code or render the form."""
        
        # make sure we have the form marker interface when testing
        z2.switch_on(self)
        
        if self.confirm_code:
            # confirm/delete nonce
            nonce_store = getUtility(INonceManager)
            try:
                email = nonce_store.retrieve(self.confirm_code)
            except KeyError:
                self.status = _(u'Sorry, your confirmation code is invalid or has expired.')
            else:
                # set up session
                session = ISession(self.request)
                session['collective.confirm_email.confirmed'] = True
                session['collective.confirm_email.email'] = email
                session.save()
            
                # redirect back to target (by removing last 2 parts of path)
                raise Redirect(self.request['URL2'])

        # render form
        return super(EmailConfirmationForm, self).__call__()
コード例 #2
0
ファイル: validate.py プロジェクト: educorvi/edi.skillpill
 def __call__(self):
     antworten = self.context.antworten
     uid = self.context.UID()
     yours = int(self.request.get(uid))
     success = False
     validated = []
     for i in antworten:
         index = antworten.index(i)
         i['btnclass'] = 'btn btn-secondary btn-sm btn-block'
         if i.get('bewertung') in ['richtig', 'success']:
             i['btnclass'] = 'btn btn-success btn-sm btn-block'
         if index == yours:
             i['yours'] = True
             if i.get('bewertung') in ['richtig', 'success']:
                 success = True
             else:
                 i['btnclass'] = 'btn btn-danger btn-sm btn-block'
         else:
             i['yours'] = False
         validated.append(i)
     cookie = {'success': success, 'validated': validated}
     session = ISession(self.request)
     if uid not in session:
         session[uid] = cookie
         session.save()
     url = "%s%s" % (self.context.absolute_url(), '#ergebnis')
     return self.request.response.redirect(url)
コード例 #3
0
def getSessionData(request):
    """
    Liest das SessionCookie
    """
    session = ISession(request)
    mongo_objid = session.get('key', '')
    client = MongoClient(mongoserver, mongoport)
    db = client.hh_database
    collection = db.hh_collection
    if mongo_objid:
        print 'lesen: ', mongo_objid
        data = collection.find_one({"_id": mongo_objid})
    else:
        data = {
            'hhlpan': False,
            'taetigkeit': {},
            'chemiesuche': {},
            'cbsuche': {},
            'mechaniksuche': {},
            'schutzhandschuhe': [],
            'hautschutz': [],
            'hautreinigung': [],
            'hautpflege': [],
            'desinfektion': [],
            'hautschutzplan': {}
        }
    return data
コード例 #4
0
 def get(self, portal, key=None):
     cart_id = 'groundwire.checkout.cart.%s' % '/'.join(portal.getPhysicalPath())
     session = ISession(getRequest())
     if cart_id not in session:
         session[cart_id] = ShoppingCart()
         session.save()
     return session[cart_id]
コード例 #5
0
 def getEditorSession(self, key=None):
     session_id = 'editlayout.%s' % SESSION_KEY
     session = ISession(getRequest())
     if session_id not in session:
         session[session_id] = dict()
         session.save()
     return session[session_id]
コード例 #6
0
ファイル: cart.py プロジェクト: kreativkombinat/cs-shop
 def destroy(self, portal, key=None):
     cart_id = 'kk.shopified.cart.%s' % '/'.join(
         portal.getPhysicalPath())
     session = ISession(getRequest())
     if cart_id in session:
         del session[cart_id]
         session.save()
コード例 #7
0
ファイル: card.py プロジェクト: educorvi/bgetem.medienshop
def setCartCookie(cookie, request):
    """
    Schreibt das Cookie in die Session
    """
    session = ISession(request)
    session['cart'] = cookie
    session.save()
コード例 #8
0
ファイル: cart.py プロジェクト: kreativkombinat/cs-shop
 def get(self, portal, key=None):
     cart_id = 'kk.shopified.cart.%s' % '/'.join(
         portal.getPhysicalPath())
     session = ISession(getRequest())
     if cart_id not in session:
         session[cart_id] = dict()
         session.save()
     return session[cart_id]
コード例 #9
0
ファイル: surveytool.py プロジェクト: vwc/buildout.locomotec
 def destroy(self, key=None):
     survey_id = 'survey.%s' % SESSION_KEY
     if key is not None:
         survey_id = 'survey.%s' % key
     session = ISession(getRequest())
     if survey_id in session:
         del session[survey_id]
         session.save()
コード例 #10
0
ファイル: surveytool.py プロジェクト: vwc/buildout.locomotec
 def get(self, key=None):
     survey_id = 'survey.%s' % SESSION_KEY
     if key is not None:
         survey_id = 'survey.%s' % key
     session = ISession(getRequest())
     if survey_id not in session:
         session[survey_id] = dict()
         session.save()
     return session[survey_id]
コード例 #11
0
ファイル: plugin.py プロジェクト: erral/cs.auth.googleplus
    def resetCredentials(self, request, response):
        """This method is called if the user logs out.
Here, we simply destroy their session.
"""
        session = ISession(request, None)
        if session is None:
            return

        session.delete()
コード例 #12
0
ファイル: tests.py プロジェクト: collective/collective.beaker
    def test_invalidated(self):
        provideAdapter(testingSession)

        request = TestRequest()
        session = ISession(request)

        self.assertEquals(False, session._invalidated)
        session.invalidate()
        self.assertEquals(True, session._invalidated)
コード例 #13
0
def confirm_email(self):
    # if the session has been confirmed, do nothing
    session = ISession(self.request)
    if session.get('collective.confirm_email.confirmed'):
        return

    # if it hasn't, redirect to the confirmation page
    url = self.request['URL']
    raise Redirect(url + '/@@confirm-email')
コード例 #14
0
    def resetCredentials(self, request, response):
        """This method is called if the user logs out.
Here, we simply destroy their session.
"""
        session = ISession(request, None)
        if session is None:
            return

        session.delete()
コード例 #15
0
    def render(self):
        session = ISession(self.request, None)

        if 'testsessionkey' in self.request:
            session['testsessionkey'] = dict(key1='Hey', key2='Boy')
            session.save()
            return 'Test key stored...'

        if 'testsessionkey2' in self.request:
            session['testsessionkey2'] = dict(key1='Hey', key2='Boy')
            session.save()
            return 'Test key2 stored...'


        if 'remove' in self.request:
            session.delete()
            session.invalidate()
            return 'Session removed and destroyed...'

        if session is None:
            return 'No session initiatied'
        if 'testsessionkey' in session:
            return 'Found session: ' + str(session)
        else:
            return 'Did not find testsessionkey in session...'
コード例 #16
0
ファイル: utils.py プロジェクト: kreativkombinat/kk.shopified
def redirect_to_checkout():
    site = getSite()
    request = getRequest()
    session = ISession(request)
    session.save()
    registry = getUtility(IRegistry)
    settings = registry.forInterface(IShopifiedSettings)
    shop_url = settings.shop_url
    portal_url = site.absolute_url()
    url = portal_url + shop_url + '/@@checkout'
    request.response.redirect(url)
コード例 #17
0
ファイル: tool.py プロジェクト: a25kk/hfph
 def destroy(key=None):
     """ Destroy module filter session """
     portal = api.portal.get()
     session_id = 'hph.lectures.filter.{0}'.format(
         '.'.join(portal.getPhysicalPath())
     )
     if key:
         session_id = 'hph.lectures.filter.{0}'.format(key)
     session = ISession(getRequest())
     if session_id in session:
         del session[session_id]
         session.save()
コード例 #18
0
ファイル: tests.py プロジェクト: collective/collective.beaker
    def test_get_del(self):
        provideAdapter(testingSession)

        request = TestRequest()
        session = ISession(request)
        session['foo'] = 'bar'

        self.assertEquals('bar', session['foo'])
        del session['foo']
        self.failIf('foo' in session)

        self.failIf(session.last_accessed is None)
        self.assertEquals(True, session.accessed())
コード例 #19
0
    def update(self):
        ''' Nothing
        '''
        # import pdb; pdb.set_trace()
        logger.debug('Generating view for kollkoll')
        kollkoll = Kollkoll()

        pid = get_pid()
        self.result = kollkoll.listCards(pid)

        session = ISession(self.request, None)
        session[SessionKeys.available_cards] = self.result
        session.save()
コード例 #20
0
ファイル: tool.py プロジェクト: a25kk/hfph
 def get(key=None):
     """ Create module filter session """
     portal = api.portal.get()
     session_id = 'hph.lectures.filter.{0}'.format(
         '.'.join(portal.getPhysicalPath())
     )
     if key:
         session_id = 'hph.lectures.filter.{0}'.format(key)
     session = ISession(getRequest())
     if session_id not in session:
         session[session_id] = dict()
         session.save()
     return session[session_id]
コード例 #21
0
ファイル: tests.py プロジェクト: collective/collective.beaker
    def test_accessed_contains(self):
        provideAdapter(testingSession)

        request = TestRequest()
        session = ISession(request)

        self.assertEquals(None, session.last_accessed)
        self.assertEquals(False, session.accessed())

        'foo' in session

        self.failIf(session.last_accessed is None)
        self.assertEquals(True, session.accessed())
コード例 #22
0
ファイル: tests.py プロジェクト: collective/collective.beaker
    def test_accessed_setdefault(self):
        provideAdapter(testingSession)

        request = TestRequest()
        session = ISession(request)

        self.assertEquals(None, session.last_accessed)
        self.assertEquals(False, session.accessed())

        session.setdefault('foo', 'bar')

        self.failIf(session.last_accessed is None)
        self.assertEquals(True, session.accessed())
コード例 #23
0
ファイル: views.py プロジェクト: Adniel/hejasverige.kollkoll
    def update(self):
        ''' Nothing
        '''
        # import pdb; pdb.set_trace()
        logger.debug('Generating view for kollkoll')
        kollkoll = Kollkoll()

        pid = get_pid()
        self.result = kollkoll.listCards(pid)

        session = ISession(self.request, None)
        session[SessionKeys.available_cards] = self.result
        session.save()
コード例 #24
0
ファイル: tests.py プロジェクト: collective/collective.beaker
 def __call__(self):
     session = ISession(self.request)
     if 'reset' in self.request:
         session['testCounter'] = 0
         session.save()
     if 'increment' in self.request:
         session['testCounter'] += 1
         session.save()
     if 'invalidate' in self.request:
         session.invalidate()
     if 'delete' in self.request:
         session.delete()
     return str(session.get('testCounter', -1))
コード例 #25
0
def getSessionData(request):
    """
    Liest das SessionCookie
    """
    session = ISession(request)
    mongo_objid = session.get('key', '')
    client = get_mongo_client().client
    db = client.mp_database
    collection = db.mp_collection
    if mongo_objid:
        data = collection.find_one({"_id":mongo_objid})
    else:
        data = {}
    return data
コード例 #26
0
ファイル: bank.py プロジェクト: Adniel/hejasverige.megabank
    def getAccount(self, personalid, context=None):

        #/accounts/<pid>
        #
        #{
        #    "AccountNumber":"String content",
        #    "AccountTypeID":2147483647,
        #    "AmountAvailable":12678967.543233,
        #    "AmountPending":12678967.543233,
        #    "AmountReserved":12678967.543233,
        #    "Balance":12678967.543233,
        #    "Cards":[{
        #        "AccountID":2147483647,
        #        "AccountPersonalID":"String content",
        #        "CardNumber":"String content",
        #        "Created":"\/Date(928142400000+0200)\/",
        #        "ID":2147483647,
        #        "PersonalID":"String content"
        #    }],
        #    "ID":2147483647,
        #    "Limit":12678967.543233,
        #    "Name":"String content",
        #    "PersonalID":"String content",
        #    "Temporary":true
        #}
        # If a context is provided. Try to return values from a cookie.
        # If no cookie is found collect new values
        if context:
            session = ISession(context.request, None)
            if session:
                account_info = {}
                # import pdb; pdb.set_trace()
                try: 
                    account_info = session[SessionKeys.account_info]

                    # is there content in key?
                    if not account_info:
                        raise KeyError

                    # check if session cache is expired
                    if datetime.datetime.now() > (account_info['_created'] + datetime.timedelta(seconds=self.cachetimeout)):
                        raise KeyError

                except KeyError, ex:
                    account_info = self.getAccountFromMegabank(personalid)
                    account_info['_created'] = datetime.datetime.now()
                    session[SessionKeys.account_info] = account_info
                    session.save()

                return session[SessionKeys.account_info]
コード例 #27
0
 def __call__(self):
     session = ISession(self.request)
     order_id = session.get('groundwire.checkout.order_id', None)
     if order_id is not None:
         order_manager = getUtility(IOrderManager)
         order = order_manager.get(order_id)
         self.cart = order.shopping_cart
         if 'getpaid.processor.uid' in order.__annotations__:
             self.txn_id = order.__annotations__['getpaid.processor.uid']
         else:
             self.txn_id = None
             
         del session['groundwire.checkout.order_id']
         session.save()
     return self.index()
コード例 #28
0
ファイル: plugin.py プロジェクト: erral/cs.auth.googleplus
    def extractCredentials(self, request):
        """This method is called on every request to extract credentials.
In our case, that means looking for the values we store in the
session.
o Return a mapping of any derived credentials.
o Return an empty mapping to indicate that the plugin found no
appropriate credentials.
"""

        # Get the session from Beaker.

        session = ISession(request, None)

        if session is None:
            return None

        # We have been authenticated and we have a session that has not yet
        # expired:

        if SessionKeys.userId in session:

            return {
                'src': self.getId(),
                'userid': session[SessionKeys.userId],
                'username': session[SessionKeys.userId],
            }

        return None
コード例 #29
0
ファイル: skill_view.py プロジェクト: educorvi/edi.skillpill
 def get_validated(self):
     validated = {}
     uid = self.context.UID()
     session = ISession(self.request)
     if uid in session:
         validated = session[uid]['validated']
     return validated
コード例 #30
0
 def test_getSessionData(self):
     sdm = self._makeOne()
     data = sdm.getSessionData()
     from Products.BeakerSessionDataManager.interfaces import ISessionDataObject
     self.assertTrue(ISessionDataObject.providedBy(data))
     from collective.beaker.interfaces import ISession
     self.assertTrue(ISession.providedBy(data.session))
コード例 #31
0
 def test_getSessionData(self):
     sdm = self._makeOne()
     data = sdm.getSessionData()
     from Products.BeakerSessionDataManager.interfaces import ISessionDataObject
     self.assertTrue(ISessionDataObject.providedBy(data))
     from collective.beaker.interfaces import ISession
     self.assertTrue(ISession.providedBy(data.session))
コード例 #32
0
def delSessionData(request):
    """
    Loescht das Cookie
    """
    data = {'hhlpan':False,
            'taetigkeit':{},
            'chemiesuche':{},
            'mechaniksuche':{},
            'schutzhandschuhe':[],
            'hautschutz':[],
            'hautreinigung':[],
            'hautpflege':[],
            'desinfektion':[],
            'hautschutzplan':{}}
    insert = setSessionData(request, data)
    session = ISession(request)
    session.delete()
コード例 #33
0
ファイル: card.py プロジェクト: educorvi/bgetem.medienshop
def getCartCookie(request):
    """
    Liest das SessionCookie
    """
    session = ISession(request)
    cart_default = {}  #leere Artikelliste
    cookie = session.get('cart', cart_default)
    delkeys = []
    for i in cookie:
        try:
            if int(cookie[i]['menge']) <= 0:
                delkeys.append(i)
        except:
            print i
    for i in delkeys:
        del cookie[i]
    return cookie
コード例 #34
0
ファイル: klassenraum.py プロジェクト: educorvi/edi.classroom
 def checkpin(self, request):
     check = False
     uid = self.UID()
     session = ISession(request)
     if uid in session:
         checkpin = session[uid]
         check = self.compare_pin(checkpin)
     return check
コード例 #35
0
    def render(self):
        session = ISession(self.request, None)

        if session is None:
            return None

        if SessionKeys.selected_amount not in session:
            logger.info('SessionKey %s not present in session. Initating with 0...' % SessionKeys.selected_amount)
            session[SessionKeys.selected_amount] = 0
            session.save()

        if SessionKeys.selected_invoices not in session:
            logger.info('SessionKey %s not present in session. Initating empty list...' % SessionKeys.selected_invoices)
            session[SessionKeys.selected_invoices] = []
            session.save()

        logger.info('Hey, I received a call...')
        if 'checkboxid' in self.request:
            logger.info('Checkbox id:' + self.request['checkboxid'])

        if 'checkboxvalue' in self.request:
            logger.info('Checkbox value:' + self.request['checkboxvalue'])

        if 'invoiceno' in self.request:
            logger.info('Invoiceno value:' + self.request['invoiceno'])

        if 'description' in self.request:
            logger.info('Description value:' + self.request['description'])

        if 'Amount' in self.request:
            logger.info('Amount value:' + self.request['amount'])
        # Update session dictionary
        #import pdb;pdb.set_trace()
        try:
            amount = float(self.request['amount'])
        except:
            amount = 0

        #import pdb; pdb.set_trace()

        if self.request['checkboxvalue'] == 'true':
            session[SessionKeys.selected_amount] = session[SessionKeys.selected_amount] + amount

            if not self.request['checkboxid'] in [l.get('id') for l in session[SessionKeys.selected_invoices]]:
                session[SessionKeys.selected_invoices].append(dict(id=self.request['checkboxid'], description=self.request['description'], amount=amount, invoiceno=self.request['invoiceno']))
                logger.debug(session[SessionKeys.selected_invoices])
        else:
            session[SessionKeys.selected_amount] = session[SessionKeys.selected_amount] - amount
            session[SessionKeys.selected_invoices] = [x for x in session[SessionKeys.selected_invoices] if x.get('id', None) != self.request['checkboxid']]

        #import pdb; pdb.set_trace()
        try:
            session.save()
            logger.debug("Session saved...")
        except:
            logger.exception("Session not saved!")
        #session['megabank.selectedamount'] =

        return str(session[SessionKeys.selected_amount])
コード例 #36
0
 def handleApply(self, action):
     data, errors = self.extractData()
     if not errors:
         checkmember = self.context.chatmember(data.get('chatpin'))
         if not checkmember:
             errormsg = u"Der eingegebene PIN ist leider nicht gültig"
             ploneapi.portal.show_message(message=errormsg,
                                          request=self.request,
                                          type='error')
             url = self.context.absolute_url() + '/chat-pin'
             return self.request.response.redirect(url)
         else:
             session = ISession(self.request)
             uid = self.context.UID()
             chatid = "chat_%s" % uid
             session[chatid] = checkmember
             session.save()
             url = self.context.absolute_url() + '/@@chatroom/'
             return self.request.response.redirect(url)
コード例 #37
0
ファイル: security.py プロジェクト: zenoss/zenoss-prodbin
    def _setAuthorizationCookie(self):
        session = ISession(self.context.REQUEST)
        authorization = IAuthorizationTool(self.context)
        token = authorization.createAuthToken(self.request)

        self.request.response.setCookie(ZAUTH_COOKIE,
                                        token['id'],
                                        path="/",
                                        secure=session.secure,
                                        http_only=True)
コード例 #38
0
ファイル: klassenraum.py プロジェクト: educorvi/edi.classroom
 def checkchat(self, request):
     check = False
     uid = self.UID()
     chatid = 'chat_%s' % uid
     session = ISession(request)
     if chatid in session:
         checkmember = session[chatid]
         chatmember = self.chatmember(checkmember)
         if chatmember:
             check = True
     return check
コード例 #39
0
def dispatchPaymentEvents(order, event):
    if order.finance_state != event.destination:
        return
    if order.finance_state == workflow_states.order.finance.CHARGED:
        # Record order_id in session so it can be found
        # by the confirmation view
        request = getRequest()
        session = ISession(request)
        session['groundwire.checkout.order_id'] = order.order_id
        session.save()

        for item in order.shopping_cart.values():
            if hasattr(item, 'after_charged'):
                item.after_charged()

        # Make sure pfg.donationform uses our order confirmation view
        if IDonationCart and IDonationCart.providedBy(order.shopping_cart):
            if getattr(request, 'pfg.donationform_suppress_confirmation', False):
                return

            portal_url = getSite().absolute_url()
            getRequest().response.redirect(portal_url + '/order-confirmation')
コード例 #40
0
def closeSession(request):
    """Close the session, and, if necessary, set any required cookies
    """
    session = ISession(request, None)
    if session is not None:
        if session.accessed():
            session.persist()
            sessionInstructions = session.request
            if sessionInstructions.get('set_cookie', False):
                if sessionInstructions['cookie_out']:
                    cookieObj = session.cookie[session.key]

                    key = cookieObj.key
                    value = session.cookie.value_encode(cookieObj.value)[1]

                    args = dict([(k, v) for k, v in cookieObj.items() if v])
                    args.setdefault('path', session._path)

                    if args.get('httponly'):
                        args.pop('httponly')
                        args['http_only'] = True

                    request.response.setCookie(key, value, **args)
コード例 #41
0
 def __call__(self):
     data = {}
     if not  ploneapi.user.is_anonymous():
         authuser = ploneapi.user.get_current()
         data['user'] = {'name':authuser.getProperty('fullname'), 'pin':authuser.getProperty('email'), 'role':'teacher'}
     else:
         session = ISession(self.request)
         chatid = 'chat_%s' % self.context.UID()
         userdata = session.get(chatid)
         userdata['role'] = 'trainee'
         data['user'] = userdata
     database = True
     if not self.get_databases():
         database = self.create_database()
     data['database'] = database
     data['teacher_folder_uid'] = self.context.aq_parent.UID()
     data['classroom_uid'] = self.context.UID()
     myauth = self.get_credentials()
     data['dbuser'] = myauth[0]
     data['dbpassword'] = myauth[1]
     classlist = self.context.get_classlist()
     data['classlist'] = classlist
     payload = jsonlib.write(data)
     return payload
コード例 #42
0
    def update(self):
        ''' Shows confirmation view before removing bank
        '''
        #import pdb; pdb.set_trace()
        session = ISession(self.request, None)
        self.card_id = self.request.get('id', None)
        self.return_url = self.request.get('return_url', None)
        available_cards = {}
        for card in session[SessionKeys.available_cards]:
            available_cards[card['id']] = card
        self.bank = available_cards[self.card_id]

        #import pdb; pdb.set_trace()

        button_ok = self.request.form.get('form.button.Ok') or None
        if button_ok:
            utils = getToolByName(self, "plone_utils")

            if self.card_id in [
                    x.get('id') for x in session[SessionKeys.available_cards]
            ]:
                kollkoll = Kollkoll()
                try:
                    result = kollkoll.removeCard(uid=get_pid(),
                                                 bid=self.card_id)
                    utils.addPortalMessage(
                        _('Din inlogging till ' + self.bank['name'] +
                          ' togs bort'), 'info')
                except Exception, ex:
                    utils.addPortalMessage(
                        _('Det uppstod ett fel i samband med att din inloggning skulle tas bort'
                          ), 'error')
                    logger.exception('Exception occured: %s' % str(ex))

            else:
                utils.addPortalMessage(_('Bank med angivet id saknas'),
                                       'error')

            if self.return_url and self.return_url != 'None':
                url = self.return_url
            else:
                url = self.context.absolute_url()

            return self.request.response.redirect(url)
コード例 #43
0
def setSessionData(request, data):
    """
    Schreibt das Cookie in die Session
    """
    session = ISession(request)
    mongo_objid = session.get('key', '')
    client = get_mongo_client().client
    db = client.mp_database
    collection = db.mp_collection
    if mongo_objid:
        insert = collection.replace_one({'_id':mongo_objid}, data, upsert=True)
        session.save()
    else:
        insert = collection.insert_one(data).inserted_id
        session['key'] = insert
        session.save()
    return insert
コード例 #44
0
ファイル: security.py プロジェクト: njervis/zenoss-prodbin
 def _getSessionData(self, id):
     # For some reason Products.BeakerSessionDataManager doesn't support getSessionDataByKey
     #sess = self.context.session_data_manager.getSessionDataByKey(sessionId)
     session = ISession(self.context.REQUEST)
     return session.get_by_id(id)
コード例 #45
0
 def destroyEditorSession(self, key=None):
     session_id = 'editlayout.%s' % SESSION_KEY
     session = ISession(getRequest())
     if session_id in session:
         del session[session_id]
         session.save()
コード例 #46
0
ファイル: partnersuche.py プロジェクト: kraeks/bghw.partner
    def handle_search(self):
        data, errors = self.extractData()
        if errors:
            return
        brains = ploneapi.content.find(portal_typ='Partner',
                                       art=data.get('art'))
        self.partners = []
        adresse = "%s, Deutschland" % data.get('plz')
        if data.get('strhnr'):
            adresse = "%s, %s, Deutschland" % (data.get('strhnr'),
                                               data.get('plz'))
        location = geolocator.geocode(adresse, timeout=10)
        geolocations = []
        if location:
            location = (location.latitude, location.longitude)
            geolocation = {
                "title": "Adresse Kunde",
                "lon": location[1],
                "lat": location[0],
                "color": '#555555'
            }
            geolocations = [geolocation]
        session = ISession(self.request)
        for i in brains:
            entry = {}
            partner = (i.latitude, i.longitude)
            distance = great_circle(location, partner).km
            if data.get('umkreis') != 'alle':
                if distance <= data.get('umkreis'):
                    obj = i.getObject()
                    entry['title'] = obj.title
                    entry['id'] = obj.UID()
                    entry['url'] = obj.absolute_url()
                    entry['plz'] = obj.plz
                    entry['ort'] = obj.ort
                    entry['kontakt'] = self.createKontaktinfos(obj)
                    entry['distance'] = distance
                    entry['printdistance'] = int(round(distance))
                    entry['zusatzinfos'] = obj.zusatzinfos
                    self.partners.append(entry)
                    geolocation = {
                        "title": obj.title,
                        "lon": i.longitude,
                        "lat": i.latitude,
                        "color": '#004994'
                    }
                    geolocations.append(geolocation)

            else:
                obj = i.getObject()
                entry['title'] = obj.title
                entry['id'] = obj.UID()
                entry['url'] = obj.absolute_url()
                entry['plz'] = obj.plz
                entry['ort'] = obj.ort
                entry['kontakt'] = self.createKontaktinfos(obj)
                entry['distance'] = distance
                entry['printdistance'] = int(round(distance))
                entry['zusatzinfos'] = obj.zusatzinfos
                self.partners.append(entry)
                geolocation = {
                    "title": obj.title,
                    "lon": i.longitude,
                    "lat": i.latitude,
                    "color": '#004994'
                }
                geolocations.append(geolocation)

        if self.partners:
            self.partners = sorted(self.partners, key=itemgetter('distance'))
        else:
            self.message = u'Leider konnten für Ihre Angaben keine Netzwerkpartner gefunden werden. Bitte ändern Sie gegebenenfalls Ihre Angaben\
                            und versuchen es dann erneut.'

            #ploneapi.portal.show_message(self.message, self.request, type="error")
            #return self.response.redirect(self.formurl)
        session['geodata'] = geolocations
        session.save()
コード例 #47
0
ファイル: card.py プロジェクト: educorvi/bgetem.medienshop
 def update(self):
     session = ISession(self.request)
     del session['cart']
     session.save()
コード例 #48
0
    def __init__(self, context, request, wizard):
        # Use collective.beaker for session managment
        session = ISession(request, None)
        self.sessionmanager = session

        super(SocialNetworkStep, self).__init__(context, request, wizard)
コード例 #49
0
def delSessionData(request):
    """
    Loescht das Cookie
    """
    session = ISession(request)
    session.delete()
コード例 #50
0
 def __call__(self):
     locations = []
     session = ISession(self.request)
     if session.get('geodata'):
         locations = session.get('geodata')
     return jsonlib.write(locations)
コード例 #51
0
 def _session(self):
     """ Here's the core logic which looks up the Beaker session. """
     session = ISession(self.REQUEST)
     return BeakerSessionDataObject(session)
コード例 #52
0
    def __call__(self):
        registry = getUtility(IRegistry)
        TWITTER_CONSUMER_KEY = registry.get(
            'cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_key'
        ).encode()
        TWITTER_CONSUMER_SECRET = registry.get(
            'cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_secret'
        ).encode()

        session = ISession(self.request)
        token = oauth.Token(
            session[AuthorizationTokenKeys.oauth_token],
            session[AuthorizationTokenKeys.oauth_token_secret],
        )
        consumer = oauth.Consumer(key=TWITTER_CONSUMER_KEY,
                                  secret=TWITTER_CONSUMER_SECRET)
        client = oauth.Client(consumer, token)
        resp, content = client.request(TWITTER_ACCESS_TOKEN_URL, 'GET')
        if resp.get('status', '999') != '200':
            IStatusMessage(self.request).add(
                _(u"Error authenticating with Twitter. Please try again."),
                type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""

        access_token = dict(parse_qsl(content))
        # Save the data in the session so that the extraction plugin can
        # authenticate the user to Plone
        session = ISession(self.request)
        session[SessionKeys.user_id] = str(access_token['user_id'])
        session[SessionKeys.screen_name] = access_token['screen_name']
        session[SessionKeys.oauth_token] = access_token['oauth_token']
        session[SessionKeys.
                oauth_token_secret] = access_token['oauth_token_secret']

        api = Api(consumer_key=TWITTER_CONSUMER_KEY,
                  consumer_secret=TWITTER_CONSUMER_SECRET,
                  access_token_key=session[AuthorizationTokenKeys.oauth_token],
                  access_token_secret=session[
                      AuthorizationTokenKeys.oauth_token_secret])

        us = api.GetUser(str(access_token['user_id']))
        session[SessionKeys.name] = us.name
        session[SessionKeys.profile_image_url] = us.profile_image_url
        session[SessionKeys.description] = us.description
        session[SessionKeys.location] = us.location
        session.save()

        # Add user data into our plugin storage:
        acl = self.context.acl_users
        acl_plugins = acl.plugins
        ids = acl_plugins.listPluginIds(IExtractionPlugin)
        for id in ids:
            plugin = getattr(acl_plugins, id)
            if ICSTwitterPlugin.providedBy(plugin):
                if plugin._storage.get(session[SessionKeys.user_id],
                                       None) is None:
                    user_data = {
                        'screen_name': session[SessionKeys.screen_name],
                        'fullname': session[SessionKeys.name],
                        'profile_image_url':
                        session[SessionKeys.profile_image_url],
                        'description': session[SessionKeys.description],
                        'location': session[SessionKeys.location]
                    }
                    plugin._storage[session[SessionKeys.user_id]] = user_data

        IStatusMessage(self.request).add(_(u"Welcome. You are now logged in."),
                                         type="info")

        return_args = ''
        if self.request.get('came_from', None) is not None:
            return_args = {'came_from': self.request.get('came_from')}
            return_args = '?' + urllib.urlencode(return_args)

        self.request.response.redirect(self.context.absolute_url() +
                                       '/logged_in' + return_args)
コード例 #53
0
 def destroy(self, portal, key=None):
     cart_id = 'groundwire.checkout.cart.%s' % '/'.join(portal.getPhysicalPath())
     session = ISession(getRequest())
     if cart_id in session:
         del session[cart_id]
         session.save()
コード例 #54
0
    def __call__(self):
        registry = getUtility(IRegistry)
        FB_APP_ID = registry.get('cs.auth.facebook.controlpanel.IFacebookloginSettings.fb_app_id').encode()
        FB_APP_SECRET = registry.get('cs.auth.facebook.controlpanel.IFacebookloginSettings.fb_app_secret').encode()

        verificationCode = self.request.form.get("code", None)
        error            = self.request.form.get("error", None)
        errorReason      = self.request.form.get("error_reason", None)

        salt = hashlib.sha256().hexdigest()
        session = ISession(self.request)
        session[FB_AUTHENTICATION_SALT_KEY] = salt
        args = {
                'state': salt,
                'scope': PERMISSIONS,
                'client_id': FB_APP_ID,
                'redirect_uri': "%s/%s" % (self.context.absolute_url(), self.__name__,),
            }

        
        # Did we get an error back after a Facebook redirect?
        if error is not None or errorReason is not None:
            log.info(error)
            log.info(errorReason)
            IStatusMessage(self.request).add(_(u"Facebook authentication denied"), type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""
        
        # Check if this the status is the same...
        return_salt = self.request.form.get('status', '')
        if return_salt and return_salt != session.get(FB_AUTHENTICATION_SALT_KEY):
            IStatusMessage(self.request).add(_(u"Facebook authentication denied"), type="error")
            self.request.response.redirect(self.context.absolute_url())
            log.info('%s != %s' % (return_salt, session.get(FB_AUTHENTICATION_SALT_KEY)))
            return u""

        # If there is no code, this is probably the first request, so redirect
        # to Facebook
        if verificationCode is None:
            self.request.response.redirect(
                    "%s?%s" % (FACEBOOK_AUTH_URL, urllib.urlencode(args),)
                )
            
            return u""
        
        # If we are on the return path form Facebook, 
        # exchange the return code for a token
        args["client_secret"] = FB_APP_SECRET
        args["code"] = verificationCode
        
        response = urlparse.parse_qs(urllib.urlopen(
                "%s?%s" % (FACEBOOK_ACCESS_TOKEN_URL, urllib.urlencode(args),)
            ).read())
        
        # Load the profile using the access token we just received
        accessToken = response["access_token"][-1]
        
        profile = json.load(urllib.urlopen(
                "%s?%s" % (FACEBOOK_PROFILE_URL, urllib.urlencode({'access_token': accessToken}),)
            ))

        userId = profile.get('id')
        name = profile.get('name')
        email = profile.get('email', '')
        username = profile.get('username', '')
        location = profile.get('location', {}).get('name', '')

        profile_image = urllib.urlopen(
                "%s?%s" % (FACEBOOK_PROFILE_PICTURE_URL, urllib.urlencode({'access_token': accessToken}),)
            ).read()

        if not userId or not name:
            IStatusMessage(self.request).add(_(u"Insufficient information in Facebook profile"), type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""
        
        # Save the data in the session so that the extraction plugin can 
        # authenticate the user to Plone        
        session[SessionKeys.accessToken] = accessToken
        session[SessionKeys.userId]      = userId
        session[SessionKeys.userName]    = username or userId
        session[SessionKeys.fullname]    = name
        session[SessionKeys.email]       = email
        session[SessionKeys.location]    = location
        session[SessionKeys.profile_image]    = profile_image
        session.save()

        # Add user data into our plugin storage:
        acl = self.context.acl_users
        acl_plugins = acl.plugins
        ids = acl_plugins.listPluginIds(IExtractionPlugin)
        for id in ids:
            plugin = getattr(acl_plugins, id)
            if ICSFacebookPlugin.providedBy(plugin):
                user_data = plugin._storage.get(session[SessionKeys.userId], {})
                user_data['username'] = session[SessionKeys.userName]
                user_data['fullname'] = session[SessionKeys.fullname]
                user_data['email'] = session[SessionKeys.email]
                user_data['location'] = session[SessionKeys.location]
                plugin._storage[session[SessionKeys.userId]] = user_data

        
        IStatusMessage(self.request).add(_(u"Welcome. You are now logged in."), type="info")
        
        return_args = ''
        if self.request.get('came_from', None) is not None:
            return_args = {'came_from': self.request.get('came_from')}
            return_args = '?' + urllib.urlencode(return_args)

        self.request.response.redirect(self.context.absolute_url() + '/logged_in' + return_args)
コード例 #55
0
    def __call__(self):
        registry = getUtility(IRegistry)
        TWITTER_CONSUMER_KEY = registry.get(
            'cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_key'
        ).encode()
        TWITTER_CONSUMER_SECRET = registry.get(
            'cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_secret'
        ).encode()

        # Create an Oauth Consumer
        oauth_consumer = oauth.Consumer(key=TWITTER_CONSUMER_KEY,
                                        secret=TWITTER_CONSUMER_SECRET)

        oauth_client = oauth.Client(oauth_consumer)

        # Set the callback URL. Be sure that callback urls are allowed in Twitter
        # App configuration. Do not leave blank the field of the callback url
        # when creating the app, otherwise this login method *will not work*.
        return_args = ''
        if self.request.get('came_from', None) is not None:
            return_args = {'came_from': self.request.get('came_from')}
            return_args = '?' + urllib.urlencode(return_args)

        args = {
            'oauth_callback':
            self.context.absolute_url() + '/@@twitter-login-verify' +
            return_args,
        }
        body = urllib.urlencode(args)
        resp, content = oauth_client.request(TWITTER_REQUEST_TOKEN_URL,
                                             'POST',
                                             body=body)

        if resp.get('status', '999') != '200':
            IStatusMessage(self.request).add(_(
                u"Error getting the authorization token from Twitter. Try again please"
            ),
                                             type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""
        else:
            # The request was successful, so save the token in the session
            # and redirect the user to Twitter
            request_token = dict(parse_qsl(content))
            session = ISession(self.request)
            session[AuthorizationTokenKeys.
                    oauth_token] = request_token['oauth_token']
            session[AuthorizationTokenKeys.
                    oauth_token_secret] = request_token['oauth_token_secret']
            session[AuthorizationTokenKeys.
                    oauth_callback_confirmed] = request_token[
                        'oauth_callback_confirmed']
            session.save()

            args = {
                'oauth_token': request_token['oauth_token'],
            }

            self.request.response.redirect("%s?%s" % (
                TWITTER_AUTH_URL,
                urllib.urlencode(args),
            ))
コード例 #56
0
    def update(self):
        # Use collective.beaker for session managment
        session = ISession(self.request, None)
        self.sessionmanager = session

        super(Wizard, self).update()
コード例 #57
0
ファイル: user.py プロジェクト: educorvi/bgetem.medienshop
    def order(self):
        data, errors = self.extractData()
        if self.verif and len(errors) == 2:
            errors = None
        if errors:
            return
        sapapi = sapshopapi.getAPI()
        checker = self.checkBestand()
        if not checker:
            url = ploneapi.portal.get().absolute_url() + '/checkorder'
            message = u'Bei Ihrer Bestellung ist leider ein Fehler aufgetreten. Bitte beachten Sie die aktualisierten Mengen bei den rot markierten\
                        Artikeln.'

            ploneapi.portal.show_message(message=message,
                                         request=self.request,
                                         type='error')
            return
        bestellung = sapapi.createOrder(self.userdata.get('email'),
                                        self.artlist)
        if bestellung.EX_RETURN == 0:
            self.bestellnummer = bestellung.EX_VBELN
            self.userdata['bestellnummer'] = self.bestellnummer
            key = setSessionData(self.request, self.userdata)

            mime_msg = MIMEMultipart('related')
            mime_msg['Subject'] = u"Ihre Bestellung auf bgetem.de"
            mime_msg['From'] = u"*****@*****.**"
            mime_msg['To'] = self.userdata.get('email')
            mime_msg.preamble = 'This is a multi-part message in MIME format.'
            msgAlternative = MIMEMultipart('alternative')
            mime_msg.attach(msgAlternative)

            htmltext = createOrderMessage(self.userdata, self.verif, self.mnr,
                                          self.artlist, self.gesamt_mem,
                                          self.gesamt, self.bestellnummer)
            msg_txt = MIMEText(htmltext, _subtype='html', _charset='utf-8')
            msgAlternative.attach(msg_txt)
            mail_host = ploneapi.portal.get_tool(name='MailHost')
            mail_host.send(mime_msg.as_string())

            #message = u'Vielen Dank, Ihre Bestellung ist bei uns eingegangen. Sie erhalten eine Bestätigung per E-Mail.'
            #ploneapi.portal.show_message(message=message, request=self.request, type='info')
            try:
                carddata = getCartCookie(self.request)
                for i in carddata:
                    artikel = ploneapi.content.find(UID=i)[0].getObject()
                    artikel._v_article = None
                session = ISession(self.request)
                del session['cart']
                session.save()
            except:
                print u'Problem beim Delete Session'
            url = ploneapi.portal.get().absolute_url(
            ) + '/medienportal/orderconfirm'
            return self.response.redirect(url)

        else:
            message = u'Bei Ihrer Bestellung ist leider ein Fehler aufgetreten. Bitte versuchen Sie es später noch einmal. (%s)' % bestellung.EX_MESSAGE
            ploneapi.portal.show_message(message=message,
                                         request=self.request,
                                         type='error')
            return self.response.redirect(self.formurl)
コード例 #58
0
    def __call__(self):
        registry = getUtility(IRegistry)
        GOOGLEPLUS_CLIENT_ID = registry.get('cs.auth.googleplus.controlpanel.IGooglePlusLoginSettings.googleplus_client_id').encode()
        GOOGLEPLUS_CLIENT_SECRET = registry.get('cs.auth.googleplus.controlpanel.IGooglePlusLoginSettings.googleplus_client_secret').encode()

        verificationCode = self.request.form.get("code", None)
        error = self.request.form.get("error", None)
        errorReason = self.request.form.get("error_reason", None)

        salt = hashlib.sha256().hexdigest()
        session = ISession(self.request)
        session[GOOGLEPLUS_AUTHENTICATION_SALT_KEY] = salt
        args = {
                'state': STATE,
                'scope': PERMISSIONS,
                'client_id': GOOGLEPLUS_CLIENT_ID,
                'redirect_uri': "%s/%s" % (self.context.absolute_url(),
                                           self.__name__),
                'response_type': RESPONSE,
            }

        # Did we get an error back after a Google+ redirect?
        if error is not None or errorReason is not None:
            log.info(error)
            log.info(errorReason)
            IStatusMessage(self.request).add(_(
                u"GOOGLEPLUS authentication denied"), type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""

        # Check if this the status is the same...
        return_salt = self.request.form.get('status', '')
        session_salt = session.get(GOOGLEPLUS_AUTHENTICATION_SALT_KEY)
        if return_salt and return_salt != session_salt:
            IStatusMessage(self.request).add(_(
                u"GooglePlus authentication denied"), type="error")
            self.request.response.redirect(self.context.absolute_url())
            log.info('%s != %s' % (
                return_salt,
                session.get(GOOGLEPLUS_AUTHENTICATION_SALT_KEY)))
            return u""

        # If there is no code, this is probably the first request, so redirect
        # to Google+
        if verificationCode is None:
            self.request.response.redirect(
                    "%s?%s" % (GOOGLEPLUS_AUTH_URL, urllib.urlencode(args),)
                )
            return u""

        # If we are on the return path form Google+,
        # exchange the return code for a token
        args = {
            'code': verificationCode,
            'client_id': GOOGLEPLUS_CLIENT_ID,
            'client_secret': GOOGLEPLUS_CLIENT_SECRET,
            'redirect_uri': "%s/%s" % (
                self.context.absolute_url(),
                self.__name__),
            'grant_type': GRANT,
            }

        response = requests.post(GOOGLEPLUS_ACCESS_TOKEN_URL, data=args)

        #Load the profile using the access token we just received
        accessToken = response.json()["access_token"]

        def unicode_to_utf8(data):
            if isinstance(data, unicode):
                return data.encode('utf-8')
            else:
                return data

        def dict_unicode_to_utf8(data):
            new_data = {}
            for key, value in data.items():
                new_data[unicode_to_utf8(key)] = unicode_to_utf8(value)
            return new_data

        profile = json.load(urllib.urlopen(
                "%s?%s" % (
                    GOOGLEPLUS_PROFILE_URL,
                    urllib.urlencode({'access_token': accessToken}),)
            ), object_hook=dict_unicode_to_utf8)

        userId = profile.get('id')
        name = profile.get('name')
        email = profile.get('email', '')
        username = profile.get('name')
        profile_image = profile.get('picture')

        if not userId:
            IStatusMessage(self.request).add(
                _(u"Insufficient information in GooglePlus profile"),
                type="error")
            self.request.response.redirect(self.context.absolute_url())
            return

        # Save the data in the session so that the extraction plugin can
        # authenticate the user to Plone
        session[SessionKeys.accessToken] = accessToken
        session[SessionKeys.userId] = userId
        session[SessionKeys.userName] = username
        session[SessionKeys.fullname] = name
        session[SessionKeys.email] = email
        session[SessionKeys.profile_image] = profile_image
        session.save()

        # Add user data into our plugin storage:
        acl = self.context.acl_users
        initial_login = acl.getUserById(userId) is None

        acl_plugins = acl.plugins
        ids = acl_plugins.listPluginIds(IExtractionPlugin)
        for id in ids:
            plugin = getattr(acl_plugins, id)
            if ICSGooglePlusPlugin.providedBy(plugin):
                user_data = plugin._storage.get(
                    session[SessionKeys.userId], {})
                user_data['username'] = session[SessionKeys.userName]
                user_data['fullname'] = session[SessionKeys.fullname]
                user_data['email'] = session[SessionKeys.email]
                plugin._storage[session[SessionKeys.userId]] = user_data

        IStatusMessage(self.request).add(
            pmf(u"Welcome! You are now logged in."),
            type="info")

        return_args = ''
        if self.request.get('came_from', None) is not None:
            return_args = {'came_from': self.request.get('came_from')}
            return_args = '?' + urllib.urlencode(return_args)

        user = acl.getUserById(userId)
        if initial_login:
            notify(GoogleUserRegisteredEvent(user, profile))
        else:
            notify(GoogleUserLoggedInEvent(user, profile))

        self.request.response.redirect(
            self.context.absolute_url() + '/logged_in' + return_args)
コード例 #59
0
def redirect_to_checkout():
    site = getSite()
    request = getRequest()
    session = ISession(request)
    session.save()
    request.response.redirect(site.absolute_url() + '/checkout')
コード例 #60
0
ファイル: security.py プロジェクト: zenoss/zenoss-prodbin
 def _getSessionData(self, id):
     # For some reason Products.BeakerSessionDataManager doesn't support getSessionDataByKey
     #sess = self.context.session_data_manager.getSessionDataByKey(sessionId)
     session = ISession(self.context.REQUEST)
     return session.get_by_id(id)