def initialize(self, request, response): """ Check cookies, load user session before handling requests. Necessary here? can be merged into POST or GET. """ webapp.RequestHandler.initialize(self, request, response) self.tempvars = {} args = get_session_from_cookie(self.request.cookies) # logging.info('WebRequest.initialize args=%s'%args) if not args: args = get_session_from_request(self.request) if not args: fbcookie = facebook.get_user_from_cookie(self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET) if fbcookie: self.get = self.post = (lambda *a: None) self.redirect('/fb/') return self.sns = 'web' self.user = None #self.tempvars = {'sbs':'web'} self.tempvars['login'] = False else: self.tempvars['login'] = True self.sns = args['sns'] if self.sns == 'fb': self.tempvars['onFacebook'] = True fbcookie = facebook.get_user_from_cookie( self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET) if fbcookie and fbcookie['uid'] != args['uid'][3:]: self.get = self.post = (lambda *a: None) self.redirect('/fb/') return self.tempvars.update(args) #['sns','uid','token'] #self.tempvars['SNS_PREP'] = SNS_PREPS.get(args['sns'],'') try: self.user = helper.get_user_by_key(args['uid']) self.tempvars['user'] = self.user #??? self.tempvars['uname'] = self.user.name except Exception, e: self.response.out.write('Error:%s' % e) self.get = self.post = (lambda *args: None)
def post(self): ck = self.request.get('ck') if not ck or ck.find('SC_Session') < 0: self.fail('No cookie') return cki = re.findall(r'SC_Session="([^"]+)"', ck)[0] args = parse_session(cki) #uid,token,sns,expires if not args: logging.warning('PageUploadRequest. parse_session return None') self.fail('Invalid upload') return uid = args['uid'] u = helper.get_user_by_key(uid, None, False) if not u: logging.warning('User %s not found' % uid) self.fail('Invalid user') return fname = self.request.get('Filename') x = fname.rfind('.') if x < 0: self.fail('Invalid image file') return ext = fname[x + 1:] if not ext in ['jpg', 'png', 'gif', 'jpeg']: self.fail("Not supported image format (only .jpg,.png,.gif)") return bkid = self.request.get('bk') pgid = self.request.get('pg') if not bkid or not pgid: self.fail('No proper book or page') return try: helper.save_page_image(u, bkid, pgid, ext, self.request.get('Filedata')) self.response.out.write('OK') except Exception, e: logging.exception(e) self.fail(e)
def ppapprove(web, args=None): """ Called by PayPal through RETURNURL set in SetExpressCheckout command. Currently payment is done directly, a better way is to return a review page for the user to confirm payment and then come back to send DoExpressCheckoutPayment. But the current method is dirty quick. The L_NAME0 items are not displayed in the sandbox PayPal continue page, not sure whether it's the same on production site. """ token = web.request.get('token') buyerid = web.request.get('PayerID') pkg = web.request.get('pkg') ukey = web.request.get('uid') if pkg == '': cs = web.request.get('CUSTOM') if cs.find(':') > 0: pkg, ukey = cs.split(':') logging.debug('pay.ppapprove: token=%s,buyerid=%s,pkg=%s,ukey=%s' % (token, buyerid, pkg, ukey)) pg = gPackages[pkg.lower()] request = { 'USER': PP_USER, 'PWD': PP_PWD, 'SIGNATURE': PP_SIG, 'VERSION': PP_VER } request['PAYERID'] = buyerid request['TOKEN'] = token request['PAYMENTACTION'] = 'Sale' request['AMT'] = '%0.2f' % float(pg['price']) request['CURRENCYCODE'] = 'GBP' request['METHOD'] = 'DoExpressCheckoutPayment' request['CUSTOM'] = '%s:%s' % (ukey, pkg) # does this return? request['DESC'] = '%s. %s' % (pg['item'], pg['description']) request['L_NAME0'] = pg['item'] request['L_NUMBER0'] = pg['id'] request['L_DESC0'] = pg['description'] request['L_AMT0'] = request['AMT'] request['L_QTY0'] = '1' requests = urllib.urlencode(request) logging.debug('About to send to PayPal: %s' % requests) try: result = urlfetch.fetch( url=PP_ECURL, payload=requests, method=urlfetch.POST, headers={'Content-type': 'application/x-www-form-urlencoded'}) if result.content.find('ACK=Success') >= 0: data = cgi.parse_qs(result.content) #token = data['TOKEN'][-1] payment_status = data['PAYMENTSTATUS'][0] if payment_status == 'Completed': data2 = { 'method': 'PP', 'quantity': '1', 'item_id': pkg, 'buyer': buyerid } data2['order_number'] = data['TRANSACTIONID'][0] data2['price'] = data['AMT'][0] data2['currency'] = data['CURRENCYCODE'][0] if 'SETTLEAMT' in data: logging.debug('settlement: %s' % data['SETTLEAMT'][0]) fee = float(data['FEEAMT'][0]) tstamp = datetime_from_timestampz(data['ORDERTIME'][0]) buyer = helper.get_user_by_key(ukey, False) if buyer is None: logging.warning('Buyer %s is not user!' % ukey) helper.send_email( 'Suinova test payment failure notification', 'Buyer %s not found' % ukey) web.response.out.write('Thank you!') return try: save_exchange(buyer, tstamp, fee, data2) except Exception: pass web.response.out.write(THANKU_PAGE) else: logging.warning( 'ppapprove result from DoExpressCheckoutPayment, payment status is %s' % payment_status) logging.info(result.content) web.response.out.write('Not completed') else: logging.error( 'ppapprove send DoExpressCheckoutPayment returned: %s' % result.content) web.fail( 'Error contacting PayPal, try later, <a href="/">Go back</a>') except Exception, e: logging.exception(e) web.fail('Error contacting PayPal, try later, <a href="/">Go back</a>')
except Exception, e: logging.exception(e) web.error(500) #will cause resend to google checkout try: if result.content.find('<charge-amount-notification') > 0: #charged, so save in ds data = get_google_notification_data(result.content) if 'original_buyer' not in data: ers = 'merchange-private-data not available in charge-amount-notification' logging.error(ers) helper.send_email('Suinova test payment failure notification', ers) web.succeed() #return 200 not to resend to Google Checkout return buyer_id = data['original_buyer'] buyer = helper.get_user_by_key(buyer_id, False) #'gg_%s' % data['buyer']) if buyer is None: logging.warning('Buyer %s is not user!' % buyer_id) helper.send_email('Suinova test payment failure notification', 'Buyer %s not found' % buyer_id) web.succeed() #return 200 not to resend to Google Checkout return gcfee = extract_text_in_tag(result.content, 'total') if len(gcfee) > 0: try: fee = float(gcfee[0]) except TypeError, e: logging.error('float(%s) error:%s' % (gcfee[0], e)) fee = 0 else: fee = 0
def ppapprove(web,args=None): """ Called by PayPal through RETURNURL set in SetExpressCheckout command. Currently payment is done directly, a better way is to return a review page for the user to confirm payment and then come back to send DoExpressCheckoutPayment. But the current method is dirty quick. The L_NAME0 items are not displayed in the sandbox PayPal continue page, not sure whether it's the same on production site. """ token = web.request.get('token') buyerid = web.request.get('PayerID') pkg = web.request.get('pkg') ukey = web.request.get('uid') if pkg == '': cs = web.request.get('CUSTOM') if cs.find(':') > 0: pkg,ukey = cs.split(':') logging.debug('pay.ppapprove: token=%s,buyerid=%s,pkg=%s,ukey=%s'%(token,buyerid,pkg,ukey)) pg = gPackages[pkg.lower()] request = {'USER':PP_USER,'PWD':PP_PWD,'SIGNATURE':PP_SIG,'VERSION':PP_VER} request['PAYERID'] = buyerid request['TOKEN'] = token request['PAYMENTACTION'] = 'Sale' request['AMT'] = '%0.2f'%float(pg['price']) request['CURRENCYCODE'] = 'GBP' request['METHOD'] = 'DoExpressCheckoutPayment' request['CUSTOM'] = '%s:%s' % (ukey,pkg) # does this return? request['DESC'] = '%s. %s' % (pg['item'],pg['description']) request['L_NAME0'] = pg['item'] request['L_NUMBER0'] = pg['id'] request['L_DESC0'] = pg['description'] request['L_AMT0'] = request['AMT'] request['L_QTY0'] = '1' requests = urllib.urlencode(request) logging.debug('About to send to PayPal: %s'%requests) try: result = urlfetch.fetch(url=PP_ECURL,payload=requests,method=urlfetch.POST,headers={'Content-type':'application/x-www-form-urlencoded'}) if result.content.find('ACK=Success')>=0: data = cgi.parse_qs(result.content) #token = data['TOKEN'][-1] payment_status = data['PAYMENTSTATUS'][0] if payment_status == 'Completed': data2 = {'method':'PP','quantity':'1','item_id':pkg,'buyer':buyerid} data2['order_number'] = data['TRANSACTIONID'][0] data2['price'] = data['AMT'][0] data2['currency'] = data['CURRENCYCODE'][0] if 'SETTLEAMT' in data: logging.debug('settlement: %s'%data['SETTLEAMT'][0]) fee = float(data['FEEAMT'][0]) tstamp = datetime_from_timestampz(data['ORDERTIME'][0]) buyer = helper.get_user_by_key(ukey,False) if buyer is None: logging.warning('Buyer %s is not user!'%ukey) helper.send_email('Suinova test payment failure notification','Buyer %s not found'%ukey) web.response.out.write('Thank you!') return try: save_exchange(buyer,tstamp,fee,data2) except Exception: pass web.response.out.write(THANKU_PAGE) else: logging.warning('ppapprove result from DoExpressCheckoutPayment, payment status is %s'%payment_status) logging.info(result.content) web.response.out.write('Not completed') else: logging.error('ppapprove send DoExpressCheckoutPayment returned: %s'%result.content) web.fail('Error contacting PayPal, try later, <a href="/">Go back</a>') except Exception,e: logging.exception(e) web.fail('Error contacting PayPal, try later, <a href="/">Go back</a>')
result = urlfetch.fetch(url=GC_REQUEST_URLS[GC_WHICH],payload=request_xml,method=urlfetch.POST,headers=GC_HEADER); except Exception,e: logging.exception(e) web.error(500) #will cause resend to google checkout try: if result.content.find('<charge-amount-notification') > 0: #charged, so save in ds data = get_google_notification_data(result.content) if 'original_buyer' not in data: ers = 'merchange-private-data not available in charge-amount-notification' logging.error(ers) helper.send_email('Suinova test payment failure notification',ers) web.succeed() #return 200 not to resend to Google Checkout return buyer_id = data['original_buyer'] buyer = helper.get_user_by_key(buyer_id,False) #'gg_%s' % data['buyer']) if buyer is None: logging.warning('Buyer %s is not user!'%buyer_id) helper.send_email('Suinova test payment failure notification','Buyer %s not found'%buyer_id) web.succeed() #return 200 not to resend to Google Checkout return gcfee = extract_text_in_tag(result.content,'total') if len(gcfee)>0: try: fee = float(gcfee[0]) except TypeError,e: logging.error('float(%s) error:%s'%(gcfee[0],e)) fee = 0 else: fee = 0 pkg_id = data['item_id']
def initialize(self, request, response): """ Authenticate through Google account. """ webapp.RequestHandler.initialize(self, request, response) from google.appengine.api import users user = users.get_current_user() if not user: logging.debug( 'GoogleRequest.initialize: not login, redirect to /gg') self.redirect(users.create_login_url("/gg/home")) self.get = (lambda *args: None) self.post = (lambda *args: None) else: #user logged in google account,check our cookie sns = 'gg' #Google: how to make use of GMail contact, chat etc? via OAuth uid = '%s_%s' % (sns, user.user_id()) logging.debug( 'GoogleRequest.initialize: %s visit via Google, try login' % uid) su = helper.from_cache(uid) if not su: su = helper.get_user_by_key(uid, False) #no memcache if su is None: logging.debug( 'GoogleRequest.initialize: New user, try create') em = user.email() name = em[:em.find('@')] su = helper.create_user(uid, name, em) #auto cached if successful if su is None: logging.error( 'GoogleRequest.initialize: create_user(%s,%s,%s) failed' % (uid, name, em)) self.response.out.write( 'Server in maintenance, please come back later. Thank you.' ) self.get = self.post = ( lambda *args: None) #stop calling request handler return else: logging.debug( 'GoogleRequest.initialize: new session today, try cache' ) su._cache_time = datetime.utcnow() if helper.to_cache(uid, su, helper.PLAYER_CACHE_SECS): logging.debug( 'GoogleRequest.initialize: Memcached, task dau and send email to admin' ) taskqueue.add(url='/task/dau', params={ 'usr': uid, 'act': 'login' }) #if uid not in ['gg_109722387073140662444','gg_108772542023352813713']: helper.send_email( 'Login SuiComics: %s(%s) @ %s' % (su.name, uid, datetime.utcnow()), 'OK') else: #in memcache logging.debug('GoogleRequest.initialize: in memcache, revisit') if hasattr(su, '_cache_time'): if (datetime.utcnow() - su._cache_time).seconds >= 3600: su._cache_time = datetime.utcnow() helper.to_cache(uid, su, helper.PLAYER_CACHE_SECS) self.tempvars = { 'user': su, 'sns': 'gg', 'login': True, 'uname': su.name, 'onFacebook': False } args = get_session_from_cookie(self.request.cookies) if not args: put_cookie(self.response.headers, uid, su.token, sns) #a generated random token else: self.tempvars.update(args) #['sns','uid','token'] self.sns = sns self.user = su
def login(self, uid, access_token): """ Login routine. From FacebookRequest: login(facebook_uid """ self.sns = 'fb' ukey = '%s_%s' % (self.sns, uid) u = helper.from_cache(ukey) if not u: u = helper.get_user_by_key(ukey, False) #memcache=False if not u: graph = facebook.GraphAPI(access_token) profile = graph.get_object('me') u = helper.create_user(ukey, profile['name'], profile.get('email', None), False) #save=False if not u: logging.error( 'FacebookRequest.login: helper.create_user failed') self.redirect_with_msg( 'Server in maintenance, please try later, thank you.') self.get = self.post = (lambda *args: None) return u.access_token = access_token u.save() logging.debug('FacebookRequest.login: New User %s saved' % ukey) else: now = datetime.utcnow() u._cache_time = now if helper.to_cache( ukey, u, helper.PLAYER_CACHE_SECS ): #2 hours, if memcache fails, do not task/dau or send_email # if u.lastime.day != now.day or u.lastime.month != now.month: # taskqueue.add(url='/task/dau',params={'usr':ukey,'act':'login'}) taskqueue.add(url='/task/dau', params={ 'usr': ukey, 'act': 'login' }) if ukey not in [ 'fb_669391906', 'fb_1464710918', 'fb_1842536962', 'fb_1831016858' ]: helper.send_email( 'Login SuiComics: %s(%s) @ %s' % (u.name, ukey, now), 'OK') else: helper.send_email( 'Login SuiComics: %s(%s) @ %s' % (u.name, ukey, now), 'OK - to remove this') else: #got user from memcache if u.access_token != access_token: u.access_token = access_token u.save() logging.debug( 'FacebookRequest.login: access_token updated while %s still in memcache' % ukey) elif hasattr(u, '_cache_time'): if (datetime.utcnow() - u._cache_time).seconds >= 3600: u._cache_time = datetime.utcnow() helper.to_cache(ukey, u, helper.PLAYER_CACHE_SECS) if self.request.headers.get('User-Agent', '').find('MSIE') >= 0: #logging.debug('addHeader P3P for MSIE') #self.response.headers.add_header('P3P','CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"') self.response.headers.add_header('P3P', 'CP="SuiComics"') args = get_session_from_cookie(self.request.cookies) if not args or args['uid'] != ukey: put_cookie(self.response.headers, ukey, u.token, self.sns) self.user = u self.tempvars = { 'user': u, 'sns': 'fb', 'login': True, 'uname': u.name, 'onFacebook': True } if self.request.get('ref') == 'bookmarks': c = self.request.get('count') if c != '0': helper.clear_fb_count(uid)