def get(self): g_user = users.get_current_user() if not g_user: login_url = users.create_login_url('/') template = env.get_template("main.html") html = template.render(login_url=login_url, stats=statistics()) self.response.out.write(html) else: logout_url = users.create_logout_url('/') login_url = None email_hash = hashlib.md5(g_user.email()).hexdigest() user_obj = User.all().ancestor(db_parent) user_obj = user_obj.filter("user_id =", g_user.user_id()) user_obj = user_obj.get() if not user_obj: user_obj = User(user_id=g_user.user_id(), nickname=g_user.nickname(), parent=db_parent, email=g_user.email()) user_obj.put() self.redirect('/library')
def make_user(email, password, parent=None, user_id=None): if User.all().ancestor(parent).filter("email =", email).fetch(1): raise AuthExcept("email exists") if user_id is None: user_id = make_userid() salt = make_salt() encrypted_password = encrypt_password(password, salt) admin_user = User(user_id=user_id, parent=parent, email=email, password=encrypted_password, salt=salt) admin_user.put() return admin_user
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 get_base_params(self, **kwargs): g_user = users.get_current_user() if g_user: user = User.all().filter("user_id =", g_user.user_id()) user = user.get() logout_url = users.create_logout_url('/') login_url = None email_hash = hashlib.md5(user.email).hexdigest() nickname = user.nickname cred_points = user.cred admin = users.is_current_user_admin() else: logout_url = None login_url = users.create_login_url('/') email_hash = '' nickname = None cred_points = None admin = False params = dict(logout_url=logout_url, login_url=login_url, email_hash=email_hash, nickname=nickname, cred_points=cred_points, admin=admin) params.update(kwargs) return params
def statistics(): stats = { "user_count": User.all().count(), "image_count": ImageObject.all().count(), "pick_count": Picks.all().count(), "vote_count": Vote.all().count() } return stats
def get_cookie_string(email): """ Creates a cookie string to use for authenticating users. user_id|encrypted_password """ user = User.all().filter("email =", email).fetch(1)[0] name = 'user' value = str(user.user_id) + '|' + str(user.password) return '%s=%s; Path=/' % (name, value)
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 verify(userid, password, ancestor): """ Verifies that the userid and encrypted password from a cookie match the database """ try: user = User.all().ancestor(ancestor)\ .filter("user_id =", int(userid)).fetch(1)[0] verified = (user.password == password) return user except IndexError: verified = False
def signin(email, password, parent): """ Checks if a email and password are valid. Will throw a AuthExcept if they are not. """ user = User.all().ancestor(parent).filter("email =", email).fetch(1) if not user: raise AuthExcept('invalid email') user = user[0] encrypted_password = encrypt_password(password, user.salt) if not encrypted_password == user.password: raise AuthExcept('invalid password')
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 signup(email, password, parent=None): """ Checks for valid inputs then adds a user to the User database. """ exists = User.all().ancestor(parent).filter("email =", email) if (exists.fetch(1)): raise AuthExcept("Account Exists") if not EMAIL_RE.match(email): raise AuthExcept("Invalid Email") if not PASS_RE.match(password): raise AuthExcept("Invalid Password") salt = make_salt() encrypted_password = encrypt_password(password, salt) temp_id = hashlib.sha256(make_salt()).hexdigest() # Set up groups. See if the email domain exists groups = ['public'] domain = email.split('@')[1] g = Group.all().ancestor(parent).filter("name =", domain).fetch(1) if g: groups.append(domain) user = VerifyUser(email=email, password=encrypted_password, salt=salt, temp_id=temp_id, group=groups, parent=parent) user.put() print("http://modelr.io/verify_email?user_id=%s" % str(user.temp_id)) mail.send_mail(sender="Hello <*****@*****.**>", to="<%s>" % user.email, subject="Modelr email verification", body=""" Welcome to Modelr! We need to verify your email address. Click the link below to validate your account and continue to billing. http://modelr.io/verify_email?user_id=%s Cheers, Matt, Evan, and Ben """ % str(user.temp_id)) return temp_id
def post(self, user_id): user = User.all().filter("user_id =", user_id).get() image_key = self.request.get("image_key") title = cgi.escape(self.request.get("title")) description = cgi.escape(self.request.get("description")) challenge = cgi.escape(self.request.get("challenge")) pickstyle = self.request.get("pickstyle") permission = self.request.get("permission") rightsholder1 = cgi.escape(self.request.get("rightsholder1")) rightsholder2 = cgi.escape(self.request.get("rightsholder2")) # This is pretty gross if not rightsholder1: if not rightsholder2: rightsholder = user.nickname else: rightsholder = rightsholder2 else: rightsholder = rightsholder1 img_obj = ImageObject.get_by_id(int(image_key), parent=db_parent) if not ((user_id == img_obj.user_id) or (users.is_current_user_admin())): raise Exception # Don't change the pickstyle if already set. if img_obj.pickstyle: if pickstyle != img_obj.pickstyle: pickstyle = img_obj.pickstyle img_obj.width = img_obj.size[0] img_obj.height = img_obj.size[1] img_obj.title = title img_obj.description = description img_obj.challenge = challenge img_obj.pickstyle = pickstyle img_obj.permission = permission img_obj.rightsholder = rightsholder img_obj.put() self.redirect('/')
def forgot_password(email, parent): """ Sets a new password after the user forgot it. """ user = User.all().ancestor(parent).filter("email =", email).fetch(1) if not user: raise AuthExcept('invalid email') user = user[0] def generate_password(size=8, chars=(string.ascii_uppercase + string.digits)): return ''.join(random.choice(chars) for x in range(size)) new = generate_password() # send a new password email mail.send_mail(sender="Hello <*****@*****.**>", to="<%s>" % user.email, subject="Modelr password reset", body=""" Here's your new password! %s Please sign in with this new password, and then change it in your profile page. http://modelr.io/signin?redirect=settings Cheers, Matt, Evan, and Ben """ % new ) # Change it in the database user.password = encrypt_password(new, user.salt) user.put()
# ===================================================================== # Define Global Variables # ===================================================================== # Initialize the model served counter models_served = ModelServedCount.all().ancestor(ModelrRoot).get() if models_served is None: models_served = ModelServedCount(count=0, parent=ModelrRoot) models_served.put() # Put in the default rock database under the admin account. # The admin account is set up so every user can view our default # scenarios and rocks admin_user = User.all().ancestor(ModelrRoot).filter("user_id =", admin_id).get() # Create the admin account if admin_user is None: password = "******" email = "*****@*****.**" admin_user = make_user(user_id=admin_id, email=email, password=password, parent=ModelrRoot) # Create the public group. All users are automatically entitled # to part of this group. public = Group.all().ancestor(ModelrRoot).filter("name =", 'public') public = public.fetch(1) if not public:
def initialize_user(email, stripe_id, parent, tax_code, price, tax): """ Takes a verified user email from the authentication queue and adds it to the permanent database with a stripe id. :param verified_email: email of the verified user to add. :param stripe_id: The stripe customer id of the user. :param parent: The ancestor database key to use for the database. :param tax_code: The tax code for the user (province abbrieviation) """ verified_filter = VerifyUser.all()\ .ancestor(parent)\ .filter("email =", email) verified_user = verified_filter.fetch(1) if not verified_user: raise AuthExcept("verification failed") verified_user = verified_user[0] # Make new user and populate user = User(parent=parent) user.user_id = make_userid() user.email = verified_user.email user.password = verified_user.password user.salt = verified_user.salt user.group = verified_user.group user.stripe_id = stripe_id user.tax_code = tax_code for group in user.group: g = Group.all().ancestor(parent).filter("name =", group).fetch(1) g[0].allowed_users.append(user.user_id) g[0].put() user.put() # remove the temporary user from the queue verified_user.delete() # send a payment confirmation email mail.send_mail(sender="Hello <*****@*****.**>", to="<%s>" % user.email, subject="Modelr subscription confirmation", body=""" Welcome to Modelr! You are now subscribed to Modelr! Your receipt is below. To unsubscribe, please reply to this email or log in to Modelr and check your user settings. Cheers, Matt, Evan, and Ben ======================= modelr.io ======================= Monthly fee USD{0:.2f} Sales tax USD{1:.2f} Total USD{2:.2f} ======================== Modelr is a product of Agile Geoscience Ltd Nova Scotia - Canada Canada Revenue Agency reg # 840217913RT0001 ======================== """.format(price/100., tax/100., (price+tax)/100.))
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 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")