Ejemplo n.º 1
0
	def post(self):
		try:
			#this is passed when an ajax form is checking the login state
			email = self.request.get('email')
			pw = enc.encrypt_password(self.request.get('pw'))
			
			if self.request.get('type') == 'ajax':
				logging.debug('AJAX CHECK')
	
				#check if login is valid
				q = levr.BusinessOwner.gql('WHERE email =:1 AND pw =:2', email, pw)
				if q.get():
					#echo that login was successful
					self.response.out.write(True)
				else:
					#echo that login was not successful
					self.response.out.write(False)
			else:
				#Normal login attempt. Redirects to manage or the login page
				email = self.request.get('email')
#				email = db.Email(email)
				pw = enc.encrypt_password(self.request.get('pw'))
				logging.debug(email)
				logging.debug(pw)
				
				if email == None:
					email = ''
				if pw == None:
					pw = ''
				
				
				#the required text fields were entered
				#query database for matching email and pw
				owner = levr.BusinessOwner.all().filter('email =', email).filter('pw =', pw).get()
				#search for owner
				logging.debug(owner)
				if owner != None:
					logging.debug('owner exists... login')
					#owner exists in db, and can login
					session = get_current_session()
					session['ownerID'] = enc.encrypt_key(owner.key())#business.key())
					session['loggedIn'] = True
					session['validated'] = owner.validated
					self.redirect('/merchants/manage')
				else:
					#show login page again - login failed
					template_values = {
					'success'		: False,
					'email'			: email
					}
					template = jinja_environment.get_template('templates/login.html')
					self.response.out.write(template.render(template_values))
#					self.response.out.write(template_values)
		except:
			levr.log_error()
Ejemplo n.º 2
0
	def post(self):
		'''Resets password on the database'''
		try:
			password1 = self.request.get('newPassword1')
			password2 = self.request.get('newPassword2')
			uid = self.request.get('id')
			uid = enc.decrypt_key(uid)
			
			if password1 == password2:
				#passwords match
				logging.debug('flag password success')
				encrypted_password = enc.encrypt_password(password1)
				logging.debug(uid)
				owner = levr.BusinessOwner.get(uid)
				owner.pw = encrypted_password
				owner.put()
				
				#log user in and redirect them to merchants/manage
				session = get_current_session()
				session['ownerID'] = enc.encrypt_key(owner.key())#business.key())
				session['loggedIn'] = True
				session['validated'] = owner.validated
				self.redirect('/merchants/manage')
				
			else:
				#passwords do not match
				self.redirect('/merchants/password/reset?id=%s&success=False' % enc.encrypt_key(uid))
		except:
			levr.log_error()
Ejemplo n.º 3
0
    def get(self, *args, **kwargs):
        '''
		A user logs in with levr using an email or alias, and a password
		'''
        try:
            #RESTRICTED
            logging.debug('LOGIN LEVR\n\n\n')
            logging.debug(kwargs)

            email_or_owner = kwargs.get('email_or_owner')
            pw = kwargs.get('pw')
            pw = enc.encrypt_password(pw)

            #check both email and password

            r_email = levr.Customer.gql('WHERE email = :1 AND pw=:2',
                                        email_or_owner, pw).get()
            r_alias = levr.Customer.gql('WHERE alias = :1 AND pw=:2',
                                        email_or_owner, pw).get()
            if r_email:
                #match based on email
                existing_user = r_email
            elif r_alias:
                #match based on alias
                existing_user = r_alias
            else:
                api_utils.send_error(self, 'Authentication failed.')
                return

            #create or refresh the alias
            existing_user = levr.build_display_name(existing_user)

            #===================================================================
            # Spoof Ninja Activity!
            #===================================================================

            data = api_utils.SpoofUndeadNinjaActivity(existing_user).run()
            logging.debug(levr.log_dict(data))
            #set last login
            existing_user = data['user']
            #still here? update last login by putting
            existing_user.put()

            #package user, private setting, send token
            response = {
                'user':
                api_utils.package_user(existing_user, True, send_token=True)
            }

            api_utils.send_response(self, response, existing_user)
        except:
            levr.log_error()
            api_utils.send_error(self, 'Server Error')
Ejemplo n.º 4
0
	def get(self,*args,**kwargs):
		'''
		A user logs in with levr using an email or alias, and a password
		'''
		try:
			#RESTRICTED
			logging.debug('LOGIN LEVR\n\n\n')
			logging.debug(kwargs)
			
			email_or_owner = kwargs.get('email_or_owner')
			pw = kwargs.get('pw')
			pw = enc.encrypt_password(pw)
			
			
			#check both email and password
			
			r_email = levr.Customer.gql('WHERE email = :1 AND pw=:2',email_or_owner,pw).get()
			r_alias  = levr.Customer.gql('WHERE alias = :1 AND pw=:2',email_or_owner,pw).get()
			if r_email:
				#match based on email
				existing_user = r_email
			elif r_alias:
				#match based on alias
				existing_user = r_alias
			else:
				api_utils.send_error(self,'Authentication failed.')
				return
			
			#create or refresh the alias
			existing_user = levr.build_display_name(existing_user)
			
			#===================================================================
			# Spoof Ninja Activity!
			#===================================================================
			
			data = api_utils.SpoofUndeadNinjaActivity(existing_user).run()
			logging.debug(levr.log_dict(data))
			#set last login
			existing_user = data['user']
			#still here? update last login by putting
			existing_user.put()
			
			#package user, private setting, send token
			response = {'user':api_utils.package_user(existing_user,True,send_token=True)}
			
			api_utils.send_response(self,response,existing_user)
		except:
			levr.log_error()
			api_utils.send_error(self,'Server Error')
Ejemplo n.º 5
0
def signupCustomer(email,alias,pw):
	pw = enc.encrypt_password(pw)
	'''Check availability of username+pass, create and login if not taken'''
	#check availabilities
	q_email = levr.Customer.gql('WHERE email = :1',email)
	q_alias  = levr.Customer.gql('WHERE alias = :1',alias)
	r_email = q_email.get()
	r_alias = q_alias.get()
	
	if r_email == None and r_alias == None: #nothing found
		c 		= levr.Customer()
		c.email = email
		c.pw 	= pw
		c.alias = alias
		
		#generate random number to decide what split test group they are in
		choice = randint(10,1000)
		decision = choice%2
		if decision == 1:
			group = 'paid'
		else:
			group = 'unpaid'
		
		#set a/b test group to customer entity
		c.group = group
		
		#put
		c.put()
		return {
			'success'	:True,
			'uid'		:enc.encrypt_key(c.key().__str__()),
			'email'		:email,
			'userName'	:alias,
			'group'		:group
			}
	elif r_email != None:
		return {
			'success': False,
			'field': 'email',
			'error': 'That email is already registered. Try again!'
		}
	elif r_alias != None:
		return {
			'success': False,
			'field': 'alias',
			'error': 'That username is already registered. Try again!'
		}
Ejemplo n.º 6
0
def loginCustomer(email_or_owner,pw):
	'''This is passed either an email or a username, so check both'''
	logging.info(pw)
	pw = enc.encrypt_password(pw)
	logging.info(pw)
	logging.info(email_or_owner)
	q_email = levr.Customer.gql('WHERE email = :1 AND pw=:2',email_or_owner,pw)
	q_owner  = levr.Customer.gql('WHERE alias = :1 AND pw=:2',email_or_owner,pw)
	r_email = q_email.get()
	r_owner = q_owner.get()
	if r_email != None:
		#found user on the basis of email
		
		#automatically update last login
		r_email.put()
		return {
			'success'		: True,
			'data'			: {
								'uid'			: enc.encrypt_key(r_email.key().__str__()),
								'email'			: r_email.email,
								'userName'		: r_email.alias,
								'group'			: r_email.group
								},
			'notifications'	: r_email.get_notifications()
		}
	elif r_owner != None:
		#found user on the basis of username
		
		#automatically update last_login
		r_owner.put()
		
		return {
			'success'		: True,
			'data'			: {
								'uid'			: enc.encrypt_key(r_owner.key().__str__()),
								'email'			: r_owner.email,
								'userName'		: r_owner.alias,
								'group'			: r_owner.group
								},
			'notifications'	: r_owner.get_notifications()
		}
	else:
		return {
			'success'	: False,
			'error': 'Incorrect username, email, or password. Please try again!'
		}
Ejemplo n.º 7
0
	def post(self,*args,**kwargs):
		#RESTRICTED
		try:
			logging.debug(kwargs)
			email = kwargs.get('email',None)
			alias = kwargs.get('alias',None)
			pw = kwargs.get('pw',None)
			
			'''Check availability of username+pass, create and login if not taken'''
			#check availabilities
			r_email = levr.Customer.gql('WHERE email = :1',email).get()
			r_alias  = levr.Customer.gql('WHERE alias = :1',alias).get()
			
			#if taken, send error
			if r_email:
				api_utils.send_error(self,'That email is already registered.')
				return
			if r_alias:
				api_utils.send_error(self,'That alias is already registered.')
				return
			
			#still here? create a customer, then.
			user = levr.create_new_user(
									email=email,
									alias=alias,
									pw=enc.encrypt_password(pw))
			#put and reply
			
			#create or refresh the alias
			user = levr.build_display_name(user)
			
			try:
				levr.text_notify(user.display_name+' from Levr!')
			except:
				levr.log_error()
			
			
			#put and reply
			user.put()
			
			
			response = {'user':api_utils.package_user(user,True,send_token=True)}
			api_utils.send_response(self,response,user)
		except:
			levr.log_error()
			api_utils.send_error(self,'Server Error')
Ejemplo n.º 8
0
    def post(self, *args, **kwargs):
        #RESTRICTED
        try:
            logging.debug(kwargs)
            email = kwargs.get('email', None)
            alias = kwargs.get('alias', None)
            pw = kwargs.get('pw', None)
            '''Check availability of username+pass, create and login if not taken'''
            #check availabilities
            r_email = levr.Customer.gql('WHERE email = :1', email).get()
            r_alias = levr.Customer.gql('WHERE alias = :1', alias).get()

            #if taken, send error
            if r_email:
                api_utils.send_error(self, 'That email is already registered.')
                return
            if r_alias:
                api_utils.send_error(self, 'That alias is already registered.')
                return

            #still here? create a customer, then.
            user = levr.create_new_user(email=email,
                                        alias=alias,
                                        pw=enc.encrypt_password(pw))
            #put and reply

            #create or refresh the alias
            user = levr.build_display_name(user)

            try:
                levr.text_notify(user.display_name + ' from Levr!')
            except:
                levr.log_error()

            #put and reply
            user.put()

            response = {
                'user': api_utils.package_user(user, True, send_token=True)
            }
            api_utils.send_response(self, response, user)
        except:
            levr.log_error()
            api_utils.send_error(self, 'Server Error')
Ejemplo n.º 9
0
	def post(self):
		'''Resets password on the database'''
		password1 = self.request.get('newPassword1')
		password2 = self.request.get('newPassword2')
		uid = self.request.get('id')
		uid = enc.decrypt_key(uid)
		
		if password1 == password2:
			#passwords match
			logging.debug('flag password success')
			encrypted_password = enc.encrypt_password(password1)
			logging.debug(uid)
			user = levr.Customer.get(uid)
			user.pw = encrypted_password
			user.put()
			
			template_values={'success':'True'}
			jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
			template = jinja_environment.get_template('templates/resetPasswordSuccess.html')
			self.response.out.write(template.render(template_values))
		else:
			#passwords do not match
			self.redirect('/password/reset?id=%s&success=False' % enc.encrypt_key(uid))
Ejemplo n.º 10
0
	def post(self):
		try:
			logging.debug(self.request.headers)
			logging.debug(self.request.body)
			logging.debug(self.request.params)
			
			#check login
			headerData = levr_utils.loginCheck(self, True)
			
			#get the owner information
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			ownerID = db.Key(ownerID)
			owner = levr.BusinessOwner.get(ownerID)
			logging.debug(owner)
			
			password = enc.encrypt_password(self.request.get('password'))
			if owner.pw == password:
				self.response.out.write(True)
			else:
				self.response.out.write(False)
			
		except:
			levr.log_error()
Ejemplo n.º 11
0
	def post(self):
		#get uploaded image
		upload = self.get_uploads()[0]
#		upload = self.request.get('img')
#		upload = blobstore.Blob(upload)
		blob_key= upload.key()
		img_key = blob_key
		logging.info(upload)
		
		
		
#		ethan = pat = alonso = ninja = False
		# new customer
		ethan = levr.Customer.all(keys_only=True).filter('email','*****@*****.**').get()
		levr_token = 'tlvXNw9F5Qgnqm_uKxYUx9xeyJHSRDnfBbVmUwvDWzQ'
		if not ethan:
			ethan = levr.Customer(levr_token = levr_token)
			ethan.email	= '*****@*****.**'
			ethan.pw 	= enc.encrypt_password('ethan')
			ethan.alias	= 'ethan owns the deals'
			ethan.favorites	= []
			ethan.tester = True
			ethan.levr_token = 'tlvXNw9F5Qgnqm_uKxYUx9xeyJHSRDnfBbVmUwvDWzQ'
#			ethan.foursquare_id = 37756769
			ethan.foursquare_token = 'IDMTODCAKR34GOI5MSLEQ1IWDJA5SYU0PGHT4F5CAIMPR4CR'
#			ethan.twitter_token = '819972614-2HoAwfJcHCOePogonjPbNNxuQQsvHeYeJ3U2KasI'
			ethan.twitter_screen_name = 'LevrDevr'
			ethan.twitter_id	= 819972614
			ethan = ethan.put()
		'AAACEdEose0cBANvf0FVOdH0NpoqLDZCnt8ZAlVfiYqe90CH1S7rOAEZC7ZChI340ElsX0bYXXOZC1Ks1kWU4JmsGMpUWzp7fm6CfIHKdXwN4ZAvVCFfGMa'
		pat = levr.Customer.all(keys_only=True).filter('email','*****@*****.**').get()
		if not pat:
			pat = levr.Customer(levr_token = levr_token)
			pat.email	= '*****@*****.**'
			pat.pw 	= enc.encrypt_password('patrick')
			pat.alias	= 'patrick'
			pat.favorites	= []
			pat.tester = True
			pat.levr_token = 'tlvXNw9F5Qgnqm_uKxYUx9xeyJHSRDnfBbVmUwvDWzQ'
#			pat.foursquare_id = 22161113
			pat.foursquare_token = 'ML4L1LW3SO0SKUXLKWMMBTSOWIUZ34NOTWTWRW41D0ANDBAX'
#			pat.twitter_friends_by_sn = ['LevrDevr']
			pat = pat.put()
		
		
		alonso = levr.Customer.all(keys_only=True).filter('email','*****@*****.**').get()
		if not alonso:
			alonso = levr.Customer(levr_token = levr_token)
			alonso.email	= '*****@*****.**'
			alonso.pw 	= enc.encrypt_password('alonso')
			alonso.alias	= 'alonso'
			alonso.favorites	= []
#			alonso.foursquare_token = '4PNJWJM0CAJ4XISEYR4PWS1DUVGD0MKFDMC4ODL3XGU115G0'
			alonso.tester = True
			
			alonso.levr_token = 'tlvXNw9F5Qgnqm_uKxYUx9xeyJHSRDnfBbVmUwvDWzQ'
#			alonso.foursquare_id = 32773785
			alonso.foursquare_token = 'RGTMFLSGVHNMZMYKSMW4HYFNEE0ZRA5PTD4NJE34RHUOQ5LZ'
			
			alonso = alonso.put()
		
		ninja = levr.Customer.all(keys_only=True).filter('email','*****@*****.**').get()
		if not ninja:
			ninja = levr.Customer(levr_token = levr_token)
			ninja.email	= '*****@*****.**'
			ninja.pw 	= enc.encrypt_password('santa')
			ninja.alias	= 'Followed'
			ninja.favorites = []
			ninja.tester = True
			ninja.levr_token = 'tlvXNw9F5Qgnqm_uKxYUx9xeyJHSRDnfBbVmUwvDWzQ'
			ninja = ninja.put()
			
			
		
		
		
		params = {
					'uid'				: ethan,
					'business_name'		: 'Als Sweatshop',
					'geo_point'			: levr.geo_converter('42.343880,-71.059570'),
					'vicinity'			: '10 Buick St',
					'types'				: 'Establishment,Food',
					'deal_description'	: 'This is a description gut guts who why when you buy a shoe with feet',
					'deal_line1'		: 'I am a deal',
					'distance'			: '10', #is -1 if unknown = double
					'development'		: True,
					'img_key'			: img_key
					}

		levr.dealCreate(params,'phone_new_business')
		
		params = {
					'uid'				: ethan,
					'business_name'		: 'Als Sweatshop 2',
					'geo_point'			: levr.geo_converter('42.343879999999999, -71.059569999999994'),
					'vicinity'			: '10 Buick St',
					'types'				: 'Establishment,Food',
					'deal_description'	: 'This is a description gut guts who why when you buy a shoe with feet',
					'deal_line1'		: 'I am a deal',
					'distance'			: '10', #is -1 if unknown = double
					'development'		: True,
					'img_key'			: img_key
					}
		
		deal = levr.dealCreate(params,'phone_new_business')
		p = db.get(pat)
		p.upvotes.append(deal.key())
		p.put()
		params = {
					'uid'				: ethan,
					'business_name'		: 'Als Sweatshop',
					'geo_point'			: levr.geo_converter('42.343880,-71.059575'),
					'vicinity'			: '10 Buick St',
					'types'				: 'Establishment,Food',
					'deal_description'	: 'This is a description gut guts who why when you buy a shoe with feet',
					'deal_line1'		: 'I am a deal',
					'distance'			: '10', #is -1 if unknown = double
					'development'		: True,
					'img_key'			: img_key
					}
		
		deal = levr.dealCreate(params,'phone_new_business')
		
		bus = levr.Business.gql('WHERE business_name=:1','Als Sweatshop').get()
		
		ant = levr.Customer.get(ethan)
		
		ant.owner_of = str(bus.key())
		ant.put()
		a = db.get(alonso)
		a.upvotes.append(deal.key())
		a.put()
		
		
		self.redirect('/new/test')
Ejemplo n.º 12
0
	def post(self):
		try:
			logging.debug(self.request.headers)
			logging.debug(self.request.body)
			logging.debug(self.request.params)
			
			#check login
			headerData = levr_utils.loginCheck(self, True)
			
			#get the owner information
			ownerID = headerData['ownerID']
			ownerID = enc.decrypt_key(ownerID)
			ownerID = db.Key(ownerID)
			owner = levr.BusinessOwner.get(ownerID)
			logging.debug(owner)
			
			password = enc.encrypt_password(self.request.get('old_password'))
			mode = self.request.get('change')
			logging.debug(owner.pw == password)
			if owner.pw == password:
				
				#password is correct
				
				if mode == 'email':
					#user is changing their email
					
					email			= self.request.get('new_email')
					confirm_email	= self.request.get('confirm_new_email')
					if email == confirm_email:
						logging.debug(email)
						#emails match - change owner email
						owner.email = email
						owner.put()
						self.redirect('/merchants/myAccount?success=true')
					else:
						#get the business
						business = owner.businesses.get()#TODO: this will be multiple businesses later
						
						template_values = {
						'owner'		: owner,
						'business'	: business,
						'mode'		: mode, #which form to show
						'error'		: 'confirm_new_email'
						}
						logging.debug(template_values)
						#password is incorrect
						template = jinja_environment.get_template('templates/editAccount.html')
						self.response.out.write(template.render(template_values))
					
				elif mode == 'password':
					#user is changing their password
					new_password		= self.request.get('new_password')
					confirm_new_password= self.request.get('confirm_new_password')
					
					if new_password == confirm_new_password:
						logging.debug(new_password)
						#passwords match - change owner password
						owner.pw = new_password
						owner.put()
						self.redirect('/merchants/myAccount?success=true')
					else:
						#new passwords do not match
						#get the business
						business = owner.businesses.get()#TODO: this will be multiple businesses later
						
						template_values = {
						'owner'		: owner,
						'business'	: business,
						'mode'		: mode, #which form to show
						'error'		: 'confirm_new_password'
						}
				
						#password is incorrect
						template = jinja_environment.get_template('templates/editAccount.html')
						self.response.out.write(template.render(template_values))
				else:
					#mode not recognized
					logging.error('mode not recognized')
			else:
				#old password is incorrect
				#get the business
				business = owner.businesses.get()#TODO: this will be multiple businesses later
				
				template_values = {
				'owner'		: owner,
				'business'	: business,
				'mode'		: mode, #which form to show
				'error'		: 'old_password'
				}
				
				logging.debug(template_values)
				template = jinja_environment.get_template('templates/editAccount.html')
				self.response.out.write(template.render(template_values))
		except:
			levr.log_error(self.request.headers)
Ejemplo n.º 13
0
	def post(self):
			#A business owner is signing up in the tour
		try:
			logging.debug(self.request.headers)
			logging.debug(self.request.body)
			logging.debug(self.request.params)
			
			owner = levr.BusinessOwner(
				#create owner with contact info, put and get key
				email			=self.request.get('email'),
				pw				=enc.encrypt_password(self.request.get('password')),
				validated		=False
				).put()
			logging.debug(owner)
			
			#get the business info from the form
			business_name	= self.request.get('business_name')
			geo_point		= levr.geo_converter(self.request.get('geo_point'))
			vicinity		= self.request.get('vicinity')
			types			= self.request.get_all('types[]')
			
			#parse business name to create an upload email
			logging.debug(business_name)
			name_str = levr.tagger(business_name)
			logging.debug(name_str)
			#create unique identifier for the business
			if name_str[0] == 'the' or name_str[0] == 'a' or name_str[0] == 'an':
				#dont like the word the in front
				logging.debug('flag the!')
				identifier = ''.join(name_str[1:3])
			else:
				identifier = ''.join(name_str[:2])
			upload_email = "u+"+identifier+"@levr.com"
			
			#check if that already exists
			num = levr.Business.all().filter('upload_email =',upload_email).count()
			
			logging.debug(num)
			if num != 0:
				#a business already exists with that upload email
				#increment the 
				upload_email = "u+"+identifier+str(num)+"@levr.com"
			
			logging.debug(upload_email)
			
			#check if business exists in database
			business = levr.Business.all().filter('business_name =', business_name).filter('vicinity =',vicinity).get()
			logging.debug(business)
			
			if business:
				logging.debug(levr_utils.log_model_props(business))
				logging.debug(owner)
				logging.debug(upload_email)
				logging.debug('flag business already exists')
				#have to delete business entity instead of update because gae wont update reference on owner entity
				if business.owner == None:
					#grab this business! 
					business.owner	= owner
					upload_email	= upload_email
					#TODO targeted will be set to false in the future, removing signed businesses from the ninja pool
#					targeted		= False
				else:
#					db.delete(business)
					logging.error('A business owner just signed up claiming a business that another person has claimed')
			else:
				logging.debug('flag business does not exist')
			
				#create business entity
				business = levr.Business(
					#create business
					owner			=owner,
					business_name	=business_name,
					vicinity		=vicinity,
					geo_point		=geo_point,
					types			=types,
					upload_email	=upload_email
					#TODO targeted will be set to false in the future, removing signed businesses from the ninja pool
#					targeted		=False
					)
			logging.debug(levr_utils.log_model_props(business))
			business.put()
			
			#creates new session for the new business
			session = get_current_session()
			session['ownerID']	= enc.encrypt_key(owner)
			session['loggedIn']	= True
			session['validated']= False
			logging.debug(session)


			#send email to pat so that he will know that there is a new business.
			message = mail.EmailMessage(
				sender	="LEVR AUTOMATED <*****@*****.**>",
				subject	="New Merchant signup",
				to		="*****@*****.**")
			logging.debug(message)
			body = 'New merchant\n\n'
			body += 'Business: '  +str(business_name)+"\n\n"
			body += 'Business ID: '+str(business)+"\n\n"
			body += "Owner Email:"+str(self.request.get('email'))+"\n\n"
			message.body = body
			message.send()


			#forward to appropriate page
			if self.request.get('destination') == 'upload':
				self.redirect('/merchants/upload')
			elif self.request.get('destination') == 'create':
				self.redirect('/merchants/deal')
		except:
			levr.log_error(self.request.body)
Ejemplo n.º 14
0
	def post(self,*args,**kwargs): #@UnusedVariable
		'''
		Checks for existing account with that business
		If the account exists, return true
		
		@attention: Only handles the case where a single account is tied to no more than one business
		
		@keyword email: required
		@keyword password: required
		@keyword business_name: required
		@keyword vicinity: required
		@keyword geo_point: required
		@keyword types: require
		@keyword development: optional
		
		@return: packaged_user with levrToken, packaged_business
		'''
		# for invalid credential responses
		user_doesnt_own_business_message = 'User does not own that business'
		# for packaging
		private = True
		followers = False
		
		# input values
		email = kwargs.get('email')
		password = kwargs.get('pw')
		business_name = kwargs.get('businessName')
		vicinity = kwargs.get('vicinity')
		geo_point = kwargs.get('geoPoint')
		types = kwargs.get('types')
		development = kwargs.get('development',False) # TODO: switch this to False by default when changing to live
		phone_number = kwargs.get('phoneNumber','')
		try:
			# Convert input data
			password = enc.encrypt_password(password)
			types = types.split(',')
			
			logging.debug('{}\n{}\n{}\n{}'.format(repr(business_name),repr(vicinity),geo_point,repr(types)))
			
			# check for existing entities
			user = levr.Customer.all().filter('email',email).get()
			requested_business = levr.Business.all().filter('business_name',business_name).filter('vicinity',vicinity).get()
			
			if user:
				logging.info('User exists')
				# check password
				assert user.pw == password, 'Password does not match username'
				
				# user should have a business
				try:
					business = user.businesses.get()
					# if the user has a business, it should be the business that was requested
					assert business, 'User does not own any businesses yet'
				except:
					logging.debug('user does not have a business yet - create one')
					# if the user does not have a business yet, add this one.
					business = levr.create_new_business(business_name,vicinity,geo_point,types,phone_number,
													owner=user
													)
#					assert False, user_doesnt_own_business_message
				else:
					logging.debug('User owns a business')
#					logging.debug(levr.log_model_props(business.owner))
#					logging.debug(levr.log_model_props(requested_business.owner))
#					if requested_business:
#						assert business.key() == requested_business.key(), user_doesnt_own_business_message
			else:
				logging.debug('User does not exist. Create a new one!!')
				# Create an account for the user with that business
				user = levr.create_new_user(
										tester=development,
										pw=password,
										email=email,
										display_name=business_name,
										)
				logging.debug(business_name)
				logging.debug(levr.log_model_props(user))
				if not requested_business:
					logging.debug('requested business was not found')
					business = levr.create_new_business(business_name,vicinity,geo_point,types,phone_number,
													owner=user
													)
				else:
					logging.debug('requested business was found')
					business = requested_business
					# 
					business.owner = user
					business.put()
			
			logging.debug('business: '+repr(business))
			#===================================================================
			# # Send message to the founders that someone has signed up for the app
			#===================================================================
			if not development:
				try:
					from google.appengine.api import mail
					message = mail.AdminEmailMessage(
													sender = '*****@*****.**',
													subject = 'New Merchant',
													)
					message.body = levr.log_model_props(user,['email','display_name',])
					message.body += levr.log_model_props(business,['business_name','vicinity'])
					message.check_initialized()
					message.send()
					
				except:
					levr.log_error()
			
			#===================================================================
			# # package and send
			#===================================================================
			packaged_user = api_utils.package_user(user, private, followers,send_token=True)
			packaged_business = api_utils.package_business(business)
			response = {
					'user' : packaged_user,
					'business' : packaged_business
					}
			self.send_response(response)
			# TODO: Merchant connect - handle all cases - new and existing accounts
		except AssertionError,e:
			levr.log_error()
			self.send_error(e)
Ejemplo n.º 15
0
    def post(self, *args, **kwargs):  #@UnusedVariable
        '''
		Checks for existing account with that business
		If the account exists, return true
		
		@attention: Only handles the case where a single account is tied to no more than one business
		
		@keyword email: required
		@keyword password: required
		@keyword business_name: required
		@keyword vicinity: required
		@keyword geo_point: required
		@keyword types: require
		@keyword development: optional
		
		@return: packaged_user with levrToken, packaged_business
		'''
        # for invalid credential responses
        user_doesnt_own_business_message = 'User does not own that business'
        # for packaging
        private = True
        followers = False

        # input values
        email = kwargs.get('email')
        password = kwargs.get('pw')
        business_name = kwargs.get('businessName')
        vicinity = kwargs.get('vicinity')
        geo_point = kwargs.get('geoPoint')
        types = kwargs.get('types')
        development = kwargs.get(
            'development', False
        )  # TODO: switch this to False by default when changing to live
        phone_number = kwargs.get('phoneNumber', '')
        try:
            # Convert input data
            password = enc.encrypt_password(password)
            types = types.split(',')

            logging.debug('{}\n{}\n{}\n{}'.format(repr(business_name),
                                                  repr(vicinity), geo_point,
                                                  repr(types)))

            # check for existing entities
            user = levr.Customer.all().filter('email', email).get()
            requested_business = levr.Business.all().filter(
                'business_name', business_name).filter('vicinity',
                                                       vicinity).get()

            if user:
                logging.info('User exists')
                # check password
                assert user.pw == password, 'Password does not match username'

                # user should have a business
                try:
                    business = user.businesses.get()
                    # if the user has a business, it should be the business that was requested
                    assert business, 'User does not own any businesses yet'
                except:
                    logging.debug(
                        'user does not have a business yet - create one')
                    # if the user does not have a business yet, add this one.
                    business = levr.create_new_business(business_name,
                                                        vicinity,
                                                        geo_point,
                                                        types,
                                                        phone_number,
                                                        owner=user)
#					assert False, user_doesnt_own_business_message
                else:
                    logging.debug('User owns a business')


#					logging.debug(levr.log_model_props(business.owner))
#					logging.debug(levr.log_model_props(requested_business.owner))
#					if requested_business:
#						assert business.key() == requested_business.key(), user_doesnt_own_business_message
            else:
                logging.debug('User does not exist. Create a new one!!')
                # Create an account for the user with that business
                user = levr.create_new_user(
                    tester=development,
                    pw=password,
                    email=email,
                    display_name=business_name,
                )
                logging.debug(business_name)
                logging.debug(levr.log_model_props(user))
                if not requested_business:
                    logging.debug('requested business was not found')
                    business = levr.create_new_business(business_name,
                                                        vicinity,
                                                        geo_point,
                                                        types,
                                                        phone_number,
                                                        owner=user)
                else:
                    logging.debug('requested business was found')
                    business = requested_business
                    #
                    business.owner = user
                    business.put()

            logging.debug('business: ' + repr(business))
            #===================================================================
            # # Send message to the founders that someone has signed up for the app
            #===================================================================
            if not development:
                try:
                    from google.appengine.api import mail
                    message = mail.AdminEmailMessage(
                        sender='*****@*****.**',
                        subject='New Merchant',
                    )
                    message.body = levr.log_model_props(
                        user, [
                            'email',
                            'display_name',
                        ])
                    message.body += levr.log_model_props(
                        business, ['business_name', 'vicinity'])
                    message.check_initialized()
                    message.send()

                except:
                    levr.log_error()

            #===================================================================
            # # package and send
            #===================================================================
            packaged_user = api_utils.package_user(user,
                                                   private,
                                                   followers,
                                                   send_token=True)
            packaged_business = api_utils.package_business(business)
            response = {'user': packaged_user, 'business': packaged_business}
            self.send_response(response)
            # TODO: Merchant connect - handle all cases - new and existing accounts
        except AssertionError, e:
            levr.log_error()
            self.send_error(e)
Ejemplo n.º 16
0
	def post(self):
		#get uploaded image
		upload = self.get_uploads()[0]
#		upload = self.request.get('img')
#		upload = blobstore.Blob(upload)
		blob_key= upload.key()
		img_key = blob_key
		logging.info(upload)
		
		# new customer
#		c = levr.Customer(key='agtkZXZ-Z2V0bGV2cnIOCxIIQ3VzdG9tZXIYEgw')
		c = levr.Customer()
		c.email	= '*****@*****.**'
		c.payment_email = c.email
		c.pw 	= enc.encrypt_password('ethan')
		c.alias	= 'alonso'
		c.favorites	= []
		c.put()
		
		#new ninja
#		ninja = levr.Customer(key='agtkZXZ-Z2V0bGV2cnIOCxIIQ3VzdG9tZXIYCww')
		ninja = levr.Customer()
		ninja.email	= '*****@*****.**'
		ninja.payment_email = c.email
		ninja.pw 	= enc.encrypt_password('ethan')
		ninja.alias	= 'ninja'
		ninja.favorites = []
		ninja.put()
		
		
		b = levr.Business.all(keys_only=True).get()
		
		
#		params = {
#					'uid'				: enc.encrypt_key(c.key()),
#					'business'			: enc.encrypt_key(str(b)),
#					'deal_description'	: 'description!!!',
#					'deal_line1'		: 'DEAL LINE!',
#					'img_key'			: img_key
#					}
		params = {
					'uid'				: enc.encrypt_key(c.key()),
					'business'			: enc.encrypt_key(str(b)),
					'business_name'		: 'Alamos',
					'geo_point'			: '42.2,-71.2',
					'vicinity'			: '10 Buick St',
					'types'				: 'aaa,type_o_negative',
					'deal_description'	: 'description!!!',
					'deal_line1'		: 'DEAL LINE!',
					'img_key'			: img_key
					}
		
		(share_url,dealID) = levr_utils.dealCreate(params,'phone_existing_business')
		logging.debug(share_url)
		logging.debug(dealID)
		
		
#		#new business
##		b = levr.Business(key='agtkZXZ-Z2V0bGV2cnIOCxIIQnVzaW5lc3MYBAw')
#		b = levr.Business()
#		b.email 		= '*****@*****.**'
#		b.pw 			= enc.encrypt_password('alonso')
#		b.business_name = 'Shaws'
#		b.vicinity		= '260 Everett St East Boston, MA'
#		b.alias 		= 'Joe'
#		b.contact_phone = '603-603-6003'
#		b.geo_point		= levr.geo_converter("15.23213,60.2342")
#		b.types			= ['tag1','tag2']
#		b.put()


#		#new deal
#		d = levr.Deal(parent=b)
#		d.img				= upload.key()
#		d.businessID		= str(b)
#		d.business_name 	= 'Shaws'
#		d.secondary_name	= 'second name'
#		d.deal_text			= '50% off booze'
#		d.deal_type			= 'bundle'
#		d.description 		= 'describe me, hun.'
#		d.img_path 			= './img/bobs-discount-furniture.png'
#		d.city 				= 'Qatar'
#		d.deal_status		= 'active'
#		d.vicinity			= '7 Gardner Terrace, Allston, MA'
#		d.tags				= ['alonso','pat','ethan']
#		d.deal_status		= 'pending'
#		d.rank				= 5
#		
#		#create the share ID - based on milliseconds since epoch
#		milliseconds = int(levr_utils.unix_time_millis(datetime.now()))
#		#make it smaller so we get ids with 5 chars, not 6
#		shortened_milliseconds = milliseconds % 100000000
#		unique_id = converter.dehydrate(shortened_milliseconds)
#		d.share_id = unique_id
#		d.put()
#
#		#new customer deal
#		cd = levr.CustomerDeal(parent=ninja)
#		cd.businessID		= str(b)
#		cd.img				= upload.key()
#		cd.business_name 	= 'Shaws'
#		cd.deal_text		= '40% of sijo'
#		cd.deal_type		= 'single'
#		cd.description 		= 'describe me, hun.'
#		cd.rating 			= 50
#		cd.count_end 		= 101
#		cd.count_redeemed 	= 0
#		cd.count_seen 		= 43
#		cd.new_redeem_count	= 0
#		cd.deal_status		= 'pending'
#		cd.geo_point		= levr.geo_converter('-80.,70.')
#		cd.vicinity			= '1234 Cherry Lane, Boston, MA 02134, USA'
#		cd.tags				= ['alonso','pat','ethan']
#		cd.rank				= 10
#		#create the share ID - based on milliseconds since epoch
#		milliseconds = int(levr_utils.unix_time_millis(datetime.now()))
#		#make it smaller so we get ids with 5 chars, not 6
#		shortened_milliseconds = milliseconds % 100000000
#		unique_id = converter.dehydrate(shortened_milliseconds)
#		cd.share_id = unique_id
#		
#		cd.put()


		self.response.headers['Content-Type'] = 'text/plain'
#		self.response.out.write('/phone/img?dealID='+enc.encrypt_key(str(c.key()))+"&size=dealDetail")
		self.response.out.write('     I think this means it was a success')