def post(self): if self.request.get('_put'): self.put() return name = self.request.get('name') email = self.request.get('email') push_token = self.request.get('token') device_type = self.request.get('type') if not push_token or not device_type: api.write_error(self.response, 400, 'Missing required parameter, token or type') return user = User(uuid=str(uuid.uuid4()), auth=str(uuid.uuid4())) if name: user.name = name update_gender(user) if email: user.devices.append(Device(device_type='EMAIL', data=email)) user.devices.append(Device(device_type=device_type.upper(), data=push_token)) user.put() update_user_cards(user) api.search.update_public_index(user) api.write_message(self.response, 'success', extra={'users' : [get_user_json(user, public=False)]})
def new_user(**kw): user = User( parent=User.parent_key(), name = kw['account'], img_key = '', chatclass = random.randrange(0,4), account = kw['account'], passward = hash_passward(kw['account'],kw['passward']), fbuser = False, ) user.put() return user.key.id()
def post(self): username = self.request.get('username') self.params['username'] = username password = self.request.get('password') verify = self.request.get('verify') email = self.request.get('email') self.params['email'] = email user = User.all() user.filter('username ='******'username_error'] = 'That is not a valid username' elif invalid_user: self.params['username_error'] = 'This name has been taken' else: self.params['username_error'] = '' if self.valid_password(password): self.params['password_error'] = '' else: self.params['password_error'] = 'That is not a valid password!' if verify == password: self.params['verify_error'] = '' else: self.params['verify_error'] = 'Your passwords did not match!' if self.valid_email(email): self.params['email_error'] = '' else: self.params['email_error'] = 'That is not a valid email!' if not invalid_user and self.valid_username(username) \ and self.valid_password(password) and self.valid_email(email) \ and verify == password: pwhash = au.make_pw_hash(username, password) new = User(username=username, password=pwhash, email=email) new.put() self.response.headers.add_header('Set-Cookie', 'user=%s; Path=/' % str(username)) self.response.headers.add_header('Set-Cookie', 'pw=%s; Path=/' % str(pwhash)) sleep(0.5) self.redirect('/blog/welcome') else: self.render('signup.html', **self.params)
def new_facebook_user(fb_cookie): graph = facebook.GraphAPI(fb_cookie["access_token"]) profile = graph.get_object("me") user = User( parent=User.parent_key(), fbuser = True, fid = str(profile["id"]), name = profile["name"], img_key = '', profile_url = profile["link"], access_token = fb_cookie["access_token"] ) user.put() return user
def post(self): if self.request.get('_put'): self.put() return name = self.request.get('name') member_ids = self.request.get_all('member_uuid') public = self.request.get('public') user = api.get_user(self.request) if not user: api.write_error(self.response, 400, 'Unknown or missing user') return group = Group(uuid=str(uuid.uuid4())) group.admins.append(user.key) group.members.append(user.key) group.name = name if 'public' in self.request.params and not public == '': group.public = public.lower() in ("yes", "true", "t", "1", "on") for member_id in member_ids: member = User.query(User.uuid == member_id).get() if member: group.members.append(member.key) group.put() if group.public: api.search.update_public_index(group) else: api.search.update_private_index(group, user.uuid) api.write_message(self.response, 'success', extra={'groups' : [ get_group_json(group) ]})
def get(self): """Output a list of all current users along with the requested token.""" urlsafe_key = self.request.get('key') user = User.GetByKey(urlsafe_key) invite_code = _MakeInviteCode(user) self.response.write(_RenderUserDetailsTemplate(user, invite_code))
def get(self): """Delete the user corresponding to the passed in key. If we had access to a delete method then we would not use get here. """ urlsafe_key = self.request.get('key') User.DeleteByKey(urlsafe_key) self.response.write(_RenderUserListTemplate())
def get(self, recipe_id): # check if ID is found in recipe database recipe = Recipe.get_by_id(int(recipe_id)) if not recipe : error = "That recipe was not found." template_values = { 'error' : error } else : # check if this recipe belongs to user if recipe.author == UserId() : isOwner = True else : isOwner = False recipe_author_name = User.query().filter(User.user_id == recipe.author).fetch(1)[0].name recipe_author_pic = User.query().filter(User.user_id == recipe.author).fetch(1)[0].picUrl() template_values = { 'recipe_author_pic' : recipe_author_pic, 'title': recipe.name, 'recipe' : recipe, 'isOwner' : isOwner, 'header': GetHeader('recipe'), 'recipe_author_name': recipe_author_name } IndividualRecipe = jinja_environment.get_template('templates/recipes_individual.html').render(template_values) self.response.write(IndividualRecipe)
def check_facebook_user(fb_cookie): user = User.by_fid(str(fb_cookie['uid'])) if not user: return None elif user.access_token != fb_cookie["access_token"]: user.access_token = fb_cookie["access_token"] user.put() return user
def _RenderUserListTemplate(): """Render a list of users.""" users = User.GetAll() user_payloads = _GenerateUserPayload(users) template_values = { 'user_payloads': user_payloads } template = JINJA_ENVIRONMENT.get_template('templates/user.html') return template.render(template_values)
def get(self): # check if user is already in database rawRecipes = Recipe.query().fetch() recipes = [] for rawRecipe in rawRecipes : if rawRecipe.image : recipes.append({ 'name': rawRecipe.name, 'latlng': str(rawRecipe.location), 'location': rawRecipe.location_name, 'cooktime': rawRecipe.cooktime, 'image': '<div style="background-image: url(' + rawRecipe.imageUrl() + ')"></div>', 'servings': rawRecipe.servings, 'ingredients': json.dumps(rawRecipe.ingredients), 'recipeUrl' : rawRecipe.viewUrl() }) else : recipes.append({ 'name': rawRecipe.name, 'latlng': str(rawRecipe.location), 'location': rawRecipe.location_name, 'cooktime': rawRecipe.cooktime, 'servings': rawRecipe.servings, 'ingredients': json.dumps(rawRecipe.ingredients), 'recipeUrl' : rawRecipe.viewUrl() }) user = users.get_current_user() name = user.nickname() userID = user.user_id() dbUser = User.query().filter(User.user_id == userID).fetch(1) if UserInfo() : name = dbUser[0].name template_values = { 'name': name } firstTime = False else : newUser = User(user_id=userID, name=name, savedRecipes=['']) newUser.put() name = user.nickname() firstTime = True template_values = { 'title': 'Homepage', 'recipes': json.dumps(recipes), 'header': GetHeader('homepage'), 'logout_url': users.create_logout_url('/'), 'first_time': firstTime } Homepage = jinja_environment.get_template('templates/homepage.html').render(template_values) self.response.write(Homepage)
def __init__(self, user_id): if user_id is None: self.user_object = User.get_by_id(user_id) else: if not isinstance(user_id, str): raise ValueError("UserID should be string") try: self.user_object = User.get_by_id(user_id) if self.user_object is None: logging.warning("User not found, creating new user") self.user_object = User(id=user_id) self.user_object.put() except Exception as e: logging.error("Something wient wrong : {}".format(e)) raise Exception self.userid = self.user_object.key.id()
def post(self): """Store client id, client secret, and domain verification content.""" client_id = self.request.get('client_id') client_secret = self.request.get('client_secret') OAuth.Update(client_id, client_secret) OAuth.Flush() dv_content = self.request.get('dv_content') DomainVerification.Update(dv_content) if User.GetCount() > 0: self.redirect(PATHS['user_page_path']) else: self.redirect(PATHS['user_add_path'])
def get(self,extID): ext = Extension.gql('WHERE extID = :1',extID).get() if not ext: path = os.path.join(os.path.dirname(__file__), 'templates/head.html') self.response.out.write(template.render(path, {'title':'Extension Not Found'})) path = os.path.join(os.path.dirname(__file__), 'templates/ext404.html') self.response.out.write(template.render(path, {})) self.response.set_status(404); else: # Convert the Markdown in the description to HTML, # but escape any HTML added by the user. ext.description = markdown.markdown(text=gfm.gfm(ext.description), safe_mode='escape') # Add the Extension to the template vars dictionary and # set other template vars to their default values. templateVars = { 'ext':ext, 'upvotePercent':0, 'downvotePercent':0, 'ratingCount':0, 'userRating':None, 'starred':False, 'userIsDev':False } if ext.developer: templateVars['devname'] = ext.developer.nickname() templateVars['ratingCount'],templateVars['upvotePercent'],templateVars['downvotePercent'] = getRatingInfo(extID) user = users.get_current_user() if user: userEntry = User.gql('WHERE user = :1',user).get() if userEntry: if extID in userEntry.starred: templateVars['starred'] = True userRating = Rating.gql('WHERE user = :1 AND extID = :2',user,extID).get() if userRating: templateVars['userRating'] = userRating.value else: templateVars['userRating'] = 0 # Every user's default vote is zero if user == ext.developer: templateVars['userIsDev'] = True path = os.path.join(os.path.dirname(__file__), 'templates/head.html') self.response.out.write(template.render(path, {'title':ext.title,'stylesheet':'gallery'})) path = os.path.join(os.path.dirname(__file__), 'templates/info.html') self.response.out.write(template.render(path, templateVars)) path = os.path.join(os.path.dirname(__file__), 'templates/foot.html') self.response.out.write(template.render(path, {}))
def get_user(request): try: auth_header = request.headers['Authorization'] except KeyError: auth_header = request.get('auth') if auth_header: uuid, auth = get_uuid_auth(auth_header) if uuid and auth: user = User.query(User.uuid == uuid).get() if user and user.auth == auth: return user return None
def get(self): username = self.request.cookies.get('user') if not username: self.redirect('/blog/signup') else: password = self.request.cookies.get('pw') user = User.all() user.filter('username ='******'Welcome, %s' % username) else: self.response.write('逗逼再见!')
def get(self): username = self.request.cookies.get('user') if not username: self.render('login.html', **self.params) else: password = self.request.cookies.get('pw') user = User.all() user.filter('username ='******'/blog/welcome') else: self.params['error'] = '逗逼再见!' self.render('login.html', **self.params)
def post(self): username = self.request.get('username') self.params['username'] = username password = self.request.get('password') user = User.all() user.filter('username ='******'Set-Cookie', 'user=%s; Path=/' % str(username)) self.response.headers.add_header('Set-Cookie', 'pw=%s; Path=/' % str(u.password)) sleep(0.5) self.redirect('/blog/welcome') else: self.params['error'] = 'Invalid Login!' self.render('login.html', **self.params)
def get(self, extID): user = users.get_current_user() if user: userEntry = User.gql("WHERE user = :1", user).get() if not userEntry: userEntry = User() userEntry.user = user userEntry.starred = [] userEntry.starred.append(extID) userEntry.put() else: self.redirect(users.create_login_url(self.request.uri))
def get(self): uuid = self.request.get('uuid') user = api.get_user(self.request) if not user: api.write_error(self.response, 403, 'Unknown or missing user') return json = None if uuid: other = User.query(User.uuid == uuid).get() if other: json = get_user_json(other) if not json: json = get_user_json(user, public=False) api.write_message(self.response, 'success', extra={'users' : [json]})
def get(self,extID): ext = Extension.gql('WHERE extID = :1',extID).get() if not ext: path = os.path.join(os.path.dirname(__file__), 'templates/head.html') self.response.out.write(template.render(path, {'title':'Extension Not Found'})) path = os.path.join(os.path.dirname(__file__), 'templates/ext404.html') self.response.out.write(template.render(path, {})) self.response.set_status(404); else: # Add the Extension to the template vars dictionary and # set other template vars to their default values. templateVars = { 'ext':ext, 'userRating':None, 'starred':False, 'userIsDev':False } if ext.developer: templateVars['devname'] = ext.developer.nickname() user = users.get_current_user() if user: userEntry = User.gql('WHERE user = :1',user).get() if userEntry: if extID in userEntry.starred: templateVars['starred'] = True userRating = Rating.gql('WHERE user = :1 AND extID = :2',user,extID).get() if userRating: templateVars['userRating'] = userRating.value else: templateVars['userRating'] = 0 # Every user's default vote is zero if user == ext.developer: templateVars['userIsDev'] = True path = os.path.join(os.path.dirname(__file__), 'templates/head.html') self.response.out.write(template.render(path, {'title':ext.title,'stylesheet':'gallery'})) path = os.path.join(os.path.dirname(__file__), 'templates/info.html') self.response.out.write(template.render(path, templateVars)) path = os.path.join(os.path.dirname(__file__), 'templates/foot.html') self.response.out.write(template.render(path, {}))
def post(self): """Add all of the selected users into the datastore.""" manual = self.request.get('manual') users_to_add = [] if manual: user_name = self.request.get('user_name') user_email = self.request.get('user_email') decoded_user = {} decoded_user['name'] = {} decoded_user['name']['fullName'] = user_name decoded_user['primaryEmail'] = user_email users_to_add.append(decoded_user) else: users = self.request.get_all('selected_user') for user in users: decoded_user = literal_eval(user) users_to_add.append(decoded_user) User.InsertUsers(users_to_add) self.redirect(PATHS['user_page_path'])
def get(self, extID): user = users.get_current_user() if user: userEntry = User.gql("WHERE user = :1", user).get() if not userEntry: userEntry = User() userEntry.user = user userEntry.starred = [] if extID in userEntry.starred: userEntry.starred.remove(extID) userEntry.put() self.redirect("/gallery/info/" + extID) else: self.redirect(users.create_login_url(self.request.uri))
def post(self): data = json.loads(self.request.body) recipe = Recipe.get_by_id(int( data['recipeID'] )) # check if user has already saved this recipe dbUser = User.query().filter(User.user_id == UserId()).fetch(1) user = dbUser[0] matches = 0 for savedRecipe in user.savedRecipes : if savedRecipe == data['recipeID'] : matches += 1 break; if matches == 0 : if recipe.thumbsUp == None : recipe.thumbsUp = 1 else : recipe.thumbsUp += 1 recipe.put() user.savedRecipes.append( data['recipeID'] ); user.put() self.response.write(json.dumps(({'recipe_thumbsUp': recipe.thumbsUp, 'net_thumbs': recipe.thumbsUp})))
def get(self, author_id): # check if there is user that corresponds with the ID author = User.query().filter(User.user_id == author_id).fetch() if author : # check if the user has any recipes recipes = Recipe.query().filter(Recipe.author == author_id).fetch() if recipes : template_values = { 'header': GetHeader('recipe'), 'recipes' : recipes, 'author' : author[0].name ,'author_bio' : author[0].bio , 'title' : 'Recipes by ' + author[0].name} if author[0].pic : template_values['author_pic'] = author[0].picUrl() if author[0].location : template_values['author_location'] = author[0].location else : error = "This user has not uploaded any recipes." template_values = { 'header': GetHeader('recipe'), 'title': 'Error', 'error' : error } else : error = "This user doesn't not exist." template_values = { 'header': GetHeader('recipe'), 'title': 'Error', 'error' : error } RecipesBy = jinja_environment.get_template('templates/recipes_by.html').render(template_values) self.response.write(RecipesBy)
def _MakeKeyString(): """Generate the key string in open ssh format for pushing to proxy servers. This key string includes only the public key for each user in order to grant the user access to each proxy server. Returns: key_string: A string of users with associated key. """ users = User.GetAll() key_string = '' ssh_starting_portion = 'ssh-rsa' space = ' ' endline = '\n' for user in users: if not user.is_key_revoked: user_string = (ssh_starting_portion + space + user.public_key + space + user.email + endline) key_string += user_string return key_string
def get(self): user = users.get_current_user() if user: templateVars = { "useremail": user.email(), "usernickname": user.nickname(), "signouturl": users.create_logout_url("/"), "extlist": [], } userEntry = User.gql("WHERE user = :1", user).get() if userEntry and userEntry.starred: for extID in userEntry.starred: extEntry = Extension.gql("WHERE extID = :1", extID).get() if extEntry: templateVars["extlist"].append(extEntry) path = os.path.join(os.path.dirname(__file__), "templates/head.html") self.response.out.write(template.render(path, {"title": "Your Account"})) path = os.path.join(os.path.dirname(__file__), "templates/account.html") self.response.out.write(template.render(path, templateVars)) path = os.path.join(os.path.dirname(__file__), "templates/foot.html") self.response.out.write(template.render(path, {})) else: self.redirect(users.create_login_url(self.request.uri))
def get(self): tags = self.request.get('tags') public = self.request.get('public') user = api.get_user(self.request) if not user: api.write_error(self.response, 400, 'Unknown or missing user') return if public: user = User.query(User.uuid == config.SUPER_USER_UUID).get() cards = [] if tags: tags = tags.lower().split(',') query = Card.query(Card.tags.IN(tags), ancestor=user.key).order(-Card.create_time) else: query = Card.query(ancestor=user.key).order(-Card.create_time) for card in query: cards.append(get_card_json(card)) api.write_message(self.response, 'success', extra={'cards': cards})
def get(self) : image_id = self.request.get('id') image = User.get_by_id(int(image_id)).pic self.response.headers['Content-Type'] = 'image/png' self.response.write(image)
def UserInfo() : user = users.get_current_user() name = user.nickname() userID = UserId() dbUser = User.query().filter(User.user_id == userID).fetch(1) return dbUser
if weekly_avg_sleep and not math.isnan(weekly_avg_sleep): variables['weekly_average_sleep'] = str(weekly_avg_sleep) return variables def get_card_type(card): tags = list(card.tags) if 'archived' in tags: tags.remove('archived') tags.sort() return ','.join(tags) def get_card_week(card): week = None for tag in card.tags: if tag.startswith('week:'): try: return int(tag.split(':')[1]) except: pass return week if __name__ == '__main__': user = User() user.features.append(Pair(name='DUE_DATE_MILLIS', value=sys.argv[1])) for card in get_week_based_cards(user): print get_card_json(card)
def get_user(account): return User.by_account(account)
def get(self): """Lookup the user and toggle the revoked status of keys.""" urlsafe_key = self.request.get('key') User.ToggleKeyRevoked(urlsafe_key) user = User.GetByKey(urlsafe_key) self.response.write(_RenderUserDetailsTemplate(user))
def get(self): """Find the user matching the specified key and generate a new key pair.""" urlsafe_key = self.request.get('key') User.UpdateKeyPair(urlsafe_key) user = User.GetByKey(urlsafe_key) self.response.write(_RenderUserDetailsTemplate(user))
MOCK_XSRF = MagicMock() MOCK_XSRF.XSRFProtect = NoOpDecorator sys.modules['xsrf'] = MOCK_XSRF import user FAKE_EMAIL = '*****@*****.**' FAKE_NAME = 'fake name' FAKE_PUBLIC_KEY = 'fakePublicKey' FAKE_PRIVATE_KEY = 'fakePrivateKey' FAKE_DS_KEY = 'urlEncodedKeyFromTheDatastore' FAKE_USER_KEY = ndb.Key(User, hashlib.sha256(FAKE_EMAIL).hexdigest()) FAKE_USER = User(key=FAKE_USER_KEY, email=FAKE_EMAIL, name=FAKE_NAME, public_key=FAKE_PUBLIC_KEY, private_key=FAKE_PRIVATE_KEY, is_key_revoked=False) FAKE_USER_ARRAY = [] FAKE_EMAIL_1 = u'*****@*****.**' FAKE_EMAIL_2 = u'*****@*****.**' FAKE_ADD_USER = {} FAKE_ADD_USER['primaryEmail'] = FAKE_EMAIL_1 FAKE_ADD_USER['name'] = {} FAKE_ADD_USER['name']['fullName'] = FAKE_NAME FAKE_ADD_USER['email'] = FAKE_EMAIL_1 FAKE_ADD_USER['role'] = 'MEMBER' FAKE_ADD_USER['type'] = 'USER' FAKE_USER_ARRAY.append(FAKE_ADD_USER)
def load_user_obj(self, user_name): logging.info("Trying to load user with user name - " + user_name.lower()) self.user_obj = User.query(User.name == user_name.lower()).get()
def get(self): """Output details based on the user key passed in.""" urlsafe_key = self.request.get('key') user = User.GetByKey(urlsafe_key) self.response.write(_RenderUserDetailsTemplate(user))
def put(self): uuid = self.request.get('group_uuid') name = self.request.get('name') admin_ids = self.request.get_all('admin_uuid') member_ids = self.request.get_all('member_uuid') public = self.request.get('public') if not uuid: api.write_error(self.response, 400, 'Missing required parameter, group_uuid') return user = api.get_user(self.request) if not user: api.write_error(self.response, 403, 'Unknown or missing user') return group = Group.query(Group.uuid == uuid).get() if not group: api.write_error(self.response, 404, 'Unknown or missing group') return if not user.key in group.admins: api.write_error(self.response, 403, 'User not allowed to update group') return if name: group.name = name if 'public' in self.request.params and not public == '': group.public = public.lower() in ("yes", "true", "t", "1", "on") for admin_id in admin_ids: remove_user = False if admin_id and admin_id[0] == '-': remove_user = True admin_id = admin_id[1:] admin = User.query(User.uuid == admin_id).get() if admin: if remove_user and admin.key in group.admins: if len(group.admins) > 1: group.admins.remove(admin.key) else: api.write_error(self.response, 403, 'Cannot remove last admin') return elif not admin.key in group.admins: group.admins.append(admin.key) else: logging.warn('Unknown user %s' % (admin_id)) for member_id in member_ids: remove_user = False if member_id and member_id[0] == '-': remove_user = True member_id = member_id[1:] member = User.query(User.uuid == member_id).get() if member: if remove_user and member.key in group.members: group.members.remove(member.key) elif not member.key in group.members: group.members.append(member.key) else: logging.warn('Unknown user %s' % (member_id)) group.put() if group.public: api.search.update_public_index(group) else: api.search.update_private_index(group, user.uuid) api.write_message(self.response, 'Updated group', extra={'groups' : [ get_group_json(group) ]})
class UserClass(object): def __init__(self, user_id): if user_id is None: self.user_object = User.get_by_id(user_id) else: if not isinstance(user_id, str): raise ValueError("UserID should be string") try: self.user_object = User.get_by_id(user_id) if self.user_object is None: logging.warning("User not found, creating new user") self.user_object = User(id=user_id) self.user_object.put() except Exception as e: logging.error("Something wient wrong : {}".format(e)) raise Exception self.userid = self.user_object.key.id() def set_name(self, name): if not isinstance(name, str): raise TypeError self.user_object.name = name def set_date_of_birth(self, date_obj): if not isinstance(date_obj, datetime): raise TypeError self.user_object.date_of_birth = date_obj def set_per_month_salary(self, per_month_salary): if not isinstance(per_month_salary, int): raise TypeError self.user_object.per_month_salary = per_month_salary def set_per_month_rent(self, per_month_rent): if not isinstance(per_month_rent, int): raise TypeError self.user_object.per_month_rent = per_month_rent def set_per_month_investment(self, per_month_investment): if not isinstance(per_month_investment, int): raise TypeError self.user_object.per_month_investment = per_month_investment def set_per_month_expenses(self, per_month_expenses): if not isinstance(per_month_expenses, int): raise TypeError self.user_object.per_month_expenses = per_month_expenses def set_no_of_dependents(self, no_of_dependents): if not isinstance(no_of_dependents, int): raise TypeError self.user_object.no_of_dependents = no_of_dependents def set_only_earning_member(self, only_earning_member): if not isinstance(only_earning_member, int): raise TypeError self.user_object.only_earning_member = only_earning_member def save_data(self): self.user_object.put() def update_user(self, name, dob, salary, rent, expenses, dependents, is_only_earning): self.set_name(name) self.set_date_of_birth(dob) self.set_per_month_salary(salary) self.set_per_month_rent(rent) self.set_per_month_expenses(expenses) self.set_no_of_dependents(dependents) self.set_only_earning_member(is_only_earning) self.save_data()
def post(self): email = self.request.get('email') push_token = self.request.get('token') device_type = self.request.get('type') user_uuid = self.request.get('uuid') code = self.request.get('code') if user_uuid and code: code = int(code) user = User.query(User.uuid == user_uuid).get() if not user or not user.recovery: api.write_error(self.response, 404, 'User not found') return if not user.recovery.code == code: api.write_error(self.response, 403, 'Invalid recovery code') return if (datetime.datetime.now() - user.recovery.time).seconds > (15 * 60): api.write_error(self.response, 403, 'Old recovery code') return user.auth = str(uuid.uuid4()) user.put() api.write_message(self.response, 'success', extra={'users' : [get_user_json(user, public=False)]}) return users = User.query(User.devices.data == email) if not users or users.count(limit=1) < 1: api.write_error(self.response, 404, 'User not found') return extra = {} push_token_found = False; first_user = None for user in users: if not user or not user.devices: continue if not first_user: first_user = user for device in user.devices: if not device.device_type in ['GOOGLE', 'APPLE', 'AMAZON']: continue if device.device_type == device_type and device.data == push_token: push_token_found = True if device.device_type == 'GOOGLE': user.auth = str(uuid.uuid4()) user.put() user_json = get_user_json(user, public=False) user_json['cards'] = [] api.gcm([push_token], {'user': user_json}) elif device.device_type == 'APPLE': # Until we can deliver data to iOS app directly, use email for them push_token_found = False if not push_token_found and first_user: # Is this correct to pick first user? if not first_user.recovery: first_user.recovery = Recovery() first_user.recovery.code = random.randint(1000, 9999) api.email(email, config.EMAIL_RECOVERY_SUBJECT, config.EMAIL_RECOVERY_BODY % (first_user.recovery.code)) first_user.put() extra = {'users' : [get_user_json(first_user)]} api.write_message(self.response, 'success', extra=extra)