Esempio n. 1
0
def check_login_headers(headers):
    # The Cookie class is really meant to be used server side; so it has
    # good support for parsing Cookie headers, and generating Set-Cookie
    # headers. We're abusing it here to do "client-side' processing
    # where we need to parse Set-Cookie headers and generate Cookie headers.
    global login_cookie_header
    login_cookie = None
    for header, value in headers.items():
        if header.lower() == "set-cookie":
            if login_cookie == None:
                login_cookie = Cookie.SimpleCookie()
            login_cookie.load(value)
    login_header = ""
    if login_cookie is None:
        return

    for key, morsel in login_cookie.iteritems():
        if login_cookie_header is None:
            login_cookie_header = ""
        else:
            login_cookie_header += "; "
        login_cookie_header += key + "=" + morsel.coded_value
        # attributes in the Cookie: header are represented as $Attribute
        # to distinguish them from cookie names, since it's:
        # Cookie: name=val; attr=val; attr=val; name=val; attr=val
        if 'path' in morsel and morsel['path'] != '':
            login_cookie_header += "; $Path=" + Cookie._quote(morsel['path'])
        if 'domain' in morsel and morsel['domain'] != '':
            login_cookie_header += "; $Domain=" + Cookie._quote(morsel['domain'])
Esempio n. 2
0
    def verify(self, sender):
        sender = str(sender).lower()
        hmac = self.local_parts[-1]
        try_hmac = Cookie.make_sender_cookie(sender)
        if try_hmac != hmac:
            domain = sender.split('@')[-1]
            dot = '.'
            domain_parts = domain.split(dot)

            while try_hmac != hmac and domain_parts:
              try_hmac = Cookie.make_sender_cookie(dot.join(domain_parts))
              del domain_parts[0]
            if try_hmac != hmac:
              raise BadCryptoError, "Invalid cryptographic tag."
Esempio n. 3
0
    def header(self, headers=None, response=None):
        '''Put up the appropriate header.
        '''
        if headers is None:
            headers = {'Content-Type':'text/html; charset=utf-8'}
        if response is None:
            response = self.response_code

        # update with additional info
        headers.update(self.additional_headers)

        if headers.get('Content-Type', 'text/html') == 'text/html':
            headers['Content-Type'] = 'text/html; charset=utf-8'

        headers = headers.items()

        for ((path, name), (value, expire)) in self.add_cookies.items():
            cookie = "%s=%s; Path=%s;"%(name, value, path)
            if expire is not None:
                cookie += " expires=%s;"%Cookie._getdate(expire)
            headers.append(('Set-Cookie', cookie))

        self._socket_op(self.request.start_response, headers, response)

        self.headers_done = 1
        if self.debug:
            self.headers_sent = headers
Esempio n. 4
0
    def _BaseCookie__ParseString(self, str, patt=cookies._CookiePattern):
        i = 0            # Our starting point
        n = len(str)     # Length of string
        M = None         # current morsel

        while 0 <= i < n:
            # Start looking for a cookie
            match = patt.search(str, i)
            if not match: break          # No more cookies

            K,V = match.group("key"), match.group("val")
            i = match.end(0)

            # Parse the key, value in case it's metainfo
            if K[0] == "$":
                # We ignore attributes which pertain to the cookie
                # mechanism as a whole.  See RFC 2109.
                # (Does anyone care?)
                if M:
                    try:
                        M[ K[1:] ] = V
                    except cookies.CookieError:
                        # We don't care.
                        pass
            elif K.lower() in cookies.Morsel._reserved:
                if M:
                    M[ K ] = cookies._unquote(V)
            else:
                rval, cval = self.value_decode(V)
                try:
                    self._BaseCookie__set(K, rval, cval)
                    M = self[K]
                except cookies.CookieError as e:
                    eventlog.warning(e)
Esempio n. 5
0
 def verify(self, dummy=''):
     try:
         (timestamp, pid, hmac) = self.local_parts[-1].split('.')
         try_hmac = Cookie.confirmationmac(timestamp, pid, self.keyword)
         if try_hmac != hmac:
             raise BadCryptoError, "Invalid cryptographic tag."
     except ValueError:
         raise BadCryptoError, "Invalid cryptographic tag format."
Esempio n. 6
0
def getSession(self,
               create=1,
               path=None,
               domain=None,
               secure=None):           
    '''
    returns the session associated with this request.
    If create, will create a new session if there is none.
    '''
    # permit sessions to be turned off by leaving the session store null,
    # but raise an exception if someone tries to access a session
    if Configuration.SessionStore is None:
        raise SessionError, "no session store enabled"
    try:
        sess= self.__userSession
    except AttributeError:
        pass
    else:
        if sess:
            return sess
    DEBUG(SESSIONHANDLER, "session is None")
    # session is None
    
    id=self.getSessionID(create)
    if not id:
        DEBUG(SESSIONHANDLER, "id is false for create: %s" % create)
        return None

    sess=self.__userSession=Session(id)
    sesskey=Configuration.SessionIDKey

    # test session - is it too old?
    if sess.age() >= Configuration.SessionTimeout:
        DEBUG(SESSIONHANDLER, "session is too old")
        sess.delete()
        del self.__userSession
        if self.requestCookie.has_key(sesskey):
            self.responseCookie[sesskey]=""
            self.responseCookie[sesskey]['expires']=Cookie._getdate(-10000000)
        del self.__sessionID
        id=self.getSessionID(create)
        if not id:
            return None
        sess=self.__userSession=Session(id)
    
    if (not self.requestCookie.has_key(sesskey)) or \
           [x for x in (path, domain, secure) if x is not None]:
        self.responseCookie[sesskey]=id

        morsel=self.responseCookie[sesskey]
        if path is not None:
            morsel['path']=path
        if domain is not None:
            morsel['domain']=domain
        if secure is not None:
            morsel['secure']=secure

    return self.__userSession
Esempio n. 7
0
 def create(self, base, sender):
     if not base:
         base = self.base()
     (dummy, local, domain) = _split(str(base))
     cookie = Cookie.make_sender_cookie(str(sender))
     self.local_parts = [ local, Defaults.TAGS_SENDER[0].lower(), cookie ]
     tagged_local = Defaults.RECIPIENT_DELIMITER.join(self.local_parts)
     self.address = tagged_local + '@' + domain
     return self
Esempio n. 8
0
 def create(self, base, timeout=None):
     if not base:
         base = self.base()
     (dummy, local, domain) = _split(str(base))
     cookie = Cookie.make_dated_cookie(int(time.time()), timeout)
     self.local_parts = [ local, Defaults.TAGS_DATED[0].lower(), cookie ]
     tagged_local = Defaults.RECIPIENT_DELIMITER.join(self.local_parts)
     self.address = tagged_local + '@' + domain
     return self
Esempio n. 9
0
    def setCookie(self, name, value, **kw):
        'See IHTTPResponse'
        cookies = self._cookies
        cookie = cookies.setdefault(name, {})

        for k, v in kw.items():
            if v is not None:
                cookie[k.lower()] = v

        cookie['value'] = value
Esempio n. 10
0
 def verify(self, dummy=''):
     try:
         (timestamp, hmac) = self.local_parts[-1].split('.')
         try_hmac = Cookie.datemac(timestamp)
         if int(time.time()) > int(timestamp):
             raise ExpiredAddressError, "Dated address has expired."
         if try_hmac != hmac:
             raise BadCryptoError, "Invalid cryptographic tag."
     except ValueError:
         raise BadCryptoError, "Invalid cryptographic tag format."
Esempio n. 11
0
 def verify(self, dummy=''):
     parts = self.local_parts[-1].split('.')
     # Not necessary anymore, since '.', among other chars, is
     # replaced by '?' in Cookie.make_keywordmac().
     keyword = '.'.join(parts[:-1])
     if not keyword:
         raise BadCryptoError, "Invalid cryptographic tag format."
     hmac = parts[-1]
     try_hmac = Cookie.make_keywordmac(keyword)
     if try_hmac != hmac:
         raise BadCryptoError, "Invalid cryptographic tag."
Esempio n. 12
0
 def getConfirmAddress(self):
     if not self.confirm_accept_address:
         if self.recipient:
             import Cookie
             (timestamp, pid) = self.msgid.split('.')
             self.confirm_accept_address =   Cookie.make_confirm_address(
                                             self.recipient, timestamp, pid,
                                             'accept')
         else:
             return None
     return self.confirm_accept_address
Esempio n. 13
0
 def create(self, base, timestamp, pid, keyword='accept'):
     if Defaults.CONFIRM_ADDRESS:
         base = Defaults.CONFIRM_ADDRESS
     elif not base:
         base = self.base()
     self.keyword = keyword
     (dummy, local, domain) = _split(str(base))
     cookie = Cookie.make_confirm_cookie(int(timestamp), pid, keyword)
     self.local_parts = [ local, Defaults.TAGS_CONFIRM[0].lower(), cookie ]
     tagged_local = Defaults.RECIPIENT_DELIMITER.join(self.local_parts)
     self.address = tagged_local + '@' + domain
     return self
Esempio n. 14
0
    def __ParseString(self, str, patt=Cookie._CookiePattern):
        i = 0  # Our starting point
        n = len(str)  # Length of string
        M = None  # current morsel

        while 0 <= i < n:
            # Start looking for a cookie
            match = patt.search(str, i)
            if not match:
                break  # No more cookies

            K, V = match.group("key"), match.group("val")
            i = match.end(0)

            # Parse the key, value in case it's metainfo
            if K[0] == "$":
                # We ignore attributes which pertain to the cookie
                # mechanism as a whole.  See RFC 2109.
                # (Does anyone care?)
                if M:
                    M[K[1:]] = V
            elif K.lower() in Cookie.Morsel._reserved:
                if M:
                    M[K] = Cookie._unquote(V)
            else:
                if not SIG_PATTERN.search(V):
                    pass
                uval = Cookie._unquote(V)
                real_val = uval[:-SIG_LEN]
                try:
                    sig = b64decode(uval[-SIG_LEN:])
                except TypeError:
                    # Incorrect padding
                    raise BadSignatureError("Bad signature for cookie '%s'" % K)
                    # TODO: use constant time string comparison
                if sig != hmac.new(self.key + K, real_val, sha256).digest():
                    raise BadSignatureError("Bad signature for cookie '%s'" % K)
                self._BaseCookie__set(K, real_val, V)
                M = self[K]
Esempio n. 15
0
 def _send_head(self):
     if self._new_session_uri!=None:
         import Cookie
         cookie = Cookie.SmartCookie()
         TTL = 3600*24*10000 # time to live in seconds (a long time)
         cookie['Redfoot_session'] = self._new_session_uri
         cookie['Redfoot_session']['path'] = "/"
         cookie['Redfoot_session']['Version'] = "1"
         cookie['Redfoot_session']['expires'] = Cookie._getdate(TTL)
         
         output = cookie.output()
         # Warning: Assuming there is only one header in output
         (name, value) = output.split(": ", 1)
         self.set_header(name, value)
Esempio n. 16
0
    def _send_head(self):
        self.write("%s %s %s\r\n" % ("HTTP/1.1", "200", "OK"))

        for key in self._header.keys():
            self.write("%s: %s\r\n" % (key, self._header[key]))

        if self._new_session_uri!=None:
            import Cookie
            cookie = Cookie.SmartCookie()
            TTL = 3600*24*10000 # time to live in seconds (a long time)
            cookie['Redfoot_session'] = self._new_session_uri
            cookie['Redfoot_session']['path'] = "/"
            cookie['Redfoot_session']['Version'] = "1"
            cookie['Redfoot_session']['expires'] = Cookie._getdate(TTL)
            self.write(cookie.output())

        self.write("\r\n")
Esempio n. 17
0
    def handle(self):
        """Make us really anonymous - nuke the cookie too."""
        # log us out
        self.client.make_user_anonymous()

        # construct the logout cookie
        now = Cookie._getdate()
        self.client.additional_headers['Set-Cookie'] = \
           '%s=deleted; Max-Age=0; expires=%s; Path=%s;' % (
               self.client.cookie_name, now, self.client.cookie_path)

        # Let the user know what's going on
        self.client.ok_message.append(self._('You are logged out'))

        # reset client context to render tracker home page
        # instead of last viewed page (may be inaccessibe for anonymous)
        self.client.classname = None
        self.client.nodeid = None
        self.client.template = None
Esempio n. 18
0
 def release(self):
     """Release a message from the pending queue."""
     import Cookie
     if Defaults.PENDING_RELEASE_APPEND:
         Util.append_to_file(self.append_address,
                             Defaults.PENDING_RELEASE_APPEND)
     if Defaults.DB_PENDING_RELEASE_APPEND and Defaults.DB_CONNECTION:
         _username = Defaults.USERNAME.lower()
         _hostname = Defaults.HOSTNAME.lower()
         _recipient = _username + '@' + _hostname
         params = FilterParser.create_sql_params(
             recipient=_recipient, username=_username,
             hostname=_hostname, sender=self.append_address)
         Util.db_insert(Defaults.DB_CONNECTION,
                        Defaults.DB_PENDING_RELEASE_APPEND,
                        params)
     timestamp, pid = self.msgid.split('.')
     # Remove Return-Path: to avoid duplicates.
     del self.msgobj['return-path']
     # Remove X-TMDA-Recipient:
     del self.msgobj['x-tmda-recipient']
     # To avoid a mail loop on re-injection, prepend an ``Old-'' prefix
     # to all existing Delivered-To lines.
     Util.rename_headers(self.msgobj, 'Delivered-To', 'Old-Delivered-To')
     # Add an X-TMDA-Confirm-Done: field to the top of the header for
     # later verification.  This includes a timestamp, pid, and HMAC.
     del self.msgobj['X-TMDA-Confirm-Done']
     self.msgobj['X-TMDA-Confirm-Done'] = Cookie.make_confirm_cookie(timestamp,
                                                                pid, 'done')
     # Add the date when confirmed in a header.
     del self.msgobj['X-TMDA-Released']
     self.msgobj['X-TMDA-Released'] = Util.make_date()
     # For messages released via tmda-cgi, add the IP address and
     # browser info of the releaser for easier tracing.
     if os.environ.has_key('REMOTE_ADDR') and \
             os.environ.has_key('HTTP_USER_AGENT'):
         cgi_header = "%s (%s)" % (os.environ.get('REMOTE_ADDR'),
                                   os.environ.get('HTTP_USER_AGENT'))
         del self.msgobj['X-TMDA-CGI']
         self.msgobj['X-TMDA-CGI'] = cgi_header
     # Reinject the message to the original envelope recipient.
     Util.sendmail(self.show(), self.recipient, self.return_path)
Esempio n. 19
0
def removeSession(self):
    '''
    clears and removes any active session.
    '''
    DEBUG(SESSIONHANDLER, "in removeSession()")
    self.getSession(0)

    try:
        sess=self.__userSession
    except AttributeError:
        pass
    else:
        if sess:
            sess.delete()
        del self.__userSession
        self.__sessionID=None
    sesskey=Configuration.SessionIDKey
    if self.requestCookie.has_key(sesskey):
        self.responseCookie[sesskey]=""
        self.responseCookie[sesskey]['expires']=Cookie._getdate(-10000000)
Esempio n. 20
0
 def cookie(self):
     c = Cookie.SimpleCookie()
     # XXX There is is a bug in the base class implementation fixed here
     c[self.cookie_name] = self.cookie_value().strip().replace('\n', '')
     for k, v in self.cookie_params.items():
         if k not in ['path', 'expires']:
             c[self.cookie_name][k] = v
     # path and secure are handled differently to keep it consistent with
     # the base class API
     if not self.cookie_params.has_key('path'):
         c[self.cookie_name]['path'] = '/'
     else:
         c[self.cookie_name]['path'] = self.cookie_params['path']
     if self.cookie_params.has_key('expires'):
         time = Cookie._getdate(float(self.cookie_params['expires']))
         log.info(time)
         c[self.cookie_name]['expires'] = time
     if self.secure:
         c[self.cookie_name]['secure'] = 'true'
     return c
Esempio n. 21
0
    def deserialize(self, name, value, max_age=None):
        """Deserializes a signed cookie value.

        :param name:
            Cookie name.
        :param value:
            A cookie value to be deserialized.
        :param max_age:
            Maximum age in seconds for a valid cookie. If the cookie is older
            than this, returns None.
        :returns:
            The deserialized secure cookie, or None if it is not valid.
        """
        if not value:
            return None

        # Unquote for old WebOb.
        value = Cookie._unquote(value)

        parts = value.split('|')
        if len(parts) != 3:
            return None

        signature = self._get_signature(name, parts[0], parts[1])

        if not security.compare_hashes(parts[2], signature):
            logging.warning('Invalid cookie signature %r', value)
            return None

        if max_age is not None:
            if int(parts[1]) < self._get_timestamp() - max_age:
                logging.warning('Expired cookie %r', value)
                return None

        try:
            return self._decode(parts[0])
        except Exception, e:
            logging.warning('Cookie value failed to be decoded: %r', parts[0])
            return None
def _add_usertracking_cookie(conn, sessionDict):
    if Configuration.usertrackingOn:
        cookiename=Configuration.usertrackingCookieName
        if not _verify_cookie(conn, cookiename):
            f=Configuration.usertrackingGenUIDFunc
            if f is None:
                conn.responseCookie[cookiename]=uuid()
            else:
                conn.responseCookie[cookiename]=f(conn)
            morsel=conn.responseCookie[cookiename]
            for c, a in _config_attrs:
                if a=='expires':
                    # special case
                    if not Configuration.usertrackingExpiresAbsolute:
                        v=getattr(Configuration, c)
                        if v is not None:
                            morsel[a]=Cookie._getdate(v)
                        continue
                v=getattr(Configuration, c)
                if v is not None:
                    morsel[a]=v
            DEBUG(USERTRACKING, str(morsel))
            DEBUG(USERTRACKING, str(conn.responseCookie[cookiename]))
Esempio n. 23
0
def get_static_file(path, dir=None, max_age=10):
    if not path: raise Http404NotFound
    if dir is None: dir = options.STATIC_DIR
    if dir is None:
        if pony.MAIN_DIR is None: raise Http404NotFound
        dir = os.path.join(pony.MAIN_DIR, 'static')
    for component in path:
        if not path_re.match(component): raise Http404NotFound
    fname = os.path.join(dir, *path)
    if not os.path.isfile(fname):
        if path == [ 'favicon.ico' ]: return get_static_file(path, pony_static_dir, 30*60)
        raise Http404NotFound
    method = local.request.method
    if method not in ('GET', 'HEAD'): raise Http405MethodNotAllowed
    ext = os.path.splitext(path[-1])[1]
    headers = local.response.headers
    headers['Content-Type'] = httputils.guess_type(ext)
    if max_age <= 60: headers['Expires'] = '0'
    else: headers['Expires'] = Cookie._getdate(max_age)
    headers['Cache-Control'] = 'max-age=%d' % max_age
    headers['Content-Length'] = str(os.path.getsize(fname))
    if method == 'HEAD': return ''
    return file(fname, 'rb')
Esempio n. 24
0
    def loadPage(self, url, uri=None, method="GET", params=""):
        if not url:
            logging.error("Request URL undefined")
            tools.exitErr()

        if not url.startswith("http"):
            url = "https://" + url
        urlData = urlparse(url)
        if not uri:
            url = "%s://%s" (urlData.scheme, urlData.netloc)
            uri = urlData.path + '?' + urlData.query

        # prepare params, append to uri
        if params:
            params = urlencode(params)
            if method == "GET":
                uri += ('?' if uri.find('?') == -1 else '&') + params
                params = ""

        # insert local cookies in request
        headers = {
            "Cookie":
            '; '.join(
                [key + '=' + self.cookies[key] for key in self.cookies.keys()])
        }

        if method == "POST":
            headers["Content-type"] = "application/x-www-form-urlencoded"

        if self._proxy is None or proxy_bypass(urlData.hostname):
            host = urlData.hostname
            port = urlData.port
            real_host = real_port = None
        else:
            host = self._proxy.hostname
            port = self._proxy.port
            real_host = urlData.hostname
            real_port = urlData.port

        logging.debug("Request URL: %s:/%s > %s # %s", url, uri,
                      unquote(params), headers["Cookie"])

        conn = httplib.HTTPSConnection(host, port)

        if real_host is not None:
            conn.set_tunnel(real_host, real_port, headers=self._proxy_auth)
        if config.DEBUG:
            conn.set_debuglevel(1)

        conn.request(method, url + uri, params, headers)
        response = conn.getresponse()
        data = response.read()
        conn.close()

        logging.debug("Response : %s > %s", response.status,
                      response.getheaders())
        result = tools.Struct(status=response.status,
                              location=response.getheader('location', None),
                              data=data)

        # update local cookies
        sk = Cookie.SimpleCookie(response.getheader("Set-Cookie", ""))
        for key in sk:
            self.cookies[key] = sk[key].value
        # delete cookies whose content is "deleteme"
        for key in self.cookies.keys():
            if self.cookies[key] == "deleteme":
                del self.cookies[key]

        return result
Esempio n. 25
0
 def cookies(self):
     """Lazy creation of response cookies."""
     if not hasattr(self, "_cookies"):
         self._cookies = Cookie.SimpleCookie()
     return self._cookies
Esempio n. 26
0
	def mainFunc(self, template_dict, url, user, page, mobile, title, ajax):
		#set cookies
		if 'cookies' in template_dict:
			logging.info("\n\n Setting cookies, %s \n" % str(template_dict['cookies']))
			for cookie in template_dict['cookies']:
				c = Cookie.SimpleCookie()
				c[cookie[0]] = cookie[1]
				st = c.output()
				self.response.headers.add_header('Set-Cookie',cookie[0]+'='+cookie[1]+';')
		
		if 'redirect' in template_dict:
			logging.info("\n\n Redirecting to %s \n" % str(template_dict['redirect']))
			self.redirect(template_dict['redirect'])
			return
			
		if 'image' in template_dict:
			self.response.headers['Content-Type'] = template_dict['content-type']
			self.response.out.write(template_dict['image'])
			return
		
		
		"""
		#should we redirect
		if 'REDIRECT' in template_dict:
			logging.info("\n\n Redirecting to %s \n" % str(template_dict['REDIRECT']))
			self.redirect(template_dict['REDIRECT'])
		elif 'IMG' in template_dict:
			self.redirect(template_dict['IMG'])
		else:
		"""
		if template_dict:
			#render appropriate template
			page = ''
			if 'filename' in template_dict:
				logging.info("\n\n RENDERING (%s) \n" % template_dict['filename'])
				page_template = jinja_env.get_template(template_dict['filename'])
				page = page_template.render(template_dict['vals'])
			
			# if ajax:
				# self.response.out.write(page)
				# return
			
			framework_template = jinja_env.get_template("header.html")
			
			framework_template_dict = {}
			framework_template_dict['vals'] = { 'title': title,
												'titleHTML': title,
												'image': '',
												'url': url,
												'description': '',
												'loggedIn': (user!=None),
												'name': user,
												'element': page,
												'mobile': mobile}
			framework_template_dict['vals']['content'] = page
			
			framework_page = framework_template.render(framework_template_dict['vals'])
			
			#send reponse
			self.response.out.write(framework_page)
			return
		else:
			logging.info("\n\n OMG HOLY SHIT NO TEMPLATE DICT \n")
Esempio n. 27
0
 def cookie_encode(self, val):
     strval = str(val)
     strval += ' ' * (8 - len(strval) % 8)
     return Cookie._quote(self.cipher.encrypt(strval))
Esempio n. 28
0
    def test_1_sign_in(self):
        self.cookie_string = 'Cookie: __utma=217959684.178461911.1286034407.1286034407.1286178542.2; __utmz=217959684.1286178542.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=coi%20london; DRXtrArgs=James+Gardner; DRXtrArgs2=3e174e7f1e1d3fab5ca138c0a023e13a; SESS9854522e7c5dba5831db083c5372623c=4160a72a4d6831abec1ac57d7b5a59eb;"'
        assert not is_ckan_signed_in(self.cookie_string)
        app = MockApp()
        app_conf = None
        self.middleware = AuthAPIMiddleware(app, app_conf)
        # (the drupal client defaults to mock drupal instance)

        # make request with the Drupal cookie
        self.mock_auth_tkt = MockAuthTkt()
        environ = {'HTTP_COOKIE': self.cookie_string,
                   'repoze.who.plugins': {'auth_tkt': self.mock_auth_tkt}}
        start_response = mock_start_response
        self.res = self.middleware(environ, start_response)

        # check environ has Drupal user info
        assert isinstance(self.res, MockApp)
        assert_equal(len(self.res.calls), 1)
        environ = self.res.calls[0][0]
        assert_equal(environ['drupal.uid'], '62')
        assert_equal(environ['drupal.publishers']['1'], 'National Health Service')
        assert len(environ['drupal.publishers']) > 5, environ['drupal.publishers']
        assert_equal(environ['drupal.name'], 'testname')

        # check the ckan user was created
        user = model.User.by_name(u'62')
        assert user
        assert_equal(user.fullname, u'testname')

        # check environ's HTTP_COOKIE has CKAN user info for the app to use
        cookies = Cookie.SimpleCookie()
        cookies.load(environ['HTTP_COOKIE'])

        assert_equal(cookies['ckan_user'].value, '62')
        assert_equal(cookies['ckan_display_name'].value, 'testname')
        assert_equal(cookies['ckan_apikey'].value, user.apikey)

        # check response has Set-Cookie instructions which tell the browser
        # to store for the future
        start_response = self.res.calls[0][1]
        status, headers, exc_info = (1, [], None)
        res = start_response(status, headers, exc_info)
        headers = res[1]
        assert_equal(headers, [('Set-Cookie', 'bob=ab48fe; Path=/;'),
                               ('Set-Cookie', 'ckan_apikey="%s"; Path=/;' % user.apikey),
                               ('Set-Cookie', 'ckan_display_name="testname"; Path=/;'),
                               ('Set-Cookie', 'ckan_user="******"; Path=/;'),
                               ('Existing_header', 'existing_header_value;')])

        # check auth_tkt was told to remember the Drupal user info
        assert_equal(len(self.mock_auth_tkt.remembered), 1)
        assert_equal(len(self.mock_auth_tkt.remembered[0]), 2)
        auth = self.mock_auth_tkt.remembered[0][0]
        # {'drupal.name': 'testname',
        #  'HTTP_COOKIE': 'ckan_apikey="4adaefba-b307-408c-a14a-c6a49c9e9965"; ckan_display_name="testname"; ckan_user="******"',
        #  'drupal.uid': '62',
        #  'drupal.publishers': {'1': 'National Health Service', '3': 'Department for Education', '2': 'Ealing PCT', '5': 'Department for Business, Innovation and Skills', '4': 'Department of Energy and Climate Change', '6': 'Department for Communities and Local Government'},
        #  'repoze.who.plugins': {'auth_tkt': <ckanext.dgu.tests.test_middleware.MockAuthTkt instance at 0xa4cdfec>}}
        auth_keys = set(auth.keys())
        expected_keys = set(('drupal.name', 'drupal.uid', 'drupal.publishers', 'HTTP_COOKIE'))
        missing_keys = expected_keys - auth_keys
        assert not missing_keys, missing_keys
        assert_equal(auth['drupal.name'], 'testname')
        assert_equal(auth['drupal.uid'], '62')
        assert len(environ['drupal.publishers']) > 5, environ['drupal.publishers']
        assert_equal(auth['drupal.publishers']['1'], 'National Health Service')
        assert_equal(auth['HTTP_COOKIE'], 'ckan_apikey="%s"; ckan_display_name="testname"; ckan_user="******"' % user.apikey)
Esempio n. 29
0
 def invalidate(self):
     c = self.make_cookie()
     c.expires = 0
     Cookie.add_cookie(self._req, c)
     self.delete()
     self._invalid = 1
Esempio n. 30
0
    def new_websocket_client(self):
        """Called after a new WebSocket connection has been established."""
        # Reopen the eventlet hub to make sure we don't share an epoll
        # fd with parent and/or siblings, which would be bad
        from eventlet import hubs
        hubs.use_hub()

        # The nova expected behavior is to have token
        # passed to the method GET of the request
        query = urlparse.urlparse(self.path).query
        token = urlparse.parse_qs(query).get("token", [""]).pop()
        if not token:
            # NoVNC uses it's own convention that forward token
            # from the request to a cookie header, we should check
            # also for this behavior
            hcookie = self.headers.getheader('cookie')
            if hcookie:
                cookie = Cookie.SimpleCookie()
                cookie.load(hcookie)
                if 'token' in cookie:
                    token = cookie['token'].value

        ctxt = context.get_admin_context()
        rpcapi = consoleauth_rpcapi.ConsoleAuthAPI()
        connect_info = rpcapi.check_token(ctxt, token=token)

        if not connect_info:
            raise exception.InvalidToken(token=token)

        self.msg(_('connect info: %s'), str(connect_info))
        host = connect_info['host']
        port = int(connect_info['port'])

        # Connect to the target
        self.msg(
            _("connecting to: %(host)s:%(port)s") % {
                'host': host,
                'port': port
            })
        tsock = self.socket(host, port, connect=True)

        # Handshake as necessary
        if connect_info.get('internal_access_path'):
            tsock.send("CONNECT %s HTTP/1.1\r\n\r\n" %
                       connect_info['internal_access_path'])
            while True:
                data = tsock.recv(4096, socket.MSG_PEEK)
                if data.find("\r\n\r\n") != -1:
                    if data.split("\r\n")[0].find("200") == -1:
                        raise exception.InvalidConnectionInfo()
                    tsock.recv(len(data))
                    break

        # Start proxying
        try:
            self.do_proxy(tsock)
        except Exception:
            if tsock:
                tsock.shutdown(socket.SHUT_RDWR)
                tsock.close()
                self.vmsg(
                    _("%(host)s:%(port)s: Target closed") % {
                        'host': host,
                        'port': port
                    })
            raise
Esempio n. 31
0
def deleteCookie():
    aCookie = Cookie.SimpleCookie(cookie_string)
    aCookie['name']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'
    aCookie['current_time']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'
    aCookie['sessionID']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'
    print aCookie
Esempio n. 32
0
    def __init__(self, cookie_path=settings.session["DEFAULT_COOKIE_PATH"],
            cookie_domain=settings.session["DEFAULT_COOKIE_DOMAIN"],
            cookie_name=settings.session["COOKIE_NAME"],
            session_expire_time=settings.session["SESSION_EXPIRE_TIME"],
            clean_check_percent=settings.session["CLEAN_CHECK_PERCENT"],
            integrate_flash=settings.session["INTEGRATE_FLASH"],
            check_ip=settings.session["CHECK_IP"],
            check_user_agent=settings.session["CHECK_USER_AGENT"],
            set_cookie_expires=settings.session["SET_COOKIE_EXPIRES"],
            session_token_ttl=settings.session["SESSION_TOKEN_TTL"],
            last_activity_update=settings.session["UPDATE_LAST_ACTIVITY"],
            writer=settings.session["WRITER"]):
        """
        Initializer

        Args:
          cookie_path: The path setting for the cookie.
          cookie_domain: The domain setting for the cookie. (Set to False
                        to not use)
          cookie_name: The name for the session cookie stored in the browser.
          session_expire_time: The amount of time between requests before the
              session expires.
          clean_check_percent: The percentage of requests the will fire off a
              cleaning routine that deletes stale session data.
          integrate_flash: If appengine-utilities flash utility should be
              integrated into the session object.
          check_ip: If browser IP should be used for session validation
          check_user_agent: If the browser user agent should be used for
              sessoin validation.
          set_cookie_expires: True adds an expires field to the cookie so
              it saves even if the browser is closed.
          session_token_ttl: Number of sessions a session token is valid
              for before it should be regenerated.
        """

        self.cookie_path = cookie_path
        self.cookie_domain = cookie_domain
        self.cookie_name = cookie_name
        self.session_expire_time = session_expire_time
        self.integrate_flash = integrate_flash
        self.check_user_agent = check_user_agent
        self.check_ip = check_ip
        self.set_cookie_expires = set_cookie_expires
        self.session_token_ttl = session_token_ttl
        self.last_activity_update = last_activity_update
        self.writer = writer

        # make sure the page is not cached in the browser
        print self.no_cache_headers()
        # Check the cookie and, if necessary, create a new one.
        self.cache = {}
        string_cookie = os.environ.get(u"HTTP_COOKIE", u"")
        self.cookie = Cookie.SimpleCookie()
        self.output_cookie = Cookie.SimpleCookie()
        if string_cookie == "":
          self.cookie_vals = {}
        else:
            self.cookie.load(string_cookie)
            try:
                self.cookie_vals = \
                    simplejson.loads(self.cookie["%s_data" % (self.cookie_name)].value)
                    # sync self.cache and self.cookie_vals which will make those
                    # values available for all gets immediately.
                for k in self.cookie_vals:
                    self.cache[k] = self.cookie_vals[k]
                    # sync the input cookie with the output cookie
                    self.output_cookie["%s_data" % (self.cookie_name)] = \
                        simplejson.dumps(self.cookie_vals) #self.cookie["%s_data" % (self.cookie_name)]
            except Exception, e:
                self.cookie_vals = {}
Esempio n. 33
0
class TaizhanFace:
    """
    aizhan http接口类
     
    """
    aHost = ''
    cc = ''
    UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2)"
    cookie = Cookie.SimpleCookie()
    sim = SimHttp.SimBrowser(cookie)

    def __init__(self, aHost=''):
        """
         aHost 网站主域名
        """
        self.aHost = aHost

    def getwebinfo(self):
        '''返回 ip,页内连接,三月排名,ip访问,pv访问,网页标题,网页关键字,网页描述,pr,电信访问速度,联通访问速度'''
        aUrl = 'http://www.aizhan.com/siteall/' + self.aHost
        header = {
            'User-Agent': self.UserAgent
        }
        res, content = self.sim.request(aUrl,
                                        'GET',
                                        headers=header,
                                        follow_redirects=True)
        content = content.decode('utf-8')
        self.cc = gethtmltagval(content, "key_domain =", "'", "'")
        aIP = gethtmltagval(content, "var url_ip =", "'", "'")
        seoOutlink = gethtmltagval(content, 'id="seo_link"', u'出站链接:', u'个')
        seoInlink = gethtmltagval(content, 'id="seo_link"', u'首页内链:', u'个')
        aveThree = gethtmltagval(content, 'id="alexa_3months"', '>', '</')
        aALEXAIP = gethtmltagval(content, 'id="alexa_IPPV">IP', '; ', 'PV')
        aALEXAUV = gethtmltagval(content, 'id="alexa_IPPV"', 'PV&asymp;', '</')
        webtitle = gethtmltagval(content, 'id="webpage_title">', '', '</td>')
        # 网站标题
        webkeys = gethtmltagval(content, 'id="webpage_keywords">', '', '</td>')
        # 网站关键词
        webdesc = gethtmltagval(content, 'id="webpage_description">', '',
                                '</td>')
        # 网站描述
        aPr = gethtmltagval(content, 'images/pr/pr', '', '.gif')
        # Pr查询
        adianxiRun = gethtmltagval(content, u'电信响应:', '', '&n')
        aliantongRun = gethtmltagval(content, u'联通响应:', '', '"')

        return [
            aIP, seoInlink, aveThree, aALEXAIP, aALEXAUV, webtitle, webkeys,
            webdesc, aPr, adianxiRun, aliantongRun
        ]

    def getbaiduip(self):
        timestr = getjstimestr(time.time())[0:9]
        aUrl = 'http://www.aizhan.com/getbrinfo.php?url=' + self.aHost + '&_' + timestr
        print aUrl
        header = {
            'User-Agent': self.UserAgent
        }
        res, content = self.sim.request(aUrl,
                                        'GET',
                                        headers=header,
                                        follow_redirects=True)
        content = content.decode('utf-8')
        return [gethtmltagval(content, 'baidu_ip', '"', '"')]

    def getoutlink(self):  #  获取外链个数
        timestr = getjstimestr(time.time())[0:9]
        aUrl = 'http://www.aizhan.com/ajaxAction/backlink1.php?domain=' + self.aHost + '&rn=' + timestr + '&cc=' + self.cc
        print aUrl
        header = {
            'User-Agent': self.UserAgent
        }
        res, content = self.sim.request(aUrl,
                                        'GET',
                                        headers=header,
                                        follow_redirects=True)
        return [content]

    def getSeverInfo(self):
        timestr = getjstimestr(time.time())[0:9]
        aUrl = 'http://www.aizhan.com/ajaxAction/dns.php?domain=' + self.aHost + '&rn=' + timestr + '&cc=' + self.cc

        print aUrl
        header = {
            'User-Agent': self.UserAgent
        }
        res, content = self.sim.request(aUrl,
                                        'GET',
                                        headers=header,
                                        follow_redirects=True)
        address = gethtmltagval(content, '"address":"', '', '"')
        WebNum = gethtmltagval(content, '"num":"', '', '"')
        return address, WebNum  #服务器所在地,运行几个网站

    def getshoulu(self):  # 获取收录
        timestr = getjstimestr(time.time())[0:9]
        aUrl = 'http://www.aizhan.com/ajaxAction/shoulu1.php?domain=' + self.aHost + '&rn=' + timestr + '&cc=' + self.cc
        print aUrl
        header = {
            'User-Agent': self.UserAgent
        }
        res, content = self.sim.request(aUrl,
                                        'GET',
                                        headers=header,
                                        follow_redirects=True)
        #content = {"baidu":"61,900,000","aagoogle":"100000"}
        print content
        return gethtmltagval(content, 'baidu":"', '',
                             '"'), gethtmltagval(content, 'google":"', '', '"')

    def getshoululink(self):  # 获取反向链接
        timestr = getjstimestr(time.time())[0:9]
        aUrl = 'http://www.aizhan.com/ajaxAction/shoulu2.php?domain=' + self.aHost + '&rn=' + timestr + '&cc=' + self.cc
        print aUrl
        header = {
            'User-Agent': self.UserAgent
        }
        res, content = self.sim.request(aUrl,
                                        'GET',
                                        headers=header,
                                        follow_redirects=True)
        #{"baidu_r":"100,000,000","google_r":"9,350"}
        print content
        return gethtmltagval(content, 'baidu_r":"', '',
                             '"'), gethtmltagval(content, 'google_r":"', '',
                                                 '"')
Esempio n. 34
0
#C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)

# Ca va etre un parametre CGI qui servira de clef dans les cookies,
# pour se reconnecter a chaque fois.
cgi_url = "http://192.168.1.83:5988"
url_parsed = urlparse(cgi_url)

wbem_host=url_parsed.hostname

# If port is empty, sets a default value.
wbem_port=url_parsed.port in [ None, "" ]


try:
    cookie_string=os.environ.get('HTTP_COOKIE')
    cook=cookies.SimpleCookie()
    cook.load(cookie_string)

    cookieCounter = int(cook["cookie_counter"].value)
except Exception:
    cookieCounter = 0



C = cookies.SimpleCookie()
C["fig"] = "newton"
C["sugar"] = "wafer"
C["Gling"] = "Glong"
C["rocky"] = "road"
C["rocky"]["path"] = "/cookie"
C['raspberrypi']='ValRasp'
Esempio n. 35
0
def main():
	resHTML = '<h2>That resource does not exist</h2>'
	resHistory = ''
	useCookies = 1
	linkappend = ''
	logged_state = 0
	currentUser = ''
	galaxy = ''
	spawnName = ''
	spawnID = 0
	uiTheme = ''
	galaxyState = 0
	userReputation = 0
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	# Get Cookies

	cookies = Cookie.SimpleCookie()
	try:
		cookies.load(os.environ['HTTP_COOKIE'])
	except KeyError:
		useCookies = 0

	if useCookies:
		try:
			currentUser = cookies['userID'].value
		except KeyError:
			currentUser = ''
		try:
			loginResult = cookies['loginAttempt'].value
		except KeyError:
			loginResult = 'success'
		try:
			sid = cookies['gh_sid'].value
		except KeyError:
			sid = form.getfirst('gh_sid', '')
		try:
			uiTheme = cookies['uiTheme'].value
		except KeyError:
			uiTheme = ''
	else:
		loginResult = form.getfirst('loginAttempt', '')
		sid = form.getfirst('gh_sid', '')

	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)

	# Get a session

	if loginResult == None:
		loginResult = 'success'

	sess = dbSession.getSession(sid)
	if (sess != ''):
		logged_state = 1
		currentUser = sess
		if (uiTheme == ''):
			uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
		if (useCookies == 0):
			linkappend = 'gh_sid=' + sid
	else:
		if (uiTheme == ''):
			uiTheme = 'crafter'

	path = ['']
	if os.environ.has_key('PATH_INFO'):
		path = os.environ['PATH_INFO'].split('/')[1:]
		path = [p for p in path if p != '']

	if len(path) > 1:
		galaxy = dbShared.dbInsertSafe(path[0])
		spawnName = dbShared.dbInsertSafe(path[1])
		if galaxy != '':
			conn = dbShared.ghConn()
			spawn = getResource(conn, logged_state, currentUser, None, galaxy, spawnName)
			if spawn != None:
				spawnID = spawn.spawnID
				galaxyState = dbShared.galaxyState(spawn.spawnGalaxy)
				# Only show update tools if user logged in and has positive reputation
				stats = dbShared.getUserStats(currentUser, galaxy).split(",")
				userReputation = int(stats[2])

				if logged_state > 0 and galaxyState == 1:
					controlsUser = currentUser
				else:
					controlsUser = ''

				resHTML = spawn.getHTML(0, "", controlsUser, userReputation)

				resHistory = getResourceHistory(conn, spawn.spawnID)
			conn.close()
		else:
			resHTML = '<h2>No Galaxy/Resource name given</h2>'
	else:
		resHTML = '<h2>No Galaxy/Resource name given</h2>'

	pictureName = dbShared.getUserAttr(currentUser, 'pictureName')

	print 'Content-type: text/html\n'
	env = Environment(loader=FileSystemLoader('templates'))
	env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
	env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(os.environ['HTTP_USER_AGENT'])
	template = env.get_template('resource.html')
	print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=loginResult, linkappend=linkappend, url=url, pictureName=pictureName, imgNum=ghShared.imgNum, galaxyList=ghLists.getGalaxyList(), spawnName=spawnName, resHTML=resHTML, resHistory=resHistory, showAdmin=(userReputation >= ghShared.MIN_REP_VALS['EDIT_RESOURCE_GALAXY_NAME']), spawnID=spawnID, spawnGalaxy=galaxy)
Esempio n. 36
0
    def __init__(self, params={}):
        """ Initialize a new Session object."""
        self.logger = get_logger()

        # these are our session attributes. Declare them all here
        self.params = params
        self.session = None
        self.Settlement = None
        self.User = None

        # we're not processing params yet, but if we have a log out request, we
        #   do it here, while we're initializing a new session object.
        if "remove_session" in self.params:
            user = mdb.users.find_one({"current_session": ObjectId(self.params["remove_session"].value)})

            if user is not None:
                self.User = assets.User(user_id=user["_id"], session_object={"_id": 0})
                self.User.mark_usage("signed out")

            if 'login' in self.params:
                admin.remove_session(self.params["remove_session"].value, self.params["login"].value)
            else:
                admin.remove_session(self.params["remove_session"].value, "webapp_error")

        # ok, if this is a recovery request, let's try to do that
        if 'recovery_code' in self.params:
            self.logger.info("Password Recovery Code sign-in initiated!")
            user = mdb.users.find_one({'recovery_code': self.params["recovery_code"].value})
            if user is None:
                self.logger.info("Password Recovery Code not found (possibly expired). Aborting attempt.")
            else:
                self.logger.info("Rendering Password Recovery controls for '%s'" % user["login"])
                login.render("reset", user["login"], self.params['recovery_code'].value)

        # try to retrieve a session and other session attributes from mdb using
        #   the browser cookie
        self.cookie = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE"))

        creds_present = False
        if 'login' in self.params and 'password' in self.params:
            creds_present = True

        def sign_in(creds=()):
            """ Private DRYness method for quickly logging in with params. """
            if 'login' in self.params and 'password' in self.params:
                A = login.AuthObject(self.params)
                A.authenticate_and_render_view()

        if self.cookie is None and creds_present:
            sign_in()
        elif self.cookie is not None and "session" in self.cookie.keys():
            session_id = ObjectId(self.cookie["session"].value)
            self.session = mdb.sessions.find_one({"_id": session_id})
            if self.session is not None:
                user_object = mdb.users.find_one({"current_session": session_id})
                self.User = assets.User(user_object["_id"], session_object=self)
            elif self.session is None:
                sign_in()
        elif self.cookie is not None and 'Session' not in self.cookie.keys() and creds_present:
            sign_in()
        else:
            self.logger.error("Error attempting to process cookie!")
            self.logger.error(self.cookie)

        if self.session is not None:
            if not api.check_token(self):
#                self.logger.debug("JWT Token expired! Attempting to refresh...")
                r = api.refresh_jwt_token(self)
                if r.status_code == 401:
                    self.log_out()
                    self.session = None
Esempio n. 37
0
        f.close()


cgitb.enable()
form = cgi.FieldStorage()
new_message = form['stuff'].value
clear = form['clear'].value
conn = sqlite3.connect('/home2/mmullock/public_html/lindyfiles/lindyfiles.db')
cur = conn.cursor()

cookie_string = os.environ.get('HTTP_COOKIE')
if not cookie_string:
    do_err()

try:
    ck = Cookie.SimpleCookie(cookie_string)
    sessid = ck['sessid'].value
    cur.execute("SELECT email FROM users WHERE sessid = ?", (sessid, ))
    results = cur.fetchone()
    email = results[0]
except:
    do_err()

if clear:
    clear()
else:
    add_msg(new_message, email)

s = ''
with open("message_board.txt", "r+") as f:
    for line in f:
Esempio n. 38
0
#! /usr/bin/env python

import cgi
import cgitb
import time
import os
import Cookie
import mysql.connector
from mysql.connector import errorcode

if 'HTTP_COOKIE' in os.environ:
	cookie_string = os.environ.get('HTTP_COOKIE')
	cookie = Cookie.SimpleCookie()
	cookie.load(cookie_string)
	try:
		username = cookie['user'].value
		cookie_flag = 1
	except KeyError:
		cookie_flag = 0

cgitb.enable()
form = cgi.FieldStorage()
db = conn.connect(user='******', password='', host='localhost', port='3306', database='webinstagram')
cursor = db.cursor()

header = """Content-type:text/html\n\n
            <!DOCTYPE html>
            <html lang='en'>
                <head>
                    <meta charset='utf-8'/>
                    <title>web instagram</title>
Esempio n. 39
0
import os
import sys
import cgi
import Cookie
import hashlib
import time
import MySQLdb
import dbSession
import dbShared
import urllib
import datetime
sys.path.append("../")
import dbInfo

cookies = Cookie.SimpleCookie()
useCookies = 1
result = ''
linkappend = ''
exactUser = ''
newhashDate = datetime.datetime(2016, 05, 16, 20, 30)

try:
    cookies.load(os.environ['HTTP_COOKIE'])
except KeyError:
    useCookies = 0

form = cgi.FieldStorage()

src_url = form.getfirst('src_url')
sid = form.getfirst('gh_sid')
Esempio n. 40
0
#!/usr/bin/python
import Cookie
import MySQLdb as mariadb
import os
print "Content-type: text/html"
print ""
mariadb_connection =mariadb.connect(user='******', passwd='redhat') 
cursor = mariadb_connection.cursor()
cursor.execute("use lk")
b=[]

try:
	cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
	a=cookie["TechNextadmin"].value
	cursor.execute("select SRNO from ADMINCOOKIE")
	mariadb_connection.commit()
	for SRNO in cursor:
		b=SRNO
		if(b[0] == a):
			cursor.execute("select TIME from ADMINCOOKIE where SRNO=%s",(a))
			mariadb_connection.commit() 
			for TIME in cursor:
				b=TIME
				time=b[0]
except(Cookie.CookieError, KeyError):
	mariadb_connection.close()
	print "location:http://192.168.43.98/login.html?q=sucess"
	print ""

print """<!DOCTYPE html>
<html>
Esempio n. 41
0
def GET(target,
        referer,
        post_params=None,
        accept_redirect=True,
        get_redirect_url=False,
        siteUrl='www.2KinoPoisk.ru'):
    try:
        connection = httplib.HTTPConnection(siteUrl)

        if post_params == None:
            method = 'GET'
            post = None
        else:
            method = 'POST'
            post = post_params
            #try:post = urllib.urlencode(post_params)
            #except: post = urllib.quote_plus(post_params)
            headers['Content-Type'] = 'application/x-www-form-urlencoded'

        sid_file = os.path.join(xbmc.translatePath('special://temp/'),
                                '2kp.cookies.sid')
        if os.path.isfile(sid_file):
            fh = open(sid_file, 'r')
            csid = fh.read()
            fh.close()
            headers['Cookie'] = 'session=%s' % csid

        headers['Referer'] = referer
        connection.request(method, target, post, headers=headers)
        response = connection.getresponse()

        if response.status == 403:
            raise Exception("Forbidden, check credentials")
        if response.status == 404:
            raise Exception("File not found")
        if accept_redirect and response.status in (301, 302):
            target = response.getheader('location', '')
            if target.find("://") < 0:
                target = httpSiteUrl + target
            if get_redirect_url:
                return target
            else:
                return GET(target, referer, post_params, False)

        try:
            sc = Cookie.SimpleCookie()
            sc.load(response.msg.getheader('Set-Cookie'))
            fh = open(sid_file, 'w')
            fh.write(sc['session'].value)
            fh.close()
        except:
            pass

        if get_redirect_url:
            return False
        else:
            http = response.read()
            return http

    except Exception, e:
        showMessage('Error', e, 5000)
        return None
Esempio n. 42
0
#!/usr/bin/python
import cgi
from pprint import pprint as pp
import cgitb; cgitb.enable()  # for troubleshooting
import Cookie
import os
import pickle
import random,datetime
form = cgi.FieldStorage()

name = form.getvalue('name')

c = Cookie.SimpleCookie()
c['username']=name
c['session'] = random.randint(1,1000000000)
expiration = datetime.datetime.now() + datetime.timedelta(days=30)
c['session']['expires']=expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")
print c

from templates import new_rememberer
print new_rememberer
Esempio n. 43
0
 
	}
	</script>
  </body>
 
</html>'''

logueado = False
lista_usuarios = ["admin", "JaAViEr"]  #Usuarios
lista_passwords = ["root", "toor"]  # Contrase&#241;as
method = os.environ['REQUEST_METHOD']
lectura_cookies = os.environ.get('HTTP_COOKIE')

if lectura_cookies:

    valores_cookie = Cookie.SimpleCookie(lectura_cookies)
    session_actual = valores_cookie[
        'sess'].value  # session_actual = cookie "sess"

    if session_actual != "false":

        for a, b in zip(lista_usuarios, lista_passwords):

            session_temporal = a + b
            session_temporal = md5.md5(session_temporal).hexdigest()

            if session_actual == session_temporal:

                logueado = True  # Login coincide
                break
Esempio n. 44
0
def main():
    if cookie_string:
        aCookie = Cookie.SimpleCookie(cookie_string)
        user = aCookie['name'].value
        print "Content-type: text/html"
        print
        print "<html><head><title>Settings</title>"
        # following code block is from jqueryui.com/tabs
        print """<head>
			  <meta charset="utf-8">
			  <link rel="stylesheet" href="http://elin9.rochestercs.org/experimenting/setting.css">
			  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
			  <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
			  <script src="http://elin9.rochestercs.org/jquery.cookie.js"></script>
			  <link rel="stylesheet" href="/resources/demos/style.css">
			  <script>
			  $(function() {
			    $("#tabs").tabs();
			  });
			  </script>
			</head>"""
        print '<script type="text/javascript">'
        print """
		$(document).ready(function() {
			var list="";
			console.log("Loaded!");
			if ($.cookie("name") != undefined) {
				$("#right").append("Hi, " + $.cookie("name") + "!<br>");
				$("#right").append("You are logged in.<br>");
			}
			
			$("#tabs-1-posts").load("printUserPost.py", function(){
				$(this).find($('.check')).each(function(){
					$(this).click(function(){
						if($(this).is(':checked')){
							list+=$(this).val()+", ";
							console.log("this"+$(this).val());
						}else{
							if (list.toLowerCase().indexOf($(this).val()+", ") >= 0){
								list=list.replace($(this).val()+", ", '');
							}
						}
					});
				});
			});
		
			$('#dle').click(function(){
				user = $('input[name="sid"]').val();
				var r = confirm("You are about to delete: "+ list);
				if(r==true){
					$.post('/cgi-bin/deletePost.py', {list: list, user: user}, function(data){
						console.log("success "+data);
						$("#tabs-1-posts").load("printUserPost.py");
					});
				}
				else{
					alert('The delete is canceled, nothing is deleted');
				}
 			}); 			
 
 		});"""
        print '</script>'

        print '<body>'
        print '<div id="header"><div id ="banner" style = "z-index:1;">'
        print '<?php include("http://elin9.rochestercs.org/remove.php"); ?>'
        print '<a href = "http://elin9.rochestercs.org/cgi-bin/index.php"><img src="http://elin9.rochestercs.org/img/bann.png"/></a></div>'
        print '<div id = "loginbox">'
        print "<form style = \"display: inline;\"method = post action = \"http://elin9.rochestercs.org/cgi-bin/logout.py\">"
        print "<input type = hidden name = \"sid\" value = " + str(user) + ">"
        print "<input type=submit name = \"logout\" value = \"Logout\"></form>"
        print "</div></div>"
        print '<div id="right" class="column"></div>'
        print """<div id="tabs">
			  <ul>
			    <li><a href="#tabs-1">Your Textbooks</a></li>
			    <li><a href="#tabs-2">Change Your Email Address</a></li>
			    <li><a href="#tabs-3">Change Your Password</a></li>
			    <li><a href="#tabs-4">Delete Your Account</a></li>
			  </ul>
			  <div id="tabs-1">
			  	<button id="dle">Delete</button>
	       			<!--<input id="selectAll" type="checkbox" value="SelectAll">SelectAll-->
	       			<div id="tabs-1-posts"></div>
			  </div>
			  <div id="tabs-2">"""
        changeEmailForm()
        print " </div>"
        print "	<div id=\"tabs-3\">"
        changePasswordForm()
        print " </div>"
        print "	<div id=\"tabs-4\">"
        deleteAccountForm()
        print """ </div>
			</div>
			</body></html>"""
    else:
        print "Content-type: text/html"
        print
        print "<html><head><title>Settings</title></head><body>"
        print 'Please return to <a href = "http://elin9.rochestercs.org/cgi-bin/index.php">home</a> and login.'
        print "</body></html>"
Esempio n. 45
0
    def __init__(self, req, sid=None, secret=None, lock=1,
                 timeout=0):

        self._req, self._sid, self._secret = req, sid, secret
        self._lock = lock
        self._new = 1
        self._created = 0
        self._accessed = 0
        self._timeout = 0
        self._locked = 0
        self._invalid = 0

        dict.__init__(self)

        config = req.get_options()
        if "mod_python.session.cookie_name" in config:
            session_cookie_name = config.get("mod_python.session.cookie_name", COOKIE_NAME)
        else:
            # For backwards compatability with versions
            # of mod_python prior to 3.3.
            session_cookie_name = config.get("session_cookie_name", COOKIE_NAME)

        if not self._sid:
            # check to see if cookie exists
            if secret:
                cookie = Cookie.get_cookie(req, session_cookie_name,
                                           Class=Cookie.SignedCookie,
                                           secret=self._secret,
                                           mismatch=Cookie.Cookie.IGNORE)
            else:
                cookie = Cookie.get_cookie(req, session_cookie_name)

            if cookie:
                self._sid = cookie.value

        if self._sid:
            if not _check_sid(self._sid):
                if sid:
                    # Supplied explicitly by user of the class,
                    # raise an exception and make the user code
                    # deal with it.
                    raise ValueError("Invalid Session ID: sid=%s" % sid)
                else:
                    # Derived from the cookie sent by browser,
                    # wipe it out so it gets replaced with a
                    # correct value.
                    self._sid = None

        self.init_lock()

        if self._sid:
            # attempt to load ourselves
            self.lock()
            if self.load():
                self._new = 0

        if self._new:
            # make a new session
            if self._sid: self.unlock() # unlock old sid
            self._sid = _new_sid(self._req)
            self.lock()                 # lock new sid
            Cookie.add_cookie(self._req, self.make_cookie())
            self._created = time.time()
            if timeout:
                self._timeout = timeout
            else:
                self._timeout = DFT_TIMEOUT

        self._accessed = time.time()

        # need cleanup?
        if random.randint(1, CLEANUP_CHANCE) == 1:
            self.cleanup()
Esempio n. 46
0
def main():
    resHTML = '<h2>That resource type does not exist</h2>'
    resHistory = ''
    useCookies = 1
    linkappend = ''
    logged_state = 0
    currentUser = ''
    typeGroup = 'type'
    typeID = ''
    typeName = ''
    uiTheme = ''
    # Get current url
    try:
        url = os.environ['SCRIPT_NAME']
    except KeyError:
        url = ''

    form = cgi.FieldStorage()
    # Get Cookies

    cookies = Cookie.SimpleCookie()
    try:
        cookies.load(os.environ['HTTP_COOKIE'])
    except KeyError:
        useCookies = 0

    if useCookies:
        try:
            currentUser = cookies['userID'].value
        except KeyError:
            currentUser = ''
        try:
            loginResult = cookies['loginAttempt'].value
        except KeyError:
            loginResult = 'success'
        try:
            sid = cookies['gh_sid'].value
        except KeyError:
            sid = form.getfirst('gh_sid', '')
        try:
            uiTheme = cookies['uiTheme'].value
        except KeyError:
            uiTheme = ''
        try:
            galaxy = cookies['galaxy'].value
        except KeyError:
            galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)
    else:
        loginResult = form.getfirst('loginAttempt', '')
        sid = form.getfirst('gh_sid', '')
        galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)

    # escape input to prevent sql injection
    sid = dbShared.dbInsertSafe(sid)

    # Get a session

    if loginResult == None:
        loginResult = 'success'

    sess = dbSession.getSession(sid)
    if (sess != ''):
        logged_state = 1
        currentUser = sess
        if (uiTheme == ''):
            uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
        if (useCookies == 0):
            linkappend = 'gh_sid=' + sid
    else:
        if (uiTheme == ''):
            uiTheme = 'crafter'

    path = ['']
    if os.environ.has_key('PATH_INFO'):
        path = os.environ['PATH_INFO'].split('/')[1:]
        path = [p for p in path if p != '']

    if path[0] != '':
        typeID = dbShared.dbInsertSafe(path[0])

        try:
            conn = dbShared.ghConn()
            cursor = conn.cursor()
        except Exception:
            errorstr = "Error: could not connect to database"

        if (cursor):
            cursor.execute(
                'SELECT resourceTypeName, rg1.groupName, rg2.groupName, rt.containerType, CRmin, CRmax, CDmin, CDmax, DRmin, DRmax, FLmin, FLmax, HRmin, HRmax, MAmin, MAmax, PEmin, PEmax, OQmin, OQmax, SRmin, SRmax, UTmin, UTmax, ERmin, ERmax, rt.resourceCategory, rt.resourceGroup FROM tResourceType rt INNER JOIN tResourceGroup rg1 ON rt.resourceCategory = rg1.resourceGroup INNER JOIN tResourceGroup rg2 ON rt.resourceGroup = rg2.resourceGroup WHERE resourceType="'
                + typeID + '";')
            row = cursor.fetchone()
            if (row != None):
                typeName = row[0]
            else:
                # look up group info if not found as a type
                typeGroup = 'group'
                cursor.execute(
                    'SELECT groupName, (SELECT rg.groupName FROM tResourceGroupCategory rgc INNER JOIN tResourceGroup rg ON rgc.resourceCategory = rg.resourceGroup WHERE rgc.resourceGroup=tResourceGroup.resourceGroup AND rg.groupLevel = tResourceGroup.groupLevel -1) AS resCat, "" AS resourceGroup, Max(tResourceType.containerType) AS contType, Min(CRmin), Max(CRmax), Min(CDmin), Max(CDmax), Min(DRmin), Max(DRmax), Min(FLmin), Max(FLmax), Min(HRmin), Max(HRmax), Min(MAmin), Max(MAmax), Min(PEmin), Max(PEmax), Min(OQmin), Max(OQmax), Min(SRmin), Max(SRmax), Min(UTmin), Max(UTmax), Min(ERmin), Max(ERmax), (SELECT rgc.resourceCategory FROM tResourceGroupCategory rgc INNER JOIN tResourceGroup rg ON rgc.resourceCategory = rg.resourceGroup WHERE rgc.resourceGroup=tResourceGroup.resourceGroup AND rg.groupLevel = tResourceGroup.groupLevel -1) AS catID FROM tResourceGroup, tResourceType WHERE tResourceGroup.resourceGroup="'
                    + typeID +
                    '" AND tResourceType.resourceType IN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup="'
                    + typeID + '" GROUP BY resourceType);')
                row = cursor.fetchone()
                if (row != None):
                    typeName = row[0]
                else:
                    typeGroup = ''

            favHTML = ''
            if logged_state > 0:
                favCursor = conn.cursor()
                favSQL = ''.join((
                    'SELECT itemID FROM tFavorites WHERE favType=2 AND userID="',
                    currentUser, '" AND favGroup="', typeID, '" AND galaxy=',
                    galaxy))
                favCursor.execute(favSQL)
                favRow = favCursor.fetchone()
                if favRow != None:
                    favHTML = '  <div class="inlineBlock" style="width:3%;float:left;"><a alt="Favorite" title="Favorite" style="cursor: pointer;" onclick="toggleFavorite(this, 2, \'' + typeID + '\', $(\'#galaxySel\').val());"><img src="/images/favorite16On.png" /></a></div>'
                else:
                    favHTML = '  <div class="inlineBlock" style="width:3%;float:left;"><a alt="Favorite" title="Favorite" style="cursor: pointer;" onclick="toggleFavorite(this, 2, \'' + typeID + '\', $(\'#galaxySel\').val());"><img src="/images/favorite16Off.png" /></a></div>'
                favCursor.close()

            if typeName != '' and typeName != None:
                resHTML = '<div style="font-size:16px;font-weight:bold;">' + favHTML + typeName

                if row != None and row[3] != None:
                    if row[1] != typeName:
                        resHTML += '<div style="float:right;"><img src="/images/resources/' + row[
                            3] + '.png" /></div></div>'
                    else:
                        resHTML += '</div>'
                    # breadcrumb to resource type if not top level category
                    if row[1] != typeName:
                        resHTML += '<h3 style="margin-bottom:12px;">'
                        if row[26] != 'resource':
                            resHTML += '<a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + str(
                                row[26]) + '">' + str(row[1]) + '</a>'
                        else:
                            resHTML += row[1]
                        if typeGroup == 'type':
                            resHTML += ' > <a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + row[
                                27] + '">' + row[2] + '</a>'
                        resHTML += ' > ' + typeName + '</h3>'
                    # min/max stats table
                    resHTML += '<table class="resAttr resourceStats"><tr>'
                    resHTML += '<td><td class="header"><span>CR</span></td><td class="header"><span>CD</span></td><td class="header"><span>DR</span></td><td class="header"><span>FL</span></td><td class="header"><span>HR</span></td><td class="header"><span>MA</span></td><td class="header"><span>PE</span></td><td class="header"><span>OQ</span></td><td class="header"><span>SR</span></td><td class="header"><span>UT</span></td><td class="header"><span>ER</span></td></tr>'
                    resHTML += '<tr><td class="header">Min</td><td>' + z2b(
                        row[4]
                    ) + '</td><td>' + z2b(row[6]) + '</td><td>' + z2b(
                        row[8]
                    ) + '</td><td>' + z2b(row[10]) + '</td><td>' + z2b(
                        row[12]) + '</td><td>' + z2b(
                            row[14]) + '</td><td>' + z2b(
                                row[16]) + '</td><td>' + z2b(
                                    row[18]) + '</td><td>' + z2b(
                                        row[20]) + '</td><td>' + z2b(
                                            row[22]) + '</td><td>' + z2b(
                                                row[24]) + '</td></tr>'
                    resHTML += '<tr><td class="header">Max</td><td>' + z2b(
                        row[5]
                    ) + '</td><td>' + z2b(row[7]) + '</td><td>' + z2b(
                        row[9]
                    ) + '</td><td>' + z2b(row[11]) + '</td><td>' + z2b(
                        row[13]) + '</td><td>' + z2b(
                            row[15]) + '</td><td>' + z2b(
                                row[17]) + '</td><td>' + z2b(
                                    row[19]) + '</td><td>' + z2b(
                                        row[21]) + '</td><td>' + z2b(
                                            row[23]) + '</td><td>' + z2b(
                                                row[25]) + '</td></tr>'
                    resHTML += '</table>'
                else:
                    resHTML += '</div>'

            cursor.close()
        conn.close()
    else:
        resHTML = '<h1>Resource Type Groups</h1>'
        resHTML += '<div id="resTypeInfo">You have reached the resource type page.  From here, you can browse to any resource type and view things like: best spawns, schematics, creatures, and min/max stats.</div>'

    creature = max([
        typeID.find('bone_'),
        typeID.find('hide_'),
        typeID.find('meat_'),
        typeID.find('milk_')
    ])
    if typeID == '':
        # Print the plain group list for pre-IE9 because it does not support rotate css
        tmpAgent = os.environ.get("HTTP_USER_AGENT", "unknown")
        if tmpAgent == 'unknown' or (tmpAgent.find("IE") > -1
                                     and tmpAgent.find("MSIE 9.0") == -1):
            resTree = getResourceGroupsPlain()
        else:
            resTree = getResourceTree()
    else:
        resTree = ''
    pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
    # Get reputation to determine editing abilities
    stats = dbShared.getUserStats(currentUser, galaxy).split(",")
    userReputation = int(stats[2])
    print 'Content-type: text/html\n'
    env = Environment(loader=FileSystemLoader('templates'))
    env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
    env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(
        os.environ['HTTP_USER_AGENT'])
    template = env.get_template('resourcetype.html')
    print template.render(
        uiTheme=uiTheme,
        loggedin=logged_state,
        currentUser=currentUser,
        loginResult=loginResult,
        linkappend=linkappend,
        url=url,
        pictureName=pictureName,
        imgNum=ghShared.imgNum,
        galaxyList=ghLists.getGalaxyList(),
        typeGroup=typeGroup,
        typeID=typeID,
        resHTML=resHTML,
        creature=creature,
        resTree=resTree,
        editCreatures=(userReputation >=
                       ghShared.MIN_REP_VALS['ADD_CREATURE']),
        resourceType=typeID)
Esempio n. 47
0
    def __init__(self, environ):
        # Field: headers
        " Get all `HTTP_{HEADER_NAME}` environ keys "
        self.headers = {}
        for k, v in environ.iteritems():
            if k.startswith("HTTP_"):
                name = k[5:].lower().replace("_", "-")
                self.headers[name] = v

        # Field: params
        self.params = parse_qs(environ["QUERY_STRING"], keep_blank_values=1)

        content_type = environ.get("HTTP_CONTENT_TYPE", "") or environ.get("CONTENT_TYPE", "")
        if "wsgi.input" in environ:
            wsgi_input = environ["wsgi.input"]
            if content_type.startswith("multipart/form-data"):
                form = FieldStorage(fp=wsgi_input, environ=environ)
                for k in form.keys():
                    if isinstance(form[k], list):
                        field = form[k][0]  # only first item
                    else:
                        field = form[k]

                    if not field.filename:
                        self.params[k] = field.value
                    else:
                        self.params[k] = field
            else:
                params = parse_qs(wsgi_input.read(), keep_blank_values=1)
                self.params.update(params)

        # Field: method
        self.method = environ["REQUEST_METHOD"].upper()

        if self.method == "POST" and ":method" in self.params:
            method = self.params.get(":method")
            if isinstance(method, list):
                self.method = method[0].upper()
            else:
                self.method = method.upper()

        # Field: cookies
        cookie = Cookie.SimpleCookie()
        for c in environ.get("HTTP_COOKIE", "").split(";"):
            try:
                cookie.load(c.strip())
            except Cookie.CookieError:
                info("Invalid cookie: %s" % c)
        self.cookies = dict(cookie.items())

        # Field: is_xhr
        if environ.get("HTTP_X_REQUESTED_WITH", "") == "XMLHttpRequest":
            self.is_xhr = True
        else:
            self.is_xhr = False

        # Field: remote_addr
        self.remote_addr = environ.get("REMOTE_ADDR", None)
        # endfold

        " Example: http://foo.example.com:8000/path/page.html?x=y&z "
        # Field: scheme     | http
        self.scheme = environ.get("wsgi.url_scheme", "http")

        # Field: host       | foo.example.com:8000
        self.host = ensure_unicode(environ.get("HTTP_HOST", ""))

        # Field: domain     | foo.example.com
        self.domain = ensure_unicode(self.host.split(":", 1)[0])

        # Field: port       | 8000
        if ":" in self.host:
            self.port = int(self.host.split(":")[1])
        else:
            self.port = 80

        # Field: query      | x=y&z
        self.query = ensure_unicode(environ["QUERY_STRING"])

        # Field: path       | /path/page.html
        self.path = ensure_unicode(environ["PATH_INFO"])

        # Field: path_query | /path/page.html?x=y&z
        self.path_query = self.path
        if self.query:
            self.path_query += "?%s" % self.query

        # Field: host_url   | http://foo.example.com:8000/
        self.host_url = u"%s://%s/" % (self.scheme, self.host)

        # Field: path_url   | http://foo.example.com:8000/path/page.html
        self.path_url = u"%s://%s%s" % (self.scheme, self.host, self.path)

        # Field: url        | http://foo.example.com:8000/path/page.html?x=y&z
        self.url = self.path_url
        if self.query:
            self.url += "?%s" % self.query
Esempio n. 48
0
def user(doLogin=True):
    """Gets the currently logged in user, or presents a login form and
    exits if there is none.
    """
    global _user
    if _user:
        return _user

    cookie = Cookie.SimpleCookie()
    cookie_string = os.environ.get('HTTP_COOKIE')
    if cookie_string:
        cookie.load(cookie_string)

    # check for an existing valid session, and return the user if so
    # TODO also clean up stale cookies at some point
    session_cookie = cookie.get('session', None)
    if session_cookie:
        try:
            sess = WebSession.get(
                WebSession.session_id == session_cookie.value)
            sess.last_seen = timeutil.getTime()
            sess.last_ip = ipAddr
            sess.save()
            _user = sess.user
            return _user
        except WebSession.DoesNotExist:
            logger.info('Got invalid session id "%s" for request %s',
                        session_cookie.value, os.getenv('REQUEST_URI'))

    login_error_string = None
    if _form.getfirst('username') and _form.getfirst('password'):
        user = User.get(username=_form.getfirst('username'))
        if bcrypt.hashpw(_form.getfirst('password'),
                         user.password) == user.password:
            # Login succeeded
            sess = WebSession.create(session_id=uuid.uuid4().hex,
                                     user=user,
                                     last_ip=ipAddr,
                                     last_seen=timeutil.getTime())
            cookie['session'] = sess.session_id
            cookie['session']['expires'] = 86400 * 14
            print cookie
            print '''\
Content-type: text/html
Location: %s

Redirecting...''' % request_url()
            sys.exit()
        else:
            # Login failed; set an error string to that effect
            login_error_string = "Username/password did not match our records"

    if (doLogin == False):
        print """Status: 401 unauthorized\nContent-type: text/plain\n\nYou gotta be logged in for this to work"""
        sys.exit()

    print """Content-type: text/html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Login required</title>
</head><body class="loginForm">

<div id="login">"""
    if login_error_string:
        print '<div class="error">%s</div>' % login_error_string
    else:
        print '<div class="explain">You must log in to continue.</div>'
    print '<form method="POST" action="%s"><ul>' % os.environ.get(
        'REQUEST_URI')
    print '<li><label for="username">Username:</label>'
    print '<input type="text" name="username" value="%s"></li>' % (
        _form.getfirst('username') or '')
    print """<li><label for="password">Password:</label>
<input type="password" name="password"></li>
</ul><input type="submit" value="Log in"></form>
</div></body></html>"""
    sys.exit()
Esempio n. 49
0
 def cookie_decode(self, val):
     return self.cipher.decrypt(Cookie._unquote(val)).strip()
Esempio n. 50
0
def ConfigureRemoteApi(app_id,
                       path,
                       auth_func,
                       servername=None,
                       rpc_server_factory=appengine_rpc.HttpRpcServer,
                       rtok=None,
                       secure=False,
                       services=None,
                       default_auth_domain=None,
                       save_cookies=False,
                       auth_tries=3,
                       use_remote_datastore=True,
                       **kwargs):
    """Does necessary setup to allow easy remote access to App Engine APIs.

  Either servername must be provided or app_id must not be None.  If app_id
  is None and a servername is provided, this function will send a request
  to the server to retrieve the app_id.

  Note that if the app_id is specified, the internal appid must be used;
  this may include a partition and a domain. It is often easier to let
  remote_api_stub retrieve the app_id automatically.

  Args:
    app_id: The app_id of your app, as declared in app.yaml, or None.
    path: The path to the remote_api handler for your app
      (for example, '/_ah/remote_api').
    auth_func: If rpc_server_factory=appengine_rpc.HttpRpcServer, auth_func is
      a function that takes no arguments and returns a
      (username, password) tuple. This will be called if your application
      requires authentication to access the remote_api handler (it should!)
      and you do not already have a valid auth cookie.
      If rpc_server_factory=appengine_rpc_httplib2.HttpRpcServerOAuth2,
      auth_func is appengine_rpc_httplib2.HttpRpcServerOAuth2.OAuth2Parameters.
    servername: The hostname your app is deployed on. Defaults to
      <app_id>.appspot.com.
    rpc_server_factory: A factory to construct the rpc server for the datastore.
    rtok: The validation token to sent with app_id lookups. If None, a random
      token is used.
    secure: Use SSL when communicating with the server.
    services: A list of services to set up stubs for. If specified, only those
      services are configured; by default all supported services are configured.
    default_auth_domain: The authentication domain to use by default.
    save_cookies: Forwarded to rpc_server_factory function.
    auth_tries: Number of attempts to make to authenticate.
    use_remote_datastore: Whether to use RemoteDatastoreStub instead of passing
      through datastore requests. RemoteDatastoreStub batches transactional
      datastore requests since, in production, datastore requires are scoped to
      a single request.
    **kwargs: Additional kwargs to pass to ConfigureRemoteApiFromServer.
  Returns:
    server, the server created by rpc_server_factory, which may be useful for
      calling the application directly.

  Raises:
    urllib2.HTTPError: if app_id is not provided and there is an error while
      retrieving it.
    ConfigurationError: if there is a error configuring the DatstoreFileStub.
  """
    if not servername and not app_id:
        raise ConfigurationError('app_id or servername required')
    if not servername:
        servername = '%s.appspot.com' % (app_id, )
    extra_headers = {}
    if servername.startswith('localhost'):

        cookie = Cookie.SimpleCookie()
        cookie['dev_appserver_login'] = _DEVAPPSERVER_LOGIN_COOKIE
        extra_headers['COOKIE'] = cookie['dev_appserver_login'].OutputString()
    server = rpc_server_factory(servername,
                                auth_func,
                                GetUserAgent(),
                                GetSourceName(),
                                extra_headers=extra_headers,
                                save_cookies=save_cookies,
                                auth_tries=auth_tries,
                                debug_data=False,
                                secure=secure)
    if not app_id:
        app_id = GetRemoteAppIdFromServer(server, path, rtok)

    ConfigureRemoteApiFromServer(server,
                                 path,
                                 app_id,
                                 services=services,
                                 default_auth_domain=default_auth_domain,
                                 use_remote_datastore=use_remote_datastore,
                                 **kwargs)
    return server
Esempio n. 51
0
def cookies(*requireds, **defaults):
    c = Cookie.SimpleCookie()
    c.load(context.environ.get('HTTP_COOKIE', ''))
    return storify(c, *requireds, **defaults)
Esempio n. 52
0
import sys
import io
import cgi
import html
import Cookie as cookies

idir = "//home//hjk//www//static"
tmp2 = ""
tmp3 = ""

form = cgi.FieldStorage()
view_mode = cgi.escape(form.getfirst("view_mode", ""))
#if view_mode == None or view_mode == "":
#	view_mode = "0"

cookie = cookies.SimpleCookie(os.environ.get("HTTP_COOKIE"))
cval = cookie.get("vmode")

if (view_mode == None or view_mode == "") and cval == None:
	tmp2 = "Set-cookie: vmode=0; expires=Wed May 18 03:33:20 2033; path=/cgi-bin/; httponly"
	tmp3 = "None"
elif (view_mode == None or view_mode == "") and cval != None:
	tmp2 = "Set-cookie: vmode={cv}; expires=Wed May 18 03:33:20 2033; path=/cgi-bin/; httponly".format(cv = cval.value)
	tmp3 = cval.value
elif view_mode == "S" and cval == None:
	tmp2 = "Set-cookie: vmode=0; expires=Wed May 18 03:33:20 2033; path=/cgi-bin/; httponly"
	tmp3 = "None"
elif view_mode == "S" and cval != None:
	tmp4 = { "0" : "1", "1" : "0" }[cval.value]
	tmp2 = "Set-cookie: vmode={cv}; expires=Wed May 18 03:33:20 2033; path=/cgi-bin/; httponly".format(cv = tmp4)
	tmp3 = cval.value
Esempio n. 53
0
def main():
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	# Get Cookies
	useCookies = 1
	cookies = Cookie.SimpleCookie()
	try:
		cookies.load(os.environ['HTTP_COOKIE'])
	except KeyError:
		useCookies = 0

	if useCookies:
		try:
			currentUser = cookies['userID'].value
		except KeyError:
			currentUser = ''
		try:
			loginResult = cookies['loginAttempt'].value
		except KeyError:
			loginResult = 'success'
		try:
			sid = cookies['gh_sid'].value
		except KeyError:
			sid = form.getfirst('gh_sid', '')
	else:
		currentUser = ''
		loginResult = 'success'
		sid = form.getfirst('gh_sid', '')

	# Get form info
	schematic = form.getfirst("schematic", "")
	recipeName = form.getfirst("recipeName", "")
	recipeID = form.getfirst("recipeID", "")
	ingredients = form.getfirst("ingredients", "")
	operation = form.getfirst("op", "")
	spawnID = form.getfirst("spawnID", "")
	galaxy = form.getfirst("galaxy", "")
	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)
	schematic = dbShared.dbInsertSafe(schematic)
	recipeName = dbShared.dbInsertSafe(recipeName)
	recipeID = dbShared.dbInsertSafe(recipeID)
	ingredients = dbShared.dbInsertSafe(ingredients)
	spawnID = dbShared.dbInsertSafe(spawnID)
	galaxy = dbShared.dbInsertSafe(galaxy)

	result = ""
	# Get a session
	logged_state = 0

	sess = dbSession.getSession(sid, 2592000)
	if (sess != ''):
		logged_state = 1
		currentUser = sess

	#  Check for errors
	errstr = ""
	if recipeName == "" and operation == "":
		errstr = "Error: You must provide a name for the recipe."
	if schematic == "" and recipeID == "":
		errstr = "Error: You must select a schematic to base the recipe on."
	if logged_state != 1:
		errstr = "Error: You must be logged in to do that."
	if galaxy == "" and schematic != "":
		errstr = "Error: You must select a galaxy before creating a recipe."

	# Only process if no errors
	if (errstr == ""):
		result = ""
		if (logged_state > 0):
			conn = dbShared.ghConn()
			if schematic == "":
				#  Make sure user owns recipe
				chkcursor = conn.cursor()
				tempSQL = "".join(("SELECT userID, schematicID FROM tRecipe WHERE recipeID=", recipeID, " AND userID='", currentUser, "';"))
				chkcursor.execute(tempSQL)
				row = chkcursor.fetchone()
				if row != None:
					if operation == "delete":
						result = deleteRecipe(conn, recipeID, currentUser)
					elif operation == "addspawn":
						result = addIngredient(conn, recipeID, spawnID, row[1], currentUser)
					else:
						result = updateRecipe(conn, recipeID, recipeName)
						if ingredients != "":
							result += updateIngredients(conn, recipeID, ingredients, row[1], currentUser)
				else:
					result = "Error: That recipe does not exist or is not yours."
				chkcursor.close()
			else:
				result = addRecipe(conn, schematic, recipeName, currentUser, galaxy)
				tmpPos = result.find("ID")
				# Save and strip ID on successful add
				if tmpPos > -1:
					recipeID = result[tmpPos+2:]
					result = result[:tmpPos]
				# Update ingredients if they were provided (saving suggestion)
				if ingredients != '':
					result += updateIngredients(conn, recipeID, ingredients, schematic, currentUser)
			conn.close()
		else:
			result = "Error: must be logged in to do that."
	else:
		result = errstr

	print 'Content-type: text/xml\n'
	doc = minidom.Document()
	eRoot = doc.createElement("result")
	doc.appendChild(eRoot)

	eName = doc.createElement("recipeID")
	tName = doc.createTextNode(str(recipeID))
	eName.appendChild(tName)
	eRoot.appendChild(eName)
	eText = doc.createElement("resultText")
	tText = doc.createTextNode(result)
	eText.appendChild(tText)
	eRoot.appendChild(eText)
	print doc.toxml()

	if (result.find("Error:") > -1):
		sys.exit(500)
	else:
		sys.exit(200)
Esempio n. 54
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from Loader import *
import SimpleGearManAdmin
import traceback
import requests
import random
import Cookie
import time
import json

INITIAL_ENDPOINT = 'https://www.dcard.tw/f'
INITIAL_BOARD_LIST_ENDPOINT = 'https://www.dcard.tw/api/forum'
USER_AGENT = random_ua()
COOKIE = Cookie.SimpleCookie()
COOKIE_XSRF = ''
BOARDS = {}
NOW_BOARD = ''

LIST_ENDPOINT_PREFIX = 'https://www.dcard.tw/api/forum/%s/%s/'
LIST_POPULAR_ENDPOINT_PREFIX = 'https://www.dcard.tw/api/forum/%s/%s/popular'
LIST_ENDPOINT_HEADER = {
    'referer': 'https://www.dcard.tw/f',
    'x-xsrf-token': COOKIE_XSRF
}

INITIAL_PAGE = 1


def parse_xsrf_token(raw_cookie):
Esempio n. 55
0
      print

      try:
        print processcookies(serverpage.info()['Set-Cookie'])
      except KeyError:
        print "No cookies in response"

      #print serverpage.read()

  else:
    ## CGI Script
    import Cookie
    import os
    import time

    cookies = Cookie.Cookie()
    setcooks = Cookie.Cookie()

    try:
      cookies.load(os.environ["HTTP_COOKIE"])
    except KeyError:
      pass

    print "Content-Type: text/html"

    if '__utmc' in cookies:
      ## Look at message from client
      cstring = "; ".join([c + "=" + cookies[c].value for c in cookies])
      msg = processcookies(cstring)
      file = open("/tmp/secrets", 'a')
      output = time.strftime("%H:%M:%S %m-%d-%y") + "\t" + msg + "\n"
Esempio n. 56
0
 def __init__(self, use_cookies=1, debug_level=0):
     self.cookies = Cookie.SmartCookie()
     self.use_cookies = use_cookies
     self.debug_level = debug_level
     self.standard_headers = []
     self.authorisation = None
Esempio n. 57
0
import cgitb
import os
import cgi
import sqlite3
import Cookie
import json

cgitb.enable()

conn = sqlite3.connect('createUser.db')
conn.text_factory = str  #need to change the text_factory for the images
c = conn.cursor()

stored_login_cookie = os.environ.get('HTTP_COOKIE')
cookie = Cookie.SimpleCookie(stored_login_cookie)

# There is probably a much better way to do this


def getUserProfileInfo():
    # print "Content-Type: application/json"
    print
    # get the users full name
    username = cookie['LOGIN'].value
    # print username
    user_rows = c.execute('SELECT * FROM profiles WHERE userName=?',
                          [username])  #should return only one
    user_rows = c.fetchone()
    if user_rows is None:
        response = user_rows
Esempio n. 58
0
 def __setitem__(self, key, value):
     strval = str(value)
     sig = b64encode(hmac.new(self.key + str(key), strval, sha256).digest())
     cval = Cookie._quote(strval + sig)
     self._BaseCookie__set(key, strval, cval)