Esempio n. 1
0
	def getUserDetails(self, request_handler):
		
		#google_login_url = users.create_login_url('/') 
	        #twitter_logout_url = '/oauth/twitter/logout'

                twitter_cookie = request_handler.request.cookies.get('oauth.twitter')
        	evernote_user = OAuthClient('evernote', request_handler)
        	flickr_user = OAuthClient('flickr', request_handler)

                #return variables
        	screen_name=None
                avatar=None
		auth_service=None
		user_details_key=None

                instaright_account=None
		# used to connect user details with session
                evernote_username=None
                flickr_username=None

		google_user = users.get_current_user()
		#logging.info('trying to connect with fb key %s secret %s' %( self.facebook_key, self.facebook_secret))
        	facebook_user = facebook.get_user_from_cookie(request_handler.request.cookies, self.facebook_key, self.facebook_secret)
                facebook_access_token=None
                existing_user = None
        	if google_user:
			existing_user= UserDetails.gql('WHERE google_profile=\'%s\'' %google_user.email()).get()
			existing_user_by_mail = UserDetails.gql('WHERE mail=\'%s\'' %google_user.email()).get()
                        if self.ud is None and existing_user is not None:
                                self.ud = existing_user
                                if self.ud.mail is None:
                                        self.ud.mail = google_user.email()
                        #TODO what is both are not None and pointing to different entities
                        if existing_user is not None and existing_user_by_mail is not None and str(existing_user.key()) != str(existing_user_by_mail.key()):
                                logging.error('data inconsistancy for google user %s ' % google_user.email())
                        #NOTE: data consistency 
			if existing_user is None and existing_user_by_mail is not None:
                                existing_user_by_mail.google_profile = google_user.email()
                                existing_user_by_mail.put()
                                existing_user = existing_user_by_mail
                        if existing_user is None:
                                #TODO update google profile
				existing_user = UserDetails()
				existing_user.mail=google_user.email()
                                existing_user.google_profile=google_user.email()
                        elif existing_user.avatar is not None:
                                avatar = existing_user.avatar
				existing_user.mail=google_user.email()
                        existing_user.put()

			auth_service='google'
                	screen_name=google_user.nickname()
			user_details_key=existing_user.key()

			user_signup_badge = UserBadge.gql('WHERE user_property = :1 and badge = :2', existing_user.key(),'signup').get()
                        if user_signup_badge is None:
                                user_badge = UserBadge()
                                user_badge.user = screen_name
                                user_badge.badge = 'signup'
                                badge = Badges.gql('WHERE badge_label = :1', 'signup').get()
                                user_badge.badge_property = badge.key()
                                user_badge.user_property = existing_user.key()
                                user_badge.put()
                        instaright_account=existing_user.instaright_account
                if twitter_cookie is not None and len(twitter_cookie) > 0:
			try:
                        	twitter_user = OAuthClient('twitter', request_handler)
				info = twitter_user.get('/account/verify_credentials')
				profile_image_url = "%s" %info['profile_image_url']
				existing_user = UserDetails.gql('WHERE twitter = \'http://twitter.com/%s\'' % screen_name).get()
				if existing_user is None:
					logging.info('new twitter user login %s' % screen_name)
					existing_user=UserDetails()
					existing_user.twitter='http://twitter.com/%s' %screen_name
					existing_user.avatar = profile_image_url
				else:
					logging.info('existing twitter user login %s' % screen_name)
					if existing_user.avatar is None:
						existing_user.avatar = profile_image_url
                                        else:
                                                avatar = existing_user.avatar
                                existing_user.put()
				user_details_key=existing_user.key()
                                twitter_cookie = request_handler.request.cookies.get('oauth.twitter')
                                twitter_oauth = OAuthAccessToken.get_by_key_name(twitter_cookie)
                                if twitter_oauth is not None and existing_user is not None:
                                        twitter_token = twitter_oauth.oauth_token
                                        twitter_secret= twitter_oauth.oauth_token_secret
                                        taskqueue.add(url='/util/twitter/get_friends', params={'user_details_key': str(existing_user.key()),'user_token':twitter_token, 'user_secret': twitter_secret})
                                if screen_name is None:
                		        screen_name = "%s" % info['screen_name']
                                        avatar=profile_image_url
				        auth_service='twitter'
                                logging.info('updating user score ...')
			        user_signup_badge = UserBadge.gql('WHERE user_property = :1 and badge = :2', existing_user.key(),'signup').get()
                                if user_signup_badge is None:
                                        user_badge = UserBadge()
                                        user_badge.user = screen_name
                                        user_badge.badge = 'signup'
                                        badge = Badges.gql('WHERE badge_label = :1', 'signup').get()
                                        user_badge.badge_property = badge.key()
                                        user_badge.user_property = existing_user.key()
                                        user_badge.put()
                                instaright_account=existing_user.instaright_account
			except:
				e0,e = sys.exc_info()[0], sys.exc_info()[1]
                                logging.info('got error while using twitter oauth: %s => %s' %(e0, e))
        	if facebook_user:
                	graph = facebook.GraphAPI(facebook_user["access_token"])
			try:
                		profile = graph.get_object("me")
				profile_link=profile["link"]
				profile_id=profile["id"]
                		friends = graph.get_connections("me", "friends")
				existing_user=UserDetails.gql('WHERE facebook = \'%s\'' % profile_link).get()
				if existing_user is not None:
					logging.info('existing facebook logging %s' % profile_link)
					existing_user.facebook=profile_link
					existing_user.facebook_friends=simplejson.dumps(friends)
					existing_user.facebook_profile=profile["name"]
					existing_user.facebook_id=profile_id
					if existing_user.avatar is None:
						existing_user.avatar = avatar
                                        else:
                                                avatar = existing_user.avatar
					existing_user.put()
				else:
					logging.info('new facebook logging %s' % profile_link)
					existing_user=UserDetails()
					existing_user.facebook=profile_link
					existing_user.facebook_profile=profile["name"]
					existing_user.facebook_friends=simplejson.dumps(friends)
					existing_user.facebook_id=profile_id
					existing_user.avatar = avatar
					existing_user.put()
                                if screen_name is None:
                		        screen_name = profile["name"]
				        auth_service='facebook'
                                        avatar=existing_user.avatar
				user_details_key=existing_user.key()
			        user_signup_badge = UserBadge.gql('WHERE user_property = :1 and badge = :2', existing_user.key(),'signup').get()
                                if user_signup_badge is None:
                                        user_badge = UserBadge()
                                        user_badge.user = screen_name
                                        user_badge.badge = 'signup'
                                        badge = Badges.gql('WHERE badge_label = :1', 'signup').get()
                                        user_badge.badge_property = badge.key()
                                        user_badge.user_property = existing_user.key()
                                        user_badge.put()
                                instaright_account=existing_user.instaright_account
                                facebook_access_token=facebook_user["access_token"]
			except:
				e0,e = sys.exc_info()[0], sys.exc_info()[1]
				logging.info('error validating token %s === more info: %s' %(e0,e))
		
                if evernote_user.get_cookie() is not None and len(evernote_user.get_cookie()) > 0:
                        logging.info('evernote token active: %s' % evernote_user)
                        logging.info('evernote access token id: %s' % evernote_user.get_cookie())
                        evernote_access = evernote_user.get_cookie()
                        access_token = OAuthAccessToken.get_by_key_name(evernote_access)
                        if access_token is not None and access_token.service == 'evernote':
                                evernote_username = access_token.specifier
                                if existing_user is not None:
                                        existing_user.evernote_profile = evernote_username
                                        existing_user.put()
                        
                if flickr_user.get_cookie() is not None and len(flickr_user.get_cookie()) > 0:
                        logging.info('flickr token active: %s' % flickr_user)
                        logging.info('flickr access token id: %s' % flickr_user.get_cookie())
                        flickr_access = flickr_user.get_cookie()
                        access_token = OAuthAccessToken.get_by_key_name(flickr_access)
                        if access_token is not None and access_token.service == 'flickr':
                                flickr_username = access_token.specifier
                                if existing_user is not None:
                                        existing_user.flickr_profile = flickr_username
                                        existing_user.put()

		log_out_cookie = request_handler.request.cookies.get('user_logged_out')
		path=request_handler.request.path
		logging.info('path: %s' %path)
		#reset logout cookie in case of /account url
		if log_out_cookie and path == '/account':
			logging.info('deleting logout cookie')
                        expires = datetime.datetime.now()
                        exp_format = datetime.datetime.strftime(expires, '%a, %d-%b-%Y %H:%M:%S GMT')
			request_handler.response.headers.add_header('Set-Cookie', 'user_logged_out=%s; expires=%s; path=/' %( '0', exp_format))
			
		logging.info('user auth with %s: %s' %(auth_service, screen_name))
                if screen_name is not None and screen_name not in self.skip_list:
                        logging.info('user %s not in skip list %s ... sending mail' %(screen_name, str(self.skip_list)))
                        mail.send_mail(sender='*****@*****.**', to='*****@*****.**', subject='User sign up!', html='Awesome new user(%s) signed up: %s <br>avatar <a href="%s"><img src="%s" width=20 height=20 /></a>' %(auth_service, screen_name , avatar, avatar), body='Awesome new user(%s) signed up: %s avatar %s' %(auth_service, screen_name, avatar))
                                        
                user_details = {'screen_name':screen_name, 'auth_service':auth_service, 'user_details_key':user_details_key, 'avatar':avatar, 'instaright_account':instaright_account,'facebook_access_token': facebook_access_token, 'evernote_name': evernote_username, 'flickr_name': flickr_username}
		logging.info('[utils] user details:%s' % user_details)
		return user_details
Esempio n. 2
0
        def get_user(self):
		uu = UserUtils()
		userSession = None
		self.screen_name=None
		self.auth_service=None
                self.avatar=None
                self.user_uuid=None
                self.instaright_account=None
                self.user_detail_key=None
                self.facebook_profile = None
                self.facebook_oauth_token = None
                self.twitter_profile = None
                self.twitter_oauth_token = None
                self.google_profile = None
                self.google_oauth_token = None
                self.evernote_name = None
                self.evernote_oauth_token = None
                self.flickr_name = None
                self.flickr_oauth_token = None
		self.picplz_name = None
		self.picplz_oauth_token = None
                self.ud=None
                ud_modified=None
                new_session=False

		uuid_cookie = self.request.cookies.get('user_uuid')
                evernote_cookie = self.request.cookies.get('oauth.evernote')
                twitter_cookie = self.request.cookies.get('oauth.twitter')
                flickr_cookie = self.request.cookies.get('oauth.flickr')
                picplz_cookie = self.request.cookies.get('oauth.picplz')
		logout_cookie = self.request.cookies.get('user_logged_out')
                user_details=None
		# try to get user name by cookie or from login
		if uuid_cookie:
			#Connect uuid with registered user
			logging.info('reusing uuid: %s' % uuid_cookie)
			self.user_uuid = uuid_cookie
			userSession = UserSessionFE.gql('WHERE user_uuid = :1 order by last_updatetime desc' , self.user_uuid).get()
			if userSession is not None and userSession.user_details is not None:
				self.ud = UserDetails.gql('WHERE __key__ = :1', userSession.user_details).get()

                                #fix instaright_account TODO possibly deprecated
                                if self.ud is not None and self.ud.instapaper_account is not None:
                                        self.ud.instaright_account=self.ud.instapaper_account
                                        ud_modified=True
				if self.ud is None:
					logging.error('missing proper db entry for cookie %s' % uuid_cookie)
				else:
					user_data = self.ud.getUserInfo()
                                        self.facebook_profile = self.ud.facebook_profile
                                        self.twitter_profile = self.ud.twitter
                                        self.google_profile = self.ud.google_profile
                                        self.evernote_name = self.ud.evernote_profile
                                        self.flickr_name = self.ud.flickr_profile
					self.screen_name = user_data["screen_name"]
                                        self.avatar = user_data["avatar"]
                                        self.instaright_account=self.ud.instaright_account
                                        self.user_detail_key=str(self.ud.key())
					logging.info('using screen name %s from session %s' %(self.screen_name, self.user_uuid))
                        if userSession is not None and userSession.user_details is None:
                                logging.info('user details not defined for session ... need to fix this with oauth')
			# sanity check
			if userSession is None:
				logging.info('smth wicked ')
				userSession = UserSessionFE()
                        if userSession and userSession.user_uuid is None:
                                userSession.user_uuid = str(self.user_uuid)
		else:
                        new_session=True
			self.user_uuid = uuid.uuid4()
			logging.info('generated new uuid: %s' % self.user_uuid)
                        expires = datetime.datetime.now() + datetime.timedelta(minutes=60)
                        exp_format = datetime.datetime.strftime(expires, '%a, %d-%b-%Y %H:%M:%S GMT')
                        logging.info('expr date %s' %exp_format)
			self.response.headers.add_header('Set-Cookie', 'user_uuid=%s; expires=%s; path=/' %( self.user_uuid, exp_format))

			userSession = UserSessionFE()
			userSession.user_uuuid = str(self.user_uuid)

		# not pretty but working
		if logout_cookie:
			logging.info('found logout cookie. reseting screen_name')
			self.screen_name = None
                        self.instaright_account=None
		else:
			user_details = uu.getUserDetails(self)
                        if user_details["screen_name"] is not None:
			        self.screen_name = user_details["screen_name"]
                        if user_details["avatar"] is not None:
                                self.avatar = user_details["avatar"]
                        if user_details["auth_service"] is not None:
			        self.auth_service = user_details["auth_service"]
                        if user_details["user_details_key"] is not None:
                                #NOTE: it is very important to set user details key!!!!
			        user_details_key = user_details["user_details_key"]
			        userSession.user_details = user_details_key
                                self.user_detail_key=str(user_details["user_details_key"])
                                #if ud changed? what then?
                                if self.ud is None:
                                        ud = UserDetails.gql('WHERE __key__ = :1' , db.Key(self.user_detail_key)).get()
                                        self.ud = ud
                        if user_details["instaright_account"] is not None:
                                self.instaright_account=user_details["instaright_account"]
                        if user_details["evernote_name"] is not None:
                                self.evernote_name = user_details["evernote_name"]
                        if user_details["flickr_name"] is not None:
                                self.flickr_name = user_details["flickr_name"]

			userSession.active=True
			
		userSession.screen_name = self.screen_name
		userSession.auth_service = self.auth_service

                #determine path
                url=self.request.url
                scheme, netloc, path, query, fragment = urlparse.urlsplit(url)

                existingUserPathSession=UserSessionFE.gql('WHERE user_uuid = :1 and path = :2 and screen_name = :3' , userSession.user_uuid, path, userSession.screen_name).get()
                if existingUserPathSession is None:
                        logging.info('new path %s -> %s' %(userSession.path, path))
                        newPathUserSession=UserSessionFE()
                        newPathUserSession.active=userSession.active
                        newPathUserSession.auth_service=userSession.auth_service
                        newPathUserSession.screen_name=userSession.screen_name
                        newPathUserSession.user=userSession.user
                        newPathUserSession.user_details=userSession.user_details
                        newPathUserSession.user_uuid=userSession.user_uuid
                        newPathUserSession.path=path
                        newPathUserSession.put()
		#userSession.put()

                user_token=None
                if self.ud is not None:
                        user_token=UserTokens.gql('WHERE user_details = :1', self.ud.key()).get()
                if user_token is None:
                        user_token=UserTokens()

		#token=UserTokens()
		#token.user_details = userSession.user_details
		#token.picplz_token= '1|oauth_secret=UxY3gF4CXmRt3tYqgYg4Ed49YbZLGuDx&oauth_token=dNyt8uanrG9sRXBse6P7uaPyZSDpwK26'
		#token.google_token= 'google|oauth_secret=UxY3gF4CXmRt3tYqgYg4Ed49YbZLGuDx&oauth_token=dNyt8uanrG9sRXBse6P7uaPyZSDpwK26'
		#token.put()

                user_token_modified=False
                evernote_oauth = None
                #NOTE: ud can be null on visits that include no auth
                if evernote_cookie is not None:
                        evernote_oauth = OAuthAccessToken.get_by_key_name(evernote_cookie)
                if evernote_oauth is not None and self.ud is not None:
                        evernote_token = evernote_oauth.oauth_token
                        logging.info('User Details modified ... updating evetnote token')
                        user_token.evernote_token=evernote_token
                        user_token.evernote_additional_info=evernote_oauth.additional_info
                        user_token_modified=True
			#TODO remove cookie -> after write not needed any more
                twitter_oauth = None
                if twitter_cookie is not None:
                        logging.info('twitter cookie defined %s' % twitter_cookie)
                        twitter_oauth = OAuthAccessToken.get_by_key_name(twitter_cookie)
                if twitter_oauth is not None and self.ud is not None:
                        twitter_token = twitter_oauth.oauth_token
                        twitter_secret= twitter_oauth.oauth_token_secret
                        logging.info('User Details modified ... updating twitter token')
                        user_token.twitter_token=twitter_token
                        user_token.twitter_secret=twitter_secret
                        user_token_modified=True
                        logging.info('twitter promo sent? %s' % self.ud.twitter_promo_sent)
                        if self.ud.twitter_promo_sent == False:
                                taskqueue.add(url='/service/submit/twitter/promo', params={'user_token': twitter_token, 'user_secret': twitter_secret, 'user_details_key': str(self.ud.key())})
                                self.ud.twitter_promo_sent=True
                                ud_modified=True
                picplz_oauth = None
                if picplz_cookie is not None:
                        picplz_oauth = OAuthAccessToken.get_by_key_name(picplz_cookie)
                        logging.info('picplz cookie defined %s' % picplz_cookie)
                if picplz_oauth is not None:
                        picplz_token = picplz_oauth.oauth_token
                        user_token.picplz_token = picplz_token
                        user_token_modified=True
			#TODO remove cookie -> after write not needed any more
                flickr_oauth = None
                if flickr_cookie is not None:
                        flickr_oauth = OAuthAccessToken.get_by_key_name(flickr_cookie)
                        logging.info('flickr cookie defined %s' % flickr_cookie)
                if flickr_oauth is not None and self.ud is not None:
                        flickr_token = flickr_oauth.oauth_token
                        logging.info('User Details modified ... updating flickr token %s' % flickr_token)
                        user_token.flickr_token=flickr_token
                        user_token_modified=True
                if user_details is not None and user_details["facebook_access_token"] is not None:
                        user_token.facebook_token=user_details["facebook_access_token"]
                        user_token_modified=True
                        if self.ud.facebook_promo_sent == False:
                                taskqueue.add(url='/service/submit/facebook/promo', params={'user_token': user_token.facebook_token, 'user_details_key': str(self.ud.key())})
                                self.ud.facebook_promo_sent=True
                                ud_modified=True
                if user_token_modified:
                        if user_token.user_details is None and self.ud is not None:
                                logging.info('user details for token not defined: ud = %s' %str(self.ud.key()))
                                user_token.user_details=self.ud
			if user_token.user_details is not None:
                        	logging.info('user_token modified ... updating:for user details %s' % str(user_token.user_details.key()))
                        	user_token.put()
			else:
                        	logging.info('user_token user details not defined ....' )
                if ud_modified:
                        logging.info('user details modified updating ...' )
                        self.ud.put()
                self.google_oauth_token, self.twitter_oauth_token, self.facebook_oauth_token, self.evernote_oauth_token, self.picplz_oauth_token= user_token.google_token, user_token.twitter_token, user_token.facebook_token, user_token.evernote_token, user_token.picplz_token