Esempio n. 1
0
    def test_accessed_get(self):
        provideAdapter(testingSession)

        request = TestRequest()
        session = ISession(request)

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

        session.get('foo')

        self.failIf(session.last_accessed is None)
        self.assertEquals(True, session.accessed())
Esempio n. 2
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
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')
Esempio n. 4
0
 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))
Esempio n. 5
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
 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()
Esempio n. 7
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
Esempio n. 8
0
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
Esempio n. 9
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
Esempio n. 10
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)
Esempio n. 11
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", "")
        if return_salt and return_salt != session.get(GOOGLEPLUS_AUTHENTICATION_SALT_KEY):
            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"]

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

        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 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
        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
        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(_(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)
Esempio n. 12
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)
Esempio n. 13
0
 def __call__(self):
     locations = []
     session = ISession(self.request)
     if session.get('geodata'):
         locations = session.get('geodata')
     return jsonlib.write(locations)