def get(self, user): group_name = self.request.get("selected_group") group = Group.all().ancestor(ModelrParent.all().get()) group = group.filter("name =", group_name).fetch(1) if (not group): self.redirect('/profile') return group = group[0] if group.admin != user.user_id: self.redirect('/profile') return users = [] for user_id in group.allowed_users: u = User.all().ancestor(ModelrParent.all().get())\ .filter("user_id =", user_id) u = u.fetch(1) if u: users.append(u[0]) params = self.get_base_params(user=user, users=users, group=group) template = env.get_template('manage_group.html') html = template.render(params) activity = "manage_group" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.response.out.write(html)
def post(self, user): if "admin" not in user.group: self.redirect('/') template = env.get_template('admin_site.html') host = self.request.get('host') if (len(host) > 0): server = Server.all().ancestor(ModelrParent.all().get()).get() server.host = self.request.get('host') server.put() html = template.render( self.get_base_params(success="Updated Host")) self.response.write(html) return email = self.request.get('email') password = self.request.get('password') verify = self.request.get('verify') if (len(email) > 0): if password != verify: template = env.get_template('admin_site.html') msg = "Password mismatch" html = template.render(email=email, error=msg) self.response.out.write(html) return else: try: make_user(email=email, password=password, parent=ModelrParent.all().get()) template = env.get_template('admin_site.html') html = template.render(success="Added User", email=email, user=user) self.response.out.write(html) return except AuthExcept as e: template = env.get_template('admin_site.html') html = template.render(error=e.msg, user=user, email=email) self.response.out.write(html) return else: template = env.get_template('admin_site.html') html = template.render() self.response.out.write(html)
def get(self, user): groups = [] for group in user.group: g = Group.all().ancestor(ModelrParent.all().get())\ .filter("name =", group) g = g.fetch(1) if g: groups.append(g[0]) template_params = self.get_base_params(user=user, groups=groups, stripe_key=stripe_public_key) if self.request.get("createfailed"): create_error = "Group name exists" template_params.update(create_error=create_error) if self.request.get("joinfailed"): join_error = "Group does not exists" template_params.update(join_error=join_error) # Get the user permission requests req = GroupRequest.all().ancestor(ModelrParent.all().get())\ .filter("user ="******"admin =", user.user_id) admin_groups = admin_groups.fetch(100) req = [] for group in admin_groups: # Check for a request g_req = GroupRequest.all().ancestor(ModelrParent.all().get()) g_req = g_req.filter("group =", group.name).fetch(100) req = req + [{'group': group.name, 'user': User.all().filter("user_id =", i.user).get()} for i in g_req] template_params.update(admin_req=req) template = env.get_template('profile.html') html = template.render(template_params) activity = "profile_view" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.response.out.write(html)
def delete(self, user): try: key = self.request.get('key') item = self.entity.get(key) if item.user != user.user_id: raise Exception # delete item and all its children deep_delete(item) activity = "removed_item" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('All OK!!') except Exception as e: print e self.error(502)
def get_base_params(self, **kwargs): ''' get the default parameters used in base_template.html ''' user = self.verify() if user: email_hash = hashlib.md5(user.email).hexdigest() else: email_hash = '' hostname = Server.all()\ .ancestor(ModelrParent.all().get()).get().host default_rock = dict(vp=0, vs=0, rho=0, vp_std=0, rho_std=0, vs_std=0, description='description', name='name', group='public') params = dict(logout=users.create_logout_url(self.request.uri), HOSTNAME=hostname, current_rock=default_rock, email_hash=email_hash) params.update(kwargs) return params
def post(self, user): # Output for successful post reception self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('All OK!!') name = self.request.get('name') group = self.request.get('group') logging.info(('name', name)) data = self.request.get('json') logging.info(data) scenarios = Scenario.all() scenarios.ancestor(user) scenarios.filter("user ="******"name =", name) scenarios = scenarios.fetch(1) # Rewrite if the name exists, create new one if it doesn't if scenarios: scenario = scenarios[0] else: scenario = Scenario(parent=user) scenario.user = user.user_id scenario.name = name scenario.group = group # Save in Db scenario.data = data.encode() scenario.put() activity = "modified_scenario" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put()
def get(self, user): activity = "signout" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.response.headers.add_header('Set-Cookie', 'user=""; Path=/') self.redirect('/')
def post(self, user): group_name = self.request.get("group") group = Group.all().ancestor(ModelrParent.all().get()) group = group.filter("name =", group_name).fetch(1)[0] # remove a user rm_user = self.request.get("user") if rm_user: u = User.all().ancestor(ModelrParent.all().get()) u = u.filter("user_id =", int(rm_user)).fetch(1) if u and group_name in u[0].group: u[0].group.remove(group_name) u[0].put() group.allowed_users.remove(int(rm_user)) group.put() self.redirect('/manage_group?selected_group=%s' % group.name) activity = "removed_user" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() return # abolish a group if (self.request.get("abolish") == "abolish"): for uid in group.allowed_users: u = User.all().ancestor(ModelrParent.all().get()) u = u.filter("user_id =", uid).fetch(1) if u and group.name in u[0].group: u[0].group.remove(group.name) u[0].put() group.delete() activity = "abolished_group" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.redirect('/profile') return
def get(self): self.response.headers['Content-Type'] = 'application/json' # Get the user but don't redirect. Anyone can play with public # scenarios. user = self.verify() name = self.request.get('name') if user: scenarios = Scenario.all() scenarios.ancestor(user) scenarios.filter("user ="******"name =", name) scenarios = scenarios.fetch(1) else: scenarios = [] # Get Evan's default scenarios (created with the admin) scen = Scenario.all()\ .ancestor(ModelrParent.all().get())\ .filter("user_id =", admin_id) scen = Scenario.all().filter("name =", name).fetch(100) if scen: scenarios += scen if scenarios: logging.info(scenarios[0]) logging.info(scenarios[0].data) scenario = scenarios[0] self.response.out.write(scenario.data) else: self.response.out.write('null') activity = "fetched_scenario" if user: ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() return
def get(self): user = self.verify() template_params = self.get_base_params(user=user) template = env.get_template('privacy.html') html = template.render(template_params) activity = "privacy" if user: ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.response.out.write(html)
def post(self, user): # Adds a rock to the database, will throw an error # if the rock name already exists try: name = self.request.get("name") rocks = get_items_by_name_and_user(self.entity, name, user) # Rewrite if the rock exists if rocks: # write out error message raise else: rock = Rock(parent=user) rock.user = user.user_id # Populate the object rock.vp = float(self.request.get('vp')) rock.vs = float(self.request.get('vs')) rock.rho = float(self.request.get('rho')) rock.vp_std = float(self.request.get('vp_std')) rock.vs_std = float(self.request.get('vs_std')) rock.rho_std = float(self.request.get('rho_std')) rock.porosity = float(self.request.get('porosity')) rock.vclay = float(self.request.get('vclay')) rock.description = self.request.get('description') rock.name = self.request.get('name') rock.group = self.request.get('group') fluid_key = self.request.get("rock-fluid") if fluid_key != "None": rock.fluid_key = Fluid.get(str(fluid_key)).key() # Save in the database rock.put() activity = "added_rock" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('All OK!!') except Exception as e: # send error print e self.error(502)
def post(self): email = self.request.get('email') template = env.get_template('message.html') try: forgot_password(email, parent=ModelrParent.all().get()) msg = ("Please check your inbox and spam folder " + "for our message. Then click on the link " + "in the email.") html = template.render(success=msg) self.response.out.write(html) except AuthExcept as e: html = template.render(error=e.msg) self.response.out.write(html)
def verify(self): """ Verify that the current user is a legimate user. Returns the user object from the database if true, otherwise returns None. """ cookie = self.request.cookies.get('user') if cookie is None: return try: user, password = cookie.split('|') except ValueError: return return verify(user, password, ModelrParent.all().get())
def get(self, subpage): if subpage: page = subpage else: page = 'help' page += '.html' user = self.verify() template_params = self.get_base_params(user=user) template = env.get_template(page) html = template.render(template_params) activity = "help" if user: ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.response.out.write(html)
def delete(self, user): name = self.request.get('name') scenarios = Scenario.all() scenarios.ancestor(user) scenarios.filter("user ="******"name =", name) scenarios = scenarios.fetch(100) for scenario in scenarios: scenario.delete() activity = "removed_scenario" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() # Output for successful post reception self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('All OK!!')
def post(self, user): try: name = self.request.get("name") fluids = get_items_by_name_and_user(self.entity, name, user) # Rewrite if the rock exists if fluids: raise Exception else: fluid = Fluid(parent=user) fluid.user = user.user_id fluid.rho_w = float(self.request.get('rho_w')) fluid.rho_hc = float(self.request.get('rho_hc')) fluid.kw = float(self.request.get('kw')) fluid.khc = float(self.request.get('khc')) fluid.sw = float(self.request.get('sw')) fluid.name = name fluid.description = self.request.get("description") fluid.group = self.request.get("group") fluid.put() activity = "added_fluid" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() except Exception as e: # Handle error print e self.error(502) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('All OK!!')
def post(self): email = self.request.get('email') password = self.request.get('password') redirect = self.request.get('redirect').encode('utf-8') try: signin(email, password, ModelrParent.all().get()) cookie = get_cookie_string(email) self.response.headers.add_header('Set-Cookie', cookie) if redirect: self.redirect(redirect) else: self.redirect('/') except AuthExcept as e: template = env.get_template('signin.html') msg = e.msg html = template.render(email=email, error=msg) self.response.out.write(html)
backoff_factor=2, max_retry_period=15) # All requests to GCS using the GCS client within current GAE request # and current thread will use this retry params as default. If a # default is not set via this mechanism, the library's built-in # default will be used. Any GCS client function can also be given a # more specific retry params that overrides the default. # Note: the built-in default is good enough for most cases. We # override retry_params here only for demo purposes. gcs.set_default_retry_params(my_default_retry_params) # Ancestor dB for all of modelr. Allows for strongly consistent # database queries. (all entities update together, so every page is # is sync) ModelrRoot = ModelrParent.all().get() if ModelrRoot is None: ModelrRoot = ModelrParent() ModelrRoot.put() # For the plot server server = Server.all().ancestor(ModelrRoot).get() if server is None: server = Server(parent=ModelrRoot) if LOCAL is True: server.live_host = "http://127.0.0.1:8081" server.dev_host = "http://127.0.0.1:8081" logging.debug("[*] Debug info activated") stripe.verify_ssl_certs = False else:
def post(self, user): err_string = [] # Join a group join_group = self.request.get("join_group") if join_group: activity = "joined_group" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() try: group = Group.all().ancestor(ModelrParent.all().get()) group = group.filter("name =", join_group).fetch(1)[0] if user.user_id in group.allowed_users: if group.name not in user.group: user.group.append(group.name) user.put() else: GroupRequest(user=user.user_id, group=group.name, parent=ModelrParent.all().get()).put() except IndexError: err_string.append("joinfailed=1") # Leave a group group = self.request.get("selected_group") if group in user.group: activity = "left_group" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() user.group.remove(group) user.put() # Create a group group = self.request.get("create_group") if group: if not Group.all().ancestor(ModelrParent.all().get())\ .filter("name =", group).fetch(1): Group(name=group, admin=user.user_id, allowed_users=[user.user_id], parent=ModelrParent.all().get()).put() user.group.append(group) user.put() activity = "created_group" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() else: err_string.append("createfailed=1") # Handle a group request request_user = self.request.get("request_user") if request_user: user_id = int(request_user) group = self.request.get("request_group") if self.request.get("allow") == "True": u = User.all().ancestor(ModelrParent.all().get()) u = u.filter("user_id =", user_id).fetch(1) if u: u[0].group.append(group) g = Group.all().ancestor(ModelrParent.all().get()) g = g.filter("name =", group).fetch(1)[0] g.allowed_users.append(u[0].user_id) u[0].put() g.put() activity = "request_response" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() g_req = GroupRequest.all().ancestor(ModelrParent.all().get()) g_req = g_req.filter("user ="******"group =", group).fetch(100) for g in g_req: g.delete() err_string = '&'.join(err_string) if err_string else '' self.redirect('/profile?' + err_string)
def get(self, user): template_params = self.get_base_params(user=user) # Get the list of issues from GitHub. # First, set up the request. gh_api_key = 'token 89c9d30cddd95358b1465d1dacb1b64597b42f89' url = 'https://api.github.com/repos/kwinkunks/modelr_app/issues' params = {'labels': 'wishlist', 'state': 'open'} query = urllib.urlencode(params) full_url = '{0}?{1}'.format(url, query) # Now make the request. req = urllib2.Request(full_url) req.add_header('Authorization', gh_api_key) try: resp = urllib2.urlopen(req) raw_json = resp.read() git_data = json.loads(raw_json) except: err_msg = ('Failed to retrieve issues from GitHub. ' + 'Please check back later.') git_data = {} else: err_msg = '' for issue in git_data: # Get the user's opinion. status = None if user: user_issues = Issue.all().ancestor(user) user_issue = user_issues.filter("issue_id =", issue["id"]).get() if user_issue: status = user_issue.vote else: Issue(parent=user, issue_id=issue["id"]).put() up, down = 0, 0 if status == 1: up = 'true' if status == -1: down = 'true' issue.update(status=status, up=up, down=down) # Get the count. We have to read the database twice. down_votes = Issue.all().ancestor(ModelrParent.all().get())\ .filter("issue_id =", issue["id"])\ .filter("vote =", -1).count() up_votes = Issue.all().ancestor(ModelrParent.all().get())\ .filter("issue_id =", issue["id"])\ .filter("vote =", 1).count() count = up_votes - down_votes issue.update(up_votes=up_votes, down_votes=down_votes, count=count) # Write out the results. template_params.update(issues=git_data, error=err_msg ) template = env.get_template('feedback.html') html = template.render(template_params) self.response.out.write(html)
def post(self): event = json.loads(self.request.body) # Get the event id and retrieve it from Stripe # anybody can post, doing it this way is more secure # event_id = event_json["id"] # event = stripe.Event.retrieve(event_id) if event["type"] == "invoice.payment_succeeded": # For testing, change it to a known user in stripe # and use the webhooks testings # event["data"]["object"]["customer"] = \ # "cus_3ZL6yHJqE8DfTx" # event["data"]["object"]["total"] = price stripe_id = event["data"]["object"]["customer"] amount = PRICE event_id = event["data"]["object"]["id"] user = User.all().ancestor(ModelrParent.all().get()) user = user.filter("stripe_id =", stripe_id).fetch(1) # Serious issue here, we need to deal with this in a # a clever way if not user: message = ("Failed to find modelr user for stripe " + "user %s, but was invoiced by stripe " % (stripe_id)) send_message(subject="Non-existent user invoiced", message=message) self.response.write("ALL OK") return tax = tax_dict.get(user[0].tax_code, None) if not tax: self.response.write("ALL OK") return # Tax them up stripe.InvoiceItem.create(customer=stripe_id, amount=int(amount * tax), currency="usd", description="Canadian Taxes") self.response.write("ALL OK") elif (event["type"] == 'customer.subscription.deleted'): # for stripe self.response.write("ALL OK") stripe_id = event["data"]["object"]["customer"] user = User.all().ancestor(ModelrParent.all().get()) user = user.filter("stripe_id =", stripe_id).get() # This should never ever happen if not user: message = ("Failed to find modelr user for stripe " + "user %s, but was invoiced by stripe " % (stripe_id)) send_message(subject="Non-existent user canceled", message=message) return user.delete() self.response.write("ALL OK") elif (event["type"] == 'customer.subscription.created'): message = str(event) send_message(subject=event["type"], message=message) self.response.write("All OK") # Send an email otherwise. We can trim this down to ones we # actually care about. else: # Too many hooks, too much noise. commented out #message = str(event) #send_message(subject=event["type"], # message=message) self.response.write("ALL OK")
def get(self, user): template_params = self.get_base_params(user=user) self.response.headers['Content-Type'] = 'text/html' # Get all the rocks rocks = Rock.all() rocks.ancestor(user) rocks.filter("user ="******"-date") default_rocks = Rock.all() default_rocks.filter("user ="******"group =", name).fetch(100)} rock_groups.append(dic) # Get all the fluids fluids = Fluid.all() fluids.ancestor(user) fluids.filter("user ="******"-date") default_fluids = Fluid.all() default_fluids.filter("user ="******"group =", name).fetch(100)} fluid_groups.append(dic) # Get all the user scenarios scenarios = Scenario.all() if not user.user_id == admin_id: scenarios.ancestor(user) else: scenarios.ancestor(ModelrParent.all().get()) scenarios.filter("user ="******"-date") for s in scenarios.fetch(100): logging.info((s.name, s)) if user.user_id != admin_id: default_image_models = ImageModel.all()\ .filter("user ="******"user ="******"image": images.get_serving_url(i.image, size=200, crop=False, secure_url=True), "image_key": str(i.key()), "editable": False, "models": EarthModel.all().ancestor(i) .filter("user ="******"image": images.get_serving_url(i.image, size=200, crop=False, secure_url=True), "image_key": str(i.key()), "editable": True, "models": EarthModel.all().ancestor(i) .filter("user ="******"selected_rock"): rock_id = self.request.get("selected_rock") current_rock = Rock.get_by_id(int(rock_id), parent=user) template_params['current_rock'] = current_rock else: current_rock = Rock() current_rock.name = "name" current_rock.description = "description" current_rock.vp = 3000.0 current_rock.vs = 1500.0 current_rock.rho = 2500.0 current_rock.vp_std = 50.0 current_rock.vs_std = 50.0 current_rock.rho_std = 50.0 template_params['current_rock'] = current_rock # Check if a fluid is being edited if self.request.get("selected_fluid"): fluid_id = self.request.get("selected_fluid") current_fluid = Fluid.get_by_id(int(fluid_id), parent=user) template_params['current_fluid'] = current_fluid else: current_fluid = Fluid() current_fluid.name = "name" current_fluid.description = "description" current_fluid.vp = 1500.0 current_fluid.K = 200.0 template_params['current_fluid'] = current_fluid template = env.get_template('dashboard.html') html = template.render(template_params) activity = "dashboard" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.response.out.write(html)
def post(self): """ Adds the user to the stripe customer list """ email = self.request.get('stripeEmail') price = PRICE # set at head of this file # Secret API key for Canada Post postal lookup cp_prod = "3a04462597330c85:46c19862981c734ff8f7b2" # cp_dev = "09b48e3a40e710ed:bb6f209fdecff9af3ec10d" cp_key = base64.b64encode(cp_prod) # Get the credit card details submitted by the form token = self.request.get('stripeToken') # Create the customer account try: customer = stripe.Customer\ .create(card=token, email=email, description="New Modelr customer") except: # The card has been declined # Let the user know and DON'T UPGRADE USER self.redirect('/signin?verified=false') return # Check the country to see if we need to charge tax country = self.request.get('stripeBillingAddressCountry') if country == "Canada": # Get postal code for canada post request postal_code = self.request.get('stripeBillingAddressZip')\ .replace(" ", "") # Hook up to the web api params = urllib.urlencode({"d2po": "True", "postalCode": postal_code, "maximum": 1}) cp_url = ("https://soa-gw.canadapost.ca/rs/postoffice?%s" % params) headers = {"Accept": "application/vnd.cpc.postoffice+xml", "Authorization": "Basic " + cp_key} try: req = urllib2.Request(cp_url, headers=headers) result = urllib2.urlopen(req).read() xml_root = ElementTree.fromstring(result) # This is super hacky, but the only way I could get the # XML out province = [] for i in xml_root.iter('{http://www.canadapost.ca/ws/' + 'postoffice}province'): province.append(i.text) tax_code = province[0] tax = tax_dict.get(tax_code) * price # Add the tax to the invoice stripe.InvoiceItem.create(customer=customer.id, amount=int(tax), currency="usd", description="Canadian Taxes") except: send_message(subject="taxation failed for %s" % customer.id) tax = 0 else: tax_code = country tax = 0 # Create the charge on Stripe's servers - # this will charge the user's card try: customer.subscriptions.create(plan="Monthly") except: # The card has been declined # Let the user know and DON'T UPGRADE USER self.redirect('/signin?verified=false') return # get the temp user from the database try: initialize_user(email, customer.id, ModelrParent.all().get(), tax_code, price, tax) except: send_message(subject="Registration Failed", message=("Failed to register user %s to " + "Modelr but was billed by Stripe. " + "Customer ID: %s") % (email, customer.id)) self.redirect('/signin?verified=false') raise self.redirect('/signin?verified=true')
def get(self): # Check for a user, but allow guests as well user = self.verify() self.response.headers['Content-Type'] = 'text/html' self.response.headers['Access-Control-Allow-Origin'] = '*' hdrs = 'X-Request, X-Requested-With' self.response.headers['Access-Control-Allow-Headers'] = hdrs # Get the default rocks default_rocks = Rock.all().order('name') default_rocks.filter("user ="******"group =", group) group_rocks.append({"name": group.capitalize(), "rocks": g_rocks.fetch(100)}) # Get the users scenarios scenarios = \ Scenario.all().ancestor(user)\ .filter("user ="******"user ="******"viewed_scenario" ActivityLog(user_id=user.user_id, activity=activity, parent=ModelrParent.all().get()).put() self.response.out.write(html)