Example #1
0
File: douban.py Project: gsy/gmusic
    def login(self,username,password):        
        # 发起HTTP请求
        conn = httplib.HTTPConnection("www.douban.com")
        conn.request("GET","/")
        resp = conn.getresponse()
        print resp.read()
        cookie = resp.getheader('Set-Cookie')
        print cookie
        cookie = SimpleCookie(cookie)
        conn.close()
        if not cookie.has_key('bid'):
            print "cookie_error"
            raise DoubanLoginException        
        else:
            self.bid = cookie['bid']
            print self.bid
            # return self.bid
        
        # login douban

        data = urllib.urlencode({'source:':'simple',
                                 'form_email':username,
                                 'form_password':password,
                                 'remember':'on'})
        contentType = "application/x-www-form-urlencoded"
        print data
        
        cookie = 'bid="%s"' % self.bid
        print cookie
        
        headers = {"Content-Type":contentType,"Cookie":cookie}
        with contextlib.closing(httplib.HTTPSConnection("www.douban.com")) as conn:
            conn.request("POST","/accounts/login",data,headers)

            r1 = conn.getresponse()
            print r1.read()
            
            resultCookie = SimpleCookie(r1.getheader('Set-Cookie'))
            print resultCookie
            # # 通过不了有验证码的情况
            if not resultCookie.has_key('dbcl2'):
                raise DoubanLoginException()

            dbcl2 = resultCookie['dbcl2'].value
            if dbcl2 is not None and len(dbcl2) > 0:
                self.dbcl2 = dbcl2
                uid = self.dbcl2.split(':')[0]
                self.uid = uid
Example #2
0
 def determineKey(handler):
     hdr = handler.headers.getheader('Cookie')
     if not hdr: return Session.generateKey()
     c = SimpleCookie()
     c.load(hdr)
     return c['session'].value if c.has_key(
         'session') else Session.generateKey()
Example #3
0
    def __login(self, username, password):
        """
        login douban, get the session token
        """
        data = urllib.urlencode({'source':'simple',
                'form_email':username, 'form_password':password})
        contentType = "application/x-www-form-urlencoded"

        self.__get_bid()
        cookie = "bid=%s" % self.bid

        headers = {"Content-Type":contentType, "Cookie": cookie }
        with contextlib.closing(httplib.HTTPSConnection("www.douban.com")) as conn:
            conn.request("POST", "/accounts/login", data, headers)
        
            r1 = conn.getresponse()
            resultCookie = SimpleCookie(r1.getheader('Set-Cookie'))

            if not resultCookie.has_key('dbcl2'):
                raise DoubanLoginException()

            dbcl2 = resultCookie['dbcl2'].value
            if dbcl2 is not None and len(dbcl2) > 0:
                self.dbcl2 = dbcl2
        
                uid = self.dbcl2.split(':')[0]
                self.uid = uid
class cookie:
    def __init__( self ):
        self.cookieObj = SimpleCookie()
        self.load()

    def load( self ):
        if not os.environ.has_key("HTTP_COOKIE"):
            # Kein Cookie vorhanden
            return

        self.cookieObj.load( os.environ["HTTP_COOKIE"] )

    def readCookie( self, CookieName ):
        if self.cookieObj == False:
            # Gibt kein Cookie
            return False

        if self.cookieObj.has_key(CookieName):
            return self.cookieObj[CookieName].value
        else:
            return False

    def debug( self ):
        print "Cookie-Debug:"
        print "<hr><pre>"
        if not os.environ.has_key("HTTP_COOKIE"):
            print "There is no HTTP_COOKIE in os.environ:\n"
            for k,v in os.environ.iteritems(): print k,v
        else:
            print self.cookieObj
        print "</pre><hr>"
Example #5
0
    def test_login_ignore_case(self):
        """
        Test that login is succesful when the usernames differ in case, but case
        is ignored.
        """
        self.env.config.set('trac', 'ignore_auth_case', 'yes')

        outcookie = Cookie()
        req = Mock(cgi_location='/trac',
                   href=Href('/trac.cgi'),
                   incookie=Cookie(),
                   outcookie=outcookie,
                   remote_addr='127.0.0.1',
                   remote_user='******',
                   authname='anonymous',
                   base_path='/trac.cgi')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value
        self.assertEquals(
            [('john', '127.0.0.1')],
            self.env.db_query(
                "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
                (auth_cookie, )))
Example #6
0
def checklogin(request):
    c=SimpleCookie(request.headers.getheader('Cookie', ''))
    m=md5.md5(fixeduser+':'+fixedpass)
    digest=m.hexdigest()
    if c.has_key('authhash') and c['authhash'].value==digest:
        return True
    else:
        return False
Example #7
0
 def check_cookie(self):
     """check, if the cookie with the session variable is set"""
     HTML = HtmlContent()
     if os.environ.has_key('HTTP_COOKIE') and os.environ.has_key('HTTP_REFERER'):
         C = SimpleCookie(os.environ['HTTP_COOKIE'])
         if C.has_key('session') and C['session'].value != "":
             if C.has_key('company') and C['company'].value != "":
                 company = C['company'].value
             else:
                 company = -1
         else:
             HTML.simple_redirect_header(self._url_)
             return	
         return company
     else:
         HTML.simple_redirect_header(self._url_)
         return
Example #8
0
def checklogin(request):
    c = SimpleCookie(request.headers.getheader('Cookie', ''))
    m = md5.md5(fixeduser + ':' + fixedpass)
    digest = m.hexdigest()
    if c.has_key('authhash') and c['authhash'].value == digest:
        return True
    else:
        return False
Example #9
0
def checklogin(request):
    c = SimpleCookie(request.headers.getheader("Cookie", ""))
    m = md5.md5(fixeduser + ":" + fixedpass)
    digest = m.hexdigest()
    if c.has_key("authhash") and c["authhash"].value == digest:
        return True
    else:
        return False
Example #10
0
    def authPloneUser(self, username, password, loginurl):

        http = httplib2.Http()

        headers = {}
        headers['Content-type'] = 'application/x-www-form-urlencoded'
        headers[
            'User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        headers[LEOCORNUS_HTTP_HEADER_KEY] = LEOCORNUS_HTTP_HEADER_VALUE

        login_form = {}
        login_form['__ac_name'] = username
        login_form['__ac_password'] = password
        login_form['cookies_enabled'] = '1'
        login_form['js_enabled'] = '0'
        login_form['form.submitted'] = '1'
        body = urllib.urlencode(login_form)

        try:
            res, cont = http.request(loginurl,
                                     'POST',
                                     headers=headers,
                                     body=body)
        except Exception:
            # not valid login url!
            return None

        if res.has_key('set-cookie'):
            cookie = SimpleCookie()
            cookie.load(res['set-cookie'])

            cookieName = settings.PLONEPROXY_COOKIE_NAME
            defaultCookieName = '__ac'
            if cookie.has_key(cookieName):

                cookieValue = cookie.get(cookieName).value
                return (cookieName, cookieValue)
            elif cookie.has_key(defaultCookieName):
                # try the default Plone cookie name in case.
                cookieValue = cookie.get(defaultCookieName).value
                return (defaultCookieName, cookieValue)

        # no valid cookie found!
        return None
Example #11
0
 def test_anonymous_session(self):
     """
     Verify that session variables are stored in the database.
     """
     incookie = Cookie()
     incookie["trac_session"] = "123456"
     outcookie = Cookie()
     req = Mock(authname="anonymous", base_path="/", incookie=incookie, outcookie=outcookie)
     session = Session(self.env, req)
     self.assertEquals("123456", session.sid)
     self.failIf(outcookie.has_key("trac_session"))
    def authPloneUser(self, username, password, loginurl):

        http = httplib2.Http()

        headers = {}
        headers['Content-type'] = 'application/x-www-form-urlencoded'
        headers['User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        headers[LEOCORNUS_HTTP_HEADER_KEY] = LEOCORNUS_HTTP_HEADER_VALUE

        login_form = {}
        login_form['__ac_name'] = username
        login_form['__ac_password'] = password
        login_form['cookies_enabled'] = '1'
        login_form['js_enabled'] = '0'
        login_form['form.submitted'] = '1'
        body = urllib.urlencode(login_form)

        try:
            res, cont = http.request(loginurl, 'POST',
                                     headers=headers, body=body)
        except Exception:
            # not valid login url!
            return None
        
        if res.has_key('set-cookie'):
            cookie = SimpleCookie()
            cookie.load(res['set-cookie'])

            cookieName = settings.PLONEPROXY_COOKIE_NAME
            defaultCookieName = '__ac'
            if cookie.has_key(cookieName):

                cookieValue = cookie.get(cookieName).value
                return (cookieName, cookieValue)
            elif cookie.has_key(defaultCookieName):
                # try the default Plone cookie name in case.
                cookieValue = cookie.get(defaultCookieName).value
                return (defaultCookieName, cookieValue)

        # no valid cookie found!
        return None
Example #13
0
 def test_anonymous_session(self):
     """
     Verify that session variables are stored in the database.
     """
     incookie = Cookie()
     incookie['trac_session'] = '123456'
     outcookie = Cookie()
     req = Mock(authname='anonymous', base_path='/', incookie=incookie,
                outcookie=outcookie)
     session = Session(self.env, req)
     self.assertEquals('123456', session.sid)
     self.failIf(outcookie.has_key('trac_session'))
Example #14
0
 def __get_bid(self):
     conn = httplib.HTTPConnection("www.douban.com")
     conn.request("GET", "/accounts/login")
     resp = conn.getresponse()
     cookie = resp.getheader('Set-Cookie')
     cookie = SimpleCookie(cookie)
     conn.close()
     if not cookie.has_key('bid'):
         raise DoubanLoginException()
     else:
         self.bid = cookie['bid']
         return self.bid
Example #15
0
def checkCookie(request):
	if os.environ.has_key('HTTP_COOKIE'):
		cookieStr = os.environ.get('HTTP_COOKIE')
		if not cookieStr:
			return False
		cookie = SimpleCookie()
		cookie.load(cookieStr)
		if not cookie.has_key('hopper_oid_sid'):
			return False
		sid = cookie['hopper_oid_sid'].value
		return isValidSession(request, sid)
	else:
		return False
Example #16
0
def getCookie( initialvalues = {} ):
    # TODO This is duplicated in leave-comic-comment.py getCookie(); delete that one.
    """
    Return a SimpleCookie.  If some of the cookie values haven't
    been set, we'll plunk them into the cookie with the initialValues
    dict.
    """
    if os.environ.has_key('HTTP_COOKIE'):
        C = SimpleCookie(os.environ['HTTP_COOKIE'])
    else:
        C = SimpleCookie()
    for key in initialvalues.keys():
        if not C.has_key(key): C[key] = initialvalues[key]
    return C
Example #17
0
 def login(self, username, password):
     data = urllib.urlencode({'form_email':username, 'form_password':password})
     with closing(httplib.HTTPConnection("www.douban.com")) as conn:
         conn.request("POST", "/accounts/login", data, {"Content-Type":"application/x-www-form-urlencoded"})
         cookie = SimpleCookie(conn.getresponse().getheader('Set-Cookie'))
         if not cookie.has_key('dbcl2'):
             print 'login failed'
             thread.exit()
             return 
         dbcl2 = cookie['dbcl2'].value
         if dbcl2 and len(dbcl2) > 0:
             self.dbcl2 = dbcl2
             self.uid = self.dbcl2.split(':')[0]
         self.bid = cookie['bid'].value
Example #18
0
    def test_login(self):
        outcookie = Cookie()
        # remote_user must be upper case to test that by default, case is
        # preserved.
        req = Mock(cgi_location='/trac', href=Href('/trac.cgi'),
                   incookie=Cookie(), outcookie=outcookie,
                   remote_addr='127.0.0.1', remote_user='******',
                   authname='john', base_path='/trac.cgi')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value

        self.assertEquals([('john', '127.0.0.1')], self.env.db_query(
            "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
            (auth_cookie,)))
Example #19
0
    def test_login(self):
        outcookie = Cookie()
        # remote_user must be upper case to test that by default, case is
        # preserved.
        req = Mock(cgi_location='/trac', href=Href('/trac.cgi'),
                   incookie=Cookie(), outcookie=outcookie,
                   remote_addr='127.0.0.1', remote_user='******', authname='john')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value
        cursor = self.db.cursor()
        cursor.execute("SELECT name,ipnr FROM auth_cookie WHERE cookie=%s",
                       (auth_cookie,))
        row = cursor.fetchone()
        self.assertEquals('john', row[0])
        self.assertEquals('127.0.0.1', row[1])
 def is_authenticated(self):
     if self.username and self.password:
         post_data = {
                 'user': self.username,
                 'passwd': self.password
                }
         response = requests.post(LOGIN_URL, data=post_data)
         cookie = SimpleCookie()
         cookie.load(response.headers.get('set-cookie'))
         # The API docs state that is the cookie returned
         # contains a reddit_session key only if the auth
         # was succesful. Unsuccesful responses will still
         # return a cookie, but with a 'reddit_first' key.
         if cookie.has_key('reddit_session'):
             self.session_key = cookie['reddit_session']
             return True
     return None
Example #21
0
    def __login(self,
                username,
                password,
                captcha_id=None,
                captcha_solution=None):
        """
        login douban, get the session token
        """
        if self.bid is None:
            self.__get_login_data()
        login_form = {
            'source': 'simple',
            'form_email': username,
            'form_password': password
        }
        if captcha_id is not None:
            login_form['captcha-id'] = captcha_id
            login_form['captcha-solution'] = captcha_solution
        data = urllib.urlencode(login_form)
        contentType = "application/x-www-form-urlencoded"

        cookie = 'bid="%s"' % self.bid

        headers = {"Content-Type": contentType, "Cookie": cookie}
        with contextlib.closing(
                httplib.HTTPSConnection("www.douban.com")) as conn:
            conn.request("POST", "/accounts/login", data, headers)

            r1 = conn.getresponse()
            resultCookie = SimpleCookie(r1.getheader('Set-Cookie'))

            if not resultCookie.has_key('dbcl2'):
                data = {}
                redir = r1.getheader('location')
                if redir:
                    redir_page = urllib.urlopen(redir).read()
                    captcha_data = self.__check_login_captcha(redir_page)
                    data['captcha_id'] = captcha_data
                raise DoubanLoginException(**data)

            dbcl2 = resultCookie['dbcl2'].value
            if dbcl2 is not None and len(dbcl2) > 0:
                self.dbcl2 = dbcl2

                uid = self.dbcl2.split(':')[0]
                self.uid = uid
Example #22
0
 def login(self, username, password):
     data = urllib.urlencode({
         'form_email': username,
         'form_password': password
     })
     with closing(httplib.HTTPConnection("www.douban.com")) as conn:
         conn.request("POST", "/accounts/login", data,
                      {"Content-Type": "application/x-www-form-urlencoded"})
         cookie = SimpleCookie(conn.getresponse().getheader('Set-Cookie'))
         if not cookie.has_key('dbcl2'):
             print 'login failed'
             thread.exit()
             return
         dbcl2 = cookie['dbcl2'].value
         if dbcl2 and len(dbcl2) > 0:
             self.dbcl2 = dbcl2
             self.uid = self.dbcl2.split(':')[0]
         self.bid = cookie['bid'].value
Example #23
0
    def test_login_ignore_case(self):
        """
        Test that login is succesful when the usernames differ in case, but case
        is ignored.
        """
        self.env.config.set('trac', 'ignore_auth_case', 'yes')

        outcookie = Cookie()
        req = Mock(cgi_location='/trac', href=Href('/trac.cgi'),
                   incookie=Cookie(), outcookie=outcookie,
                   remote_addr='127.0.0.1', remote_user='******',
                   authname='anonymous', base_path='/trac.cgi')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value
        self.assertEquals([('john', '127.0.0.1')], self.env.db_query(
            "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
            (auth_cookie,)))
    def post(self):
        try:
            user = users.get_current_user()
            if user is None:
                return self.redirect('/index')
            else:
                logout_link = users.create_logout_url(PROTOCOLHTTP + DOMAIN +
                                                      "/index")

            cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', ''))
            if cookie.has_key('picturetooken'):
                tooken = cookie['picturetooken'].value

            cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', ''))
            cookie['picturetooken'] = ""
            cookie['picturetooken']['expires'] = 3600
            print cookie.output()
            hiddenToken = self.request.get('tooken')
            if tooken != hiddenToken:
                #return self.redirect('/user/picture/insert')
                raise

            i = 0
            while (i < 9):
                binary = self.request.get('binary_' + str(i))
                #print len(binary)
                if not binary:
                    break
                name = self.request.body_file.vars['binary_' + str(i)].filename
                mime = self.request.body_file.vars[
                    'binary_' + str(i)].headers['content-type']
                self.registerPicture(binary, name, mime, user)
                i += 1

            if user:
                loginFlg = 1
            params = {'logout_link': logout_link, 'loginFlg': loginFlg}
            fpath = os.path.join(os.path.dirname(__file__),
                                 'template/user/picture', 'insertend.html')
            html = template.render(fpath, params)
            self.response.out.write(html)
        except:
            self.errorFunc()
	def login(self, captcha_id, captcha_solution, callback):
		"""
		login to douban, get the session token
		"""
		try:
			if self.bid is None:
				self.__get_login_data()
			login_form = {'source':'simple', 'form_email':self.username,
				'form_password':self.password}
			if captcha_id is not None:
				login_form['captcha-id'] = captcha_id
				login_form['captcha-solution'] = captcha_solution
			data = urllib.urlencode(login_form)
			content_type = "application/x-www-form-urlencoded"
			cookie = 'bid="%s"' % self.bid
			headers = {"Content-Type":content_type, "Cookie": cookie}

			with contextlib.closing(httplib.HTTPSConnection("www.douban.com")) as conn:
				conn.request("POST", "/accounts/login", data, headers)
				r1 = conn.getresponse()
				resultCookie = SimpleCookie(r1.getheader('Set-Cookie'))

				if not resultCookie.has_key('dbcl2'):
					data = {}
					redir = r1.getheader('location')
					if redir:
						redir_page = urllib.urlopen(redir).read()
						captcha_data = self.__check_login_captcha(redir_page)
						data['captcha_id'] = captcha_data
					raise DoubanLoginException(**data)

				dbcl2 = resultCookie['dbcl2'].value
				if dbcl2 is not None and len(dbcl2) > 0:
					self.dbcl2 = dbcl2
					uid = self.dbcl2.split(':')[0]
					self.uid = uid

		except Exception as e:
			GLib.idle_add(callback, e)
		else:
			self.__load_channels()
			GLib.idle_add(callback, None)
Example #26
0
    def test_login(self):
        outcookie = Cookie()
        # remote_user must be upper case to test that by default, case is
        # preserved.
        req = Mock(cgi_location='/trac',
                   incookie=Cookie(),
                   outcookie=outcookie,
                   remote_addr='127.0.0.1',
                   remote_user='******',
                   authname='john')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value
        cursor = self.db.cursor()
        cursor.execute("SELECT name,ipnr FROM auth_cookie WHERE cookie=%s",
                       (auth_cookie, ))
        row = cursor.fetchone()
        self.assertEquals('john', row[0])
        self.assertEquals('127.0.0.1', row[1])
Example #27
0
    def test_login(self):
        outcookie = Cookie()
        # remote_user must be upper case to test that by default, case is
        # preserved.
        req = Mock(cgi_location='/trac',
                   href=Href('/trac.cgi'),
                   incookie=Cookie(),
                   outcookie=outcookie,
                   remote_addr='127.0.0.1',
                   remote_user='******',
                   authname='john',
                   base_path='/trac.cgi')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value

        self.assertEquals(
            [('john', '127.0.0.1')],
            self.env.db_query(
                "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
                (auth_cookie, )))
Example #28
0
    def test_login_ignore_case(self):
        """
        Test that login is succesful when the usernames differ in case, but case
        is ignored.
        """
        self.env.config.set('trac', 'ignore_auth_case', 'yes')

        outcookie = Cookie()
        req = Mock(cgi_location='/trac',
                   incookie=Cookie(),
                   outcookie=outcookie,
                   remote_addr='127.0.0.1',
                   remote_user='******',
                   authname='anonymous')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value
        cursor = self.db.cursor()
        cursor.execute("SELECT name,ipnr FROM auth_cookie WHERE cookie=%s",
                       (auth_cookie, ))
        row = cursor.fetchone()
        self.assertEquals('john', row[0])
        self.assertEquals('127.0.0.1', row[1])
Example #29
0
class PoorSession:
    """Self-contained cookie with session data"""

    def __init__(self, req, expires = 0, path = '/', SID = 'SESSID', get = None):
        """Constructor.
        @param  req     mod_python.apache.request
        @param  expires cookie expire time in seconds, if it 0, no expire is set
        @param  path    cookie path
        @param  SID     cookie key name
        @param  get     raw data session's cookie if \b HTTP_COOKIE is not present
        """
        
        # @cond PRIVATE
        self.SID = SID
        self.expires = expires
        self.path = path
        self.cookie = SimpleCookie()
        # @endcond

        ## @property data
        # data is session dictionary to store user data in cookie
        self.data = {}

        raw = None

        # get SID from cookie or url
        if not req.subprocess_env.has_key("SERVER_SOFTWARE"):
            req.add_common_vars()

        if req.subprocess_env.has_key("HTTP_COOKIE"):
            self.cookie.load(req.subprocess_env["HTTP_COOKIE"])
            if self.cookie.has_key(SID):
                raw = self.cookie[SID].value
        elif get:
            raw = get
        #endif
        

        if raw:
            try:
                self.data = loads(hidden(bz2.decompress(b64decode(raw)),
                                    req.secret_key))
                if type(self.data) != DictType:
                    raise RuntimeError()
            except:
                req.log_error('Bad session data.')
            #endtry

            if 'expires' in self.data and self.data['expires'] < int(time()):
                req.log_error('Session was expired, generating new.', APLOG_INFO)
                self.data = {}
            #endif
        #endif

    #enddef

    def renew(self):
        """Renew cookie, in fact set expires to next time if it set."""
        if self.expires:
            self.data['expires'] = int(time()) + self.expires
            return

        if 'expires' in self.data:
            self.data.pop('expires')
    #enddef

    def write(self, req):
        """Store data to cookie value. This method is called automaticly in
        header method.
        @param req mod_python.apache.request
        """
        raw = b64encode(bz2.compress(hidden(dumps(self.data),
                                     req.secret_key), 9))
        self.cookie[self.SID] = raw
        self.cookie[self.SID]['path'] = self.path

        if self.expires:
            self.data['expires'] = int(time()) + self.expires
            self.cookie[self.SID]['expires'] = self.expires
            
        return raw
    #enddef

    def destroy(self):
        """Destroy session. In fact, set cookie expires value to past (-1)."""
        self.data = {}
        self.data['expires'] = -1
        self.cookie[self.SID]['expires'] = -1
    #enddef

    def header(self, req, headers_out = None):
        """Generate cookie headers and append it to headers_out if it set.
        @param req mod_python.apache.request
        @param headers_out mod_python.apache.mp_table object
        @returns list of cookie header pairs
        """
        self.write(req)
        cookies = self.cookie.output().split('\r\n')
        header = []
        for cookie in cookies:
            var = cookie[:10] # Set-Cookie
            val = cookie[12:] # SID=###; expires=###; Path=/
            header.append((var,val))
            if headers_out != None:
                headers_out.add(var, val)
        return header
    def get(self):
        user = users.get_current_user()
        if user is None:
            return self.redirect('/index')
        else:
            logout_link = users.create_logout_url(PROTOCOLHTTP + DOMAIN +
                                                  "/index")
        page = self.request.get('page')
        zoomFlg = self.request.get('zoomFlg')
        searchLabel = self.request.get('searchLabel')
        picturHandlerePage = self.request.get('picturHandlerePage')
        delFlg = self.request.get('delFlg')

        cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', ''))
        if delFlg != "1":
            if searchLabel != "":
                cookie['picturHandlerePage'] = ""
                cookie['searchLabel'] = searchLabel.encode('utf-8')
                cookie['searchLabel']['expires'] = 3600
                print cookie.output()
            else:
                if cookie.has_key('searchLabel'):
                    searchLabel = cookie['searchLabel'].value.decode('utf-8')
        else:
            searchLabel = ""
            picturHandlerePage = ""
            cookie['searchLabel'] = ""
            cookie['picturHandlerePage'] = ""
            print cookie.output()

        #############PICTURE#######################

        if picturHandlerePage == '':
            if cookie.has_key('picturHandlerePage'):
                picturHandlerePage = cookie['picturHandlerePage'].value.decode(
                    'utf-8')
        else:
            cookie['picturHandlerePage'] = picturHandlerePage.encode('utf-8')
            cookie['picturHandlerePage']['expires'] = 3600
            print cookie.output()
        try:
            picturHandlerePage = int(picturHandlerePage) - 1
        except:
            picturHandlerePage = 0

        email = user.email()
        userData = db.GqlQuery("SELECT * FROM User WHERE email='" + email +
                               "'")
        for user in userData:
            userid = user.key().id()
        userDatas = User.get_by_id(long(userid))
        userPictureDatas = userDatas.picture_set

        datas = list()
        keyList = list()
        for PictureData in userPictureDatas:
            keyList.append(PictureData.key().id())
        if searchLabel != "":
            PictureDatas = Picture.gql("WHERE label =:1", searchLabel)
            for PictureData in PictureDatas:
                if PictureData.key().id() in keyList:
                    datas.append(PictureData)
        else:
            for upd in userPictureDatas:
                datas.append(upd)
        datas.sort(key=operator.attrgetter('registerDate'))
        datas.reverse()

        pictureCount = len(datas)
        pagerFlg = 0
        if pictureCount > PAGE:
            pagerFlg = 1

        lastPage = int(math.ceil(float(pictureCount) / PAGE))
        if picturHandlerePage > lastPage:
            picturHandlerePage = lastPage
        #pager
        #now page picturepage+1
        #last page paginator.pages+1
        page1 = 1
        if picturHandlerePage + 1 > 2:
            page1 = picturHandlerePage + 1 - 1
        elif picturHandlerePage + 1 > 3:
            page1 = picturHandlerePage + 1 - 2
        if picturHandlerePage + 1 == lastPage + 1:
            page1 = page1 - 3
        elif picturHandlerePage == lastPage + 1:
            page1 = page1 - 2

        if page1 < 2:
            page1 = 2

        pages = range(page1 - 1, lastPage + 1)

        paginator = ObjectPaginator(datas, PAGE)
        if picturHandlerePage >= paginator.pages:
            picturHandlerePage = paginator.pages - 1
        if user:
            loginFlg = 1

        params = {
            "datas": paginator.get_page(picturHandlerePage),
            "pages": pages,
            "page": picturHandlerePage + 1,
            "prev": picturHandlerePage,
            "next": picturHandlerePage + 2,
            "pagerFlg": pagerFlg,
            "lastpage": lastPage,
            'zoomFlg': zoomFlg,
            'searchLabel': searchLabel,
            'loginFlg': loginFlg,
            'logout_link': logout_link
        }

        fpath = os.path.join(os.path.dirname(__file__),
                             'template/user/picture', 'list.html')
        html = template.render(fpath, params)
        self.response.out.write(html)

        return
Example #31
0
    def get(self):
        user = users.get_current_user()
        if not user:
            return self.redirect('/admin/index')
        cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', ''))
        #############PICTURE#######################
        picturepage = self.request.get('picturepage')
        if picturepage == '':
            if cookie.has_key('picturepage'):
                picturepage = cookie['picturepage'].value.decode('utf-8')
        else:
            cookie['picturepage'] = picturepage.encode('utf-8')
            cookie['picturepage']['expires'] = 3600

        try:
            picturepage = int(picturepage) - 1
        except:
            picturepage = 0
        userid = self.request.get('userid')
        datas = User.get_by_id(long(userid))
        params = {'datas': datas}

        paginator = ObjectPaginator(datas.picture_set, PICTUREPAGE)
        if picturepage >= paginator.pages:
            picturepage = paginator.pages - 1
        ##############PICTURE_END#####################
        ##############ALBUM#########################

        albumpage = self.request.get('albumpage')
        if albumpage == '':
            if cookie.has_key('albumpage'):
                albumpage = cookie['albumpage'].value.decode('utf-8')
        else:
            cookie['albumpage'] = albumpage.encode('utf-8')
            cookie['albumpage']['expires'] = 3600

        print cookie.output()
        try:
            albumpage = int(albumpage) - 1
        except:
            albumpage = 0

        albumpaginator = ObjectPaginator(datas.album_set, ALBUMPICTURE)
        if albumpage >= albumpaginator.pages:
            albumpage = albumpaginator.pages - 1

        params = {
            "datas": paginator.get_page(picturepage),
            "picturepages": range(1, paginator.pages + 1),
            "picturepage": picturepage + 1,
            "userid": datas,
            "albumdatas": albumpaginator.get_page(albumpage),
            "albumpages": range(1, albumpaginator.pages + 1),
            "albumpage": albumpage + 1
        }

        fpath = os.path.join(os.path.dirname(__file__), 'template/admin/user',
                             'showalbum.html')
        html = template.render(fpath, params)
        self.response.out.write(html)

        return
Example #32
0
  def get(self):
    try:
      user = users.get_current_user()
      formList = [
                    'searchValue',
                    'prefecture',
                    'line',
                    'station',
                    'category',
                    'hicategory',
                    'searchflg'

                    ]
      formData={}
      cnt = 0
      cateFlg = 0
      noneFlg = 0
      searchFlg = 0
      stationFlg = 0
      for roopList in formList:
        if self.request.get(roopList) !="":
          cnt += 1
        formData[roopList] = self.request.get(roopList)

      if formData["category"] =="":
        if formData["hicategory"] != "":
          formData["category"] = formData["hicategory"]

      cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', ''))
      if formData["searchflg"] == "1":
        cookie["searchValue"]=""
        cookie["prefecture"]=""
        cookie["line"]=""
        cookie["station"]=""

      if formData["searchValue"] != "":
        cookie["searchValue"] = formData["searchValue"].encode('utf-8')
        cookie['searchValue']['expires'] = 3600
      else:
        if cookie.has_key("searchValue"):
          formData["searchValue"] = cookie["searchValue"].value.decode('utf-8')
      if formData["prefecture"] != "":
        cookie["prefecture"] = formData["prefecture"].encode('utf-8')
        cookie["prefecture"]["expires"] = 3600
      else:
        if cookie.has_key("prefecture"):
          formData["prefecture"] = cookie["prefecture"].value.decode('utf-8')
      if formData["line"] != "":
        cookie["line"] = formData["line"].encode('utf-8')
        cookie["line"]["expires"] = 3600
      else:
        if cookie.has_key("line"):
          formData["line"] = cookie["line"].value.decode('utf-8')
      if formData["station"] != "":
        cookie["station"] = formData["station"].encode('utf-8')
        cookie["station"]["expires"] = 3600
      else:
        if cookie.has_key("station"):
          formData["station"] = cookie["station"].value.decode('utf-8')

      print cookie.output()
      #Defaulut
      todayTime = str(date.today())
      yesterdayTime = date.today()-timedelta(1)
      AlbumDatas = list()

      if formData["searchValue"] == "" and formData["prefecture"] == "" and formData["line"] == "" and formData["station"] == "":
         return self.redirect('/index')
      else:
        validataKey = list()
        searchlist = list()

        if formData["searchValue"] != "":
          searchlist2 = formData['searchValue'].split(' ')
          for sc in searchlist2:
            if sc!='':
              searchlist.append(sc)
        if formData["prefecture"] !="":
          prefectureData = Prefecture.gql("WHERE prefecture_name = :1", formData["prefecture"])
          for pd in prefectureData:
            if pd.prefecture_number != 1:
              if len(pd.prefecture_name) == 3:
                prefecture = pd.prefecture_name[0:2]
              if len(pd.prefecture_name)== 4:
                prefecture = pd.prefecture_name[0:3]

          searchlist.append(prefecture)
        if formData["line"] !="" and formData["station"] =="":
          searchlist.append(formData["line"])
        if formData["station"] !="":
          searchlist.append(formData["station"])
        cnt = len(searchlist)
        if cnt == 1:
          gqlAlbumDatas = Album.gql("WHERE search_index =:1", searchlist[0])
        else:
          i = 0
          searchVal = ""
          sqlString = ""
          slList = list()
          for sl in searchlist:
            i+=1
            if i==1:
              sqlString = "search_index =:"+str(i)
            else:
              sqlString += " AND search_index =:"+str(i)
            slList.append(sl)

          if cnt == 2:
            gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1])
          elif cnt == 3:
            gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2])
          elif cnt == 4:
            gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3])
          elif cnt == 5:
            gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4])
          elif cnt == 6:
            gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5])
          elif cnt == 7:
            gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5],slList[6])
          elif cnt == 8:
            gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5],slList[6],slList[7])
          elif cnt >= 9:
            gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5],slList[6],slList[7],slList[8])
          elif cnt >= 10:
            gqlAlbumDatas = Album.gql("WHERE "+sqlString, slList[0],slList[1],slList[2],slList[3],slList[4],slList[5],slList[6],slList[7],slList[8],slList[9])

      for AlbumData in gqlAlbumDatas:
        AlbumDatas.append(AlbumData)

      if formData["category"] != "" or formData["category"] == "populer":
        filterDatas = list()
        if formData["category"] =="today":
          for data in AlbumDatas:
            strTime = ""
            strTime = str(data.updateDate)
            if strTime[0:10] == todayTime:
              filterDatas.append(data)
        if formData["category"] =="spring":
          for data in AlbumDatas:
            if data.season == 2:
              filterDatas.append(data)
        elif formData["category"] =="summer":
          for data in AlbumDatas:
            if data.season == 3:
              filterDatas.append(data)
        elif formData["category"] =="fall":
          for data in AlbumDatas:
            if data.season == 4:
              filterDatas.append(data)
        elif formData["category"] =="winter":
          for data in AlbumDatas:
            if data.season == 5:
              filterDatas.append(data)
        elif formData["category"] =="recentPopuler":
          kako = date.today()-timedelta(30)
          for data in AlbumDatas:
            if data.updateDate > kako:
              filterDatas.append(data)
        AlbumDatas = list()
        AlbumDatas = filterDatas
      datas = list()
      for AlbumData in AlbumDatas:
        if AlbumData.user.name is not None:
          if AlbumData.user.name !="":
            AlbumData.user.nickname = AlbumData.user.name
        if AlbumData.picture_counter !=0:
          PcaDatas = PictureConnectAlbum.gql("WHERE album = :1 ORDER BY album", AlbumData)
          pictureid = 0;
          for PcaData in PcaDatas:
            try:
              PictureDatas = PcaData.picture
              pictureid = int(PictureDatas.key().id())
              if(pictureid != 0):
                break
            except:
              pictureid=0
          if pictureid != 0:
            AlbumData.pictureid = pictureid
            datas.append(AlbumData)
            strList = list()
            for data in datas:
              if len(data.recital) > 22:
                da = data.recital[0:22]
                da +="..."
                data.subrecital = da
              if len(data.title) > 8:
                da2 = data.title[0:8]
                da2 +="..."
                data.subtitle = da2

      datas.sort(key=operator.attrgetter('watch_counter'))
      datas.reverse()

      page = self.request.get("page")
      try:
          page = int(page) - 1
      except:
          page = 0

      albumCount = len(datas)

      pagerFlg = 0
      if albumCount > PAGE:
        pagerFlg = 1;

      lastPage = int(math.ceil(float(albumCount)/PAGE))
      if page > lastPage:
        page = lastPage
      paginator = ObjectPaginator(datas,PAGE)
      if page>=paginator.pages:
              page = paginator.pages - 1
      if user is not None:
          loginFlg = 1

      #pager
      #now page picturepage+1
      #last page paginator.pages+1
      page1 = 1
      if page+1 > 2:
        page1 = page+1-1
      elif page+1 > 3:
        page1 = page+1-2
      if page+1 == lastPage+1:
        page1 = page1-3
      elif page == lastPage+1:
        page1 = page1-2

      if page1 < 2:
        page1 = 2

      pages = range(page1-1,lastPage+1)

      ################selext box######################
      PreDatas     = Prefecture.all()
      prelist      = list()
      lineDatas    = list()
      StationDatas = list()
      for pd in PreDatas:
        prelist.append(pd)
      prelist.sort(key=operator.attrgetter("prefecture_number"))
      if formData["prefecture"] !="":
        lineDatas    = self.createLine(formData["prefecture"])

      if formData["line"] !="":
        StationDatas = self.createStation(formData["line"])
      #################create login#######################
      user = users.get_current_user()
      loginFlg      = ""
      user_top_link = ""
      logout_link   = ""
      if user is not None:
          loginFlg = 1
          logout_link = users.create_logout_url(PROTOCOLHTTP+DOMAIN+"/index")
      else:
          user_top_link = users.create_login_url(PROTOCOLHTTPS+DOMAIN+"/user")
      #################create map#######################
      prefectureData = Prefecture.gql("WHERE prefecture_number = :1 order by prefecture_number", 26)

      for pd in prefectureData:
        if pd.prefecture_number != 1:
          if len(pd.prefecture_name) == 3:
            prefecture = pd.prefecture_name[0:2]
          if len(pd.prefecture_name)== 4:
            prefecture = pd.prefecture_name[0:3]

      gqlAlbumDatas = Album.gql("WHERE search_index =:1 limit 0, 100", prefecture)
      sortList = list()
      for AlbumData in gqlAlbumDatas:
        try:
          if AlbumData.picture_counter > 0:
            sortList.append(AlbumData)
        except:
          continue
      sortList.sort(key=operator.attrgetter('watch_counter'))

      AlbumDatas = list()
      AlbumDatas2 = list()
      for AlbumData in sortList:
        if AlbumData.latitude is not None and AlbumData.longitude is not None:
          AlbumDatas2.append(AlbumData)

      params = {
          "datas"         : paginator.get_page(page),
          "pages"         : pages,
          "page"          : page+1,
          "prev"          : page,
          "next"          : page+2,
          "pagerFlg"      : pagerFlg,
          "lastpage"      : lastPage,
          "category"      : formData["category"],
          "searchValue"   : formData["searchValue"],
          "prefecture"    : formData["prefecture"],
          "line"          : formData["line"],
          "station"       : formData["station"],
          "hicategory"    : formData["hicategory"],
          "searchflg"     : formData["searchflg"],
          "AlbumDatas"    : AlbumDatas2,
          "PreDatas"      : prelist,
          "lineDatas"     : lineDatas,
          "user_top_link" : user_top_link,
          "logout_link"   : logout_link,
          "loginFlg"      : loginFlg,
          "StationDatas"  : StationDatas
      }

      fpath = os.path.join(os.path.dirname(__file__),'template/user','indexsearch.html')
      html = template.render(fpath,params)
      self.response.out.write(html)
    except:
      self.errorFunc()
Example #33
0
class PoorSession:
    """Self-contained cookie with session data"""
    def __init__(self, req, expires=0, path='/', SID='SESSID', get=None):
        """Constructor.
        @param  req     mod_python.apache.request
        @param  expires cookie expire time in seconds, if it 0, no expire is set
        @param  path    cookie path
        @param  SID     cookie key name
        @param  get     raw data session's cookie if \b HTTP_COOKIE is not present
        """

        # @cond PRIVATE
        self.SID = SID
        self.expires = expires
        self.path = path
        self.cookie = SimpleCookie()
        # @endcond

        ## @property data
        # data is session dictionary to store user data in cookie
        self.data = {}

        raw = None

        # get SID from cookie or url
        if not req.subprocess_env.has_key("SERVER_SOFTWARE"):
            req.add_common_vars()

        if req.subprocess_env.has_key("HTTP_COOKIE"):
            self.cookie.load(req.subprocess_env["HTTP_COOKIE"])
            if self.cookie.has_key(SID):
                raw = self.cookie[SID].value
        elif get:
            raw = get
        #endif

        if raw:
            try:
                self.data = loads(
                    hidden(bz2.decompress(b64decode(raw)), req.secret_key))
                if type(self.data) != DictType:
                    raise RuntimeError()
            except:
                req.log_error('Bad session data.')
            #endtry

            if 'expires' in self.data and self.data['expires'] < int(time()):
                req.log_error('Session was expired, generating new.',
                              APLOG_INFO)
                self.data = {}
            #endif
        #endif

    #enddef

    def renew(self):
        """Renew cookie, in fact set expires to next time if it set."""
        if self.expires:
            self.data['expires'] = int(time()) + self.expires
            return

        if 'expires' in self.data:
            self.data.pop('expires')

    #enddef

    def write(self, req):
        """Store data to cookie value. This method is called automaticly in
        header method.
        @param req mod_python.apache.request
        """
        raw = b64encode(
            bz2.compress(hidden(dumps(self.data), req.secret_key), 9))
        self.cookie[self.SID] = raw
        self.cookie[self.SID]['path'] = self.path

        if self.expires:
            self.data['expires'] = int(time()) + self.expires
            self.cookie[self.SID]['expires'] = self.expires

        return raw

    #enddef

    def destroy(self):
        """Destroy session. In fact, set cookie expires value to past (-1)."""
        self.data = {}
        self.data['expires'] = -1
        self.cookie[self.SID]['expires'] = -1

    #enddef

    def header(self, req, headers_out=None):
        """Generate cookie headers and append it to headers_out if it set.
        @param req mod_python.apache.request
        @param headers_out mod_python.apache.mp_table object
        @returns list of cookie header pairs
        """
        self.write(req)
        cookies = self.cookie.output().split('\r\n')
        header = []
        for cookie in cookies:
            var = cookie[:10]  # Set-Cookie
            val = cookie[12:]  # SID=###; expires=###; Path=/
            header.append((var, val))
            if headers_out != None:
                headers_out.add(var, val)
        return header
Example #34
0
File: webapp.py Project: 20c/vodka1
  def __call__(self, environ, start_response):

    self.set_profiling()
    t_total = self.start_profile();

    rv = self.application(environ, start_response)
    t_p = self.start_profile()
    request = environ.get("request", {})
    headers = request.get("headers")
    cookies = request.get("cookies_out")


    # set cookie headers

    if cookies:
      for key, value in cookies.items():
        if type(value) != SimpleCookie:
          cookie = SimpleCookie()
          cookie[key] = value
          cookie[key]["path"] = self.cookie_path 
          if self.cookie_secure == "yes":
            cookie[key]["secure"] = True
        else:
          cookie = value
        if cookie.has_key(key):
          headers.append(('Set-Cookie', cookie[key].OutputString()))

    if request.get("created_session"):
      log.debug(
        "NEW SESSION CREATED %s @ %s - %s... on path %s, HTTP_COOKIE: %s" % (
          request.get("user_agent"),
          request.get("remote_addr"),
          request.get("created_session")[:8],
          request.get("path"),
          environ.get("HTTP_COOKIE")
        )
      )
    #print "response handler: %s, %s" % (request.get("path"), headers)
    
    # send status and headers 
    
    status = int(request.get("status", 200))
    status = "%s %s" % (str(status), HTTPresponses.get(status, ('OK'))[0])

    headers = request.get("headers", [])
    
    if False and self.config.get("server", {}).get("gzip","no") == "yes":
      headers.append(("Content-Length", str(len(rv))))

    dbg_print("Sending %s : %s" % (request.get("status"), str(headers)))

    t_d = self.end_profile("total-response-time", environ, t_total)
    if t_d:
      headers.append(("Server-Overhead-Time", str(t_d)))

    headers.append(("Server-Time", "%.5f" % time.time()))

    start_response(status, headers)

    # if dispatch went to app , call cleanup_request

    if hasattr(environ.get("dispatch_to"), "cleanup_request"):
      environ["dispatch_to"].cleanup_request(request, environ)
      self.end_profile("response-handler", environ, t_p)
      self.save_profile(environ)
      return valid_wsgi_response(rv)
    

    self.end_profile("response-handler", environ, t_p)
    self.save_profile(environ)
    return valid_wsgi_response(rv)