Example #1
0
class BaseTest(unittest.TestCase):
  def setUp(self):
    # Set up testing for application.
    self.test_app = webtest.TestApp(billing.app)

    # Set up datastore for testing.
    self.testbed = testbed.Testbed()
    self.testbed.activate()
    self.testbed.init_datastore_v3_stub()
    self.testbed.init_user_stub()

    # Make some testing plans.
    self.test_plan = plans.Plan("test", 0, 150, "This is a test plan.")
    self.test_plan_legacy = plans.Plan("test_legacy", 1, 100,
                                       "This is a test plan.",
                                       legacy=self.test_plan)

    # Make a test user.
    self.user = Membership(email="*****@*****.**",
                           first_name="Testy", last_name="Testerson",
                           username="******",
                           spreedly_token="notatoken", plan="test")
    self.user.put()

    # Simulate the user login.
    self.testbed.setup_env(user_email=self.user.email, user_is_admin="0",
                           overwrite=True)

  def tearDown(self):
    self.testbed.deactivate()
Example #2
0
  def post(self):
    if Config().is_dev:
      # Only allow this if it's the dev server.
      entry = self.request.body
      logging.debug("Got new entry: " + entry)
      entry = json.loads(entry)
      # Change formatted date back into datetime.
      for key in entry.keys():
        if type(getattr(Membership, key)) == db.DateTimeProperty:
          if not entry[key]:
            # It could be None as well.
            continue
          entry[key] = pickle.loads(str(entry[key]))
      # entry should have everything nicely in a dict...
      member = Membership(**entry)

      # Is this an update or a new model?
      match = Membership.all().filter("email =", member.email).get()
      if match:
        # Replace the old one.
        logging.debug("Found entry with same username. Replacing...")
        db.delete(match)

      member.put()
      logging.debug("Put entry in datastore.")
Example #3
0
    def post(self):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url("/key"))
            return
        account = Membership.all().filter("username ="******"@")[0]).get()
        if not account or not account.spreedly_token or account.status != "active":
            message = "Error #1982, which should never happen."
            internal = True
            self.response.out.write(self.render("templates/error.html", locals()))
            return
        is_park = self.request.get("ispark")
        if is_park == "True":  # checks if user input is a parking pass number or an rfid number
            pass_to_add = self.request.get("parking_pass")
            try:  # tests if there are only numbers in the parking pass
                float(pass_to_add)
            except ValueError:
                message = '<p>A Parking Pass may only contain numbers.</p><a href="/key">Try Again</a>'
                internal = False
                self.response.out.write(self.render("templates/error.html", locals()))
                return
            account.parking_pass = pass_to_add

            logging.debug("Setting parking pass for %s to %s." % (account.full_name(), account.parking_pass))

            db.put(account)
            self.response.out.write(self.render("templates/pass_ok.html", locals()))  # outputs the parking number
        else:
            rfid_tag = self.request.get("rfid_tag").strip()
            description = self.request.get("description").strip()
            if rfid_tag.isdigit():
                if Membership.all().filter("rfid_tag =", rfid_tag).get():
                    message = "<p>That RFID tag is in use by someone else.</p>"
                    internal = False
                    self.response.out.write(self.render("templates/error.html", locals()))
                    return
                if not description:
                    message = "<p>Please enter a reason why you are associating a replacement RFID key.  Please hit BACK and try again.</p>"
                    internal = False
                    self.response.out.write(self.render("templates/error.html", locals()))
                    return
                account.rfid_tag = rfid_tag

                logging.debug("Setting RFID for %s to %s." % (account.full_name(), account.rfid_tag))

                account.put()
                bc = BadgeChange(rfid_tag=rfid_tag, username=account.username, description=description)
                bc.put()
                self.response.out.write(self.render("templates/key_ok.html", locals()))
                return
            else:
                message = "<p>That RFID ID seemed invalid. Hit back and try again.</p>"
                internal = False
                self.response.out.write(self.render("templates/error.html", locals()))
                return
Example #4
0
class MembershipTest(unittest.TestCase):

    def setUp(self):
        """Setup method to instance an object of Membership class """
        code = 9
        name = "Gold"
        discount = 10
        self.membership = Membership(code, name, discount)
        self.test_membership = Membership(5, "Platinum", 5)
        
    def test_create_membership(self):
        """Test if an instance is created with the required data"""
        self.assertIsInstance(self.test_membership, Membership)
        
    def test_set_code_of_membership(self):
        """Test to update the membership code"""
        other_code = 10
        self.test_membership.set_code(other_code)
        self.assertEqual(other_code, self.test_membership.get_code())
        
    def test_set_name_of_membership(self):
        """ Test to update the membership name"""
        other_name = "Platinum"
        self.test_membership.set_name(other_name)
        self.assertEqual(other_name, self.test_membership.get_name())
        
    def test_set_discont_of_membership(self):
        """ Test to update the membership discount"""
        other_discount = 11
        self.test_membership.set_discount(other_discount)
        self.assertEqual(other_discount, self.test_membership.get_discount())
Example #5
0
  def test_discount(self):
    # A unique number on all the giftcards.
    serial = "1678"
    # A "correct" hash, based on what the actual code does.
    correct_hash = hashlib.sha1(serial + self.code).hexdigest()
    correct_hash = re.sub("[a-f]", "", correct_hash)[:8]
    gift_code = "1337" + serial + correct_hash
    print "Using test gift code: %s" % (gift_code)

    # Now try using this code.
    user = Membership.get_by_hash(self.user_hash)
    user.referrer = gift_code
    user.put()

    response = self.test_app.post("/account/" + self.user_hash,
                                  self._TEST_PARAMS)
    self.assertEqual(302, response.status_int)

    # We should have a record of the used code.
    codes = main.UsedCode.all().run()
    for code in codes:
      # We should only have one code in there.
      self.assertEqual(gift_code, code.code)
      self.assertEqual("*****@*****.**", code.email)
      self.assertEqual("OK", code.extra)

    user = Membership.get_by_hash(self.user_hash)
    user.username = None
    user.put()

    # Try to use the same code again.
    response = self.test_app.post("/account/" + self.user_hash,
                                  self._TEST_PARAMS, expect_errors=True)
    self.assertEqual(422, response.status_int)
    self.assertIn("already been used", response.body)

    # Now we should have individual records of the same code being used twice.
    codes = main.UsedCode.all().run()
    # Turn the iterator into a list.
    codes = [code for code in codes]

    self.assertEqual(gift_code, codes[0].code)
    self.assertEqual(gift_code, codes[1].code)
    self.assertEqual("*****@*****.**", codes[0].email)
    self.assertEqual("*****@*****.**", codes[1].email)
    if codes[0].extra == "OK":
      # The other one should be the duplicate.
      self.assertEqual("2nd+ attempt", codes[1].extra)
    elif codes[0].extra == "2nd+ attempt":
      # The other one should be the good one.
      self.assertEqual("OK", codes[1].extra)
    else:
      fail("Got unexpected extra '%s'." % (codes[0].extra))
Example #6
0
  def test_failure_if_account(self):
    existing_user = Membership(first_name=self._TEST_PARAMS["first_name"],
                               last_name=self._TEST_PARAMS["last_name"],
                               email=self._TEST_PARAMS["email"],
                               spreedly_token=None,
                               username="******",
                               password="******")
    existing_user.put()

    response = self.test_app.post("/", self._TEST_PARAMS, expect_errors=True)
    self.assertEqual(422, response.status_int)

    self.assertIn("payment", response.body)
Example #7
0
  def setUp(self):
    super(CreateUserTaskTest, self).setUp()

    # Add a user to the datastore.
    user = Membership(first_name="Testy", last_name="Testerson",
                      email="*****@*****.**", hash="notahash",
                      spreedly_token="notatoken", username="******",
                      password="******")
    user.put()

    self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME)
    self.user_hash = user.hash
    self.params = {"hash": self.user_hash, "username": "******",
                   "password": "******"}
Example #8
0
    def post(self):
        subscriber_ids = self.request.get("subscriber_ids").split(",")
        for id in subscriber_ids:
            logging.debug("Updating subscriber with id %s." % id)
            subscriber_api.update_subscriber(Membership.get_by_id(int(id)))

        self.response.out.write("ok")
Example #9
0
 def get(self):
   countdown = 0
   for membership in Membership.all().filter("status =", None):
     if (datetime.datetime.now().date() - membership.created.date()).days > 1:
       countdown += 90
       self.response.out.write("bye %s " % (membership.email))
       taskqueue.add(url="/tasks/clean_row", params={"user": membership.key().id()}, countdown=countdown)
Example #10
0
  def get(self):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return

    member = Membership.get_by_email(user.email())
    if not member:
      # User is not (yet) a member.
      self.redirect("/")
      return
    else:
      # Open billing information.
      url = member.spreedly_url()
      plan = Plan.get_by_name(member.plan)
      if plan.legacy:
        # Show the legacy plan warning.
        current = plan.get_legacy_pair()
        self.response.out.write(self.render(
            "templates/billing_popup.html",
            url=url, legacy=plan, current=current))
        return
      else:
        self.redirect(url)
        return
Example #11
0
 def post(self):
     countdown = 0
     for membership in Membership.all().filter('status =', None):
         if (datetime.now().date() - membership.created.date()).days > 1:
             countdown += 90
             self.response.out.write("bye "+membership.email+ " ")
             taskqueue.add(url='/tasks/clean_row', params={'user': membership.key().id()}, countdown=countdown)
Example #12
0
 def post(self):
     user = Membership.get_by_id(int(self.request.get("user")))
     try:
       mail.send_mail(sender=Config().EMAIL_FROM,
           to=user.email,
           subject="Hi again -- from Hacker Dojo!",
           body="Hi %s,"
           "\nOur fancy membership system noted that you started filling"
           " out the Membership Signup form, but didn't complete it."
           "\nWell -- We'd love to have you as a member!"
           "\nHacker Dojo has grown by leaps and bounds in recent years."
           " Give us a try?"
           "\nIf you would like to become a member of Hacker Dojo, just"
           " complete the signup process at http://signup.hackerdojo.com"
           "\nIf you don't want to sign up -- please give us anonymous"
           " feedback so we know how we can do better!  URL:"
           " http://bit.ly/jJAGYM"
           "\nCheers!\nHacker Dojo"
           "\n\nPS: Please ignore this e-mail if you already signed up --"
           " you might have started signing up twice or something :)"
           " PPS: This is an automated e-mail and we're now deleting your"
           " e-mail address from the signup application." % (user.full_name)
       )
     except:
       noop = True
     user.delete()
Example #13
0
    def post(self, ids=None):
        subscriber_ids = self.request.get('subscriber_ids').split(',')
        c = Config()
        s = spreedly.Spreedly(c.SPREEDLY_ACCOUNT, token=c.SPREEDLY_APIKEY)
        for id in subscriber_ids:
            subscriber = s.subscriber_details(sub_id=int(id))
            logging.debug("customer_id: "+ subscriber['customer-id'])
            member = Membership.get_by_id(int(subscriber['customer-id']))
            if member:
                if member.status == 'paypal':
                    mail.send_mail(sender=EMAIL_FROM,
                        to=PAYPAL_EMAIL,
                        subject="Please cancel PayPal subscription for %s" % member.full_name(),
                        body=member.email)
                member.status = 'active' if subscriber['active'] == 'true' else 'suspended'
                if member.status == 'active' and not member.username:
                    taskqueue.add(url='/tasks/create_user', method='POST', params={'hash': member.hash}, countdown=3)
                if member.status == 'active' and member.unsubscribe_reason:
                    member.unsubscribe_reason = None
                member.spreedly_token = subscriber['token']
                member.plan = subscriber['feature-level'] or member.plan
                if not subscriber['email']:
                  subscriber['email'] = "*****@*****.**"
                member.email = subscriber['email']                
                member.put()
                # TODO: After a few months (now() = 06.13.2011), only suspend/restore if status CHANGED
                # As of right now, we can't trust previous status, so lets take action on each call to /update
                if member.status == 'active' and member.username:
                    logging.info("Restoring User: "******"Suspending User: "******"ok")
Example #14
0
 def setUp(self):
     """Setup method to instance an object of Membership class """
     code = 9
     name = "Gold"
     discount = 10
     self.membership = Membership(code, name, discount)
     self.test_membership = Membership(5, "Platinum", 5)
Example #15
0
  def test_create_user(self):
    response = self.test_app.post("/tasks/create_user", self.params)
    self.assertEqual(200, response.status_int)

    # Check that it's sending the right parameters to the domain app.
    self.assertIn("username=testy.testerson", response.body)
    self.assertIn("password=notasecret", response.body)
    self.assertIn("first_name=Testy", response.body)
    self.assertIn("last_name=Testerson", response.body)

    user = Membership.get_by_hash(self.user_hash)
    # Check that the user ended up with a username.
    self.assertEqual("testy.testerson", user.username)
    # Check that domain_user got set.
    self.assertTrue(user.domain_user)
    # Check that the password got cleared.
    self.assertEqual(None, user.password)

    # Check that it sent the right email.
    messages = self.mail_stub.get_sent_messages(to="*****@*****.**")
    self.assertEqual(1, len(messages))

    # It should give the user this data.
    body = str(messages[0].body)
    self.assertIn(user.username, body)
Example #16
0
    def post(self):
        user_id = int(self.request.get("user"))
        logging.debug("Getting member with id: %d" % (user_id))
        user = Membership.get_by_id(int(self.request.get("user")))
        if not user:
          logging.error("Bad ID for member.")
          self.abort(422)

        logging.info("Sending email to %s %s." % \
                     (user.first_name, user.last_name))
        subject = "Hacker Dojo Membership: ACTION REQUIRED"

        first_name = user.first_name
        subscribe_url = user.subscribe_url()
        unsubscribe_url = user.unsubscribe_url()
        body = self.render("templates/areyoustillthere.txt", locals())

        to = "%s <%s>" % (user.full_name(), user.email)
        bcc = "%s <%s>" % ("Billing System", "*****@*****.**")
        if user.username:
            cc="%s <*****@*****.**>" % (user.full_name(), user.username),
            mail.send_mail(sender=Config().EMAIL_FROM_AYST, to=to,
                           subject=subject, body=body, bcc=bcc, cc=cc)
        else:
            mail.send_mail(sender=Config().EMAIL_FROM_AYST, to=to,
                           subject=subject, body=body, bcc=bcc)
Example #17
0
 def post(self):
     countdown = 0
     for membership in Membership.all().filter('status =', "suspended"):
       if not membership.unsubscribe_reason and membership.spreedly_token and "Deleted" not in membership.last_name and membership.extra_dnd != True:
         countdown += 1200 # One e-mail every 20 min = 72 e-mails a day (100 is free appengine limit)
         self.response.out.write("Are you still there "+membership.email+ "?<br/>")
         taskqueue.add(url='/tasks/areyoustillthere_mail', params={'user': membership.key().id()}, countdown=countdown)
Example #18
0
  def test_user_suspending(self):
    user = Membership.get_by_email("*****@*****.**")
    # The next one should suspend us.
    user.signins = Config().LITE_VISITS - 1
    user.put()

    params = {"email": "*****@*****.**"}
    response = self.test_app.post("/api/v1/signin", params)
    result = json.loads(response.body)

    self.assertEqual(200, response.status_int)
    self.assertEqual(0, result["visits_remaining"])

    user = Membership.get_by_email("*****@*****.**")
    self.assertEqual(Config().LITE_VISITS, user.signins)
    self.assertEqual("no_visits", user.status)
Example #19
0
 def post(self): 
     user = Membership.get_by_id(int(self.request.get('user')))
     subject = "What's your twitter handle?"
     base = self.request.host
     body = render('templates/twittermail.txt', locals())
     to = "%s <*****@*****.**>" % (user.full_name(), user.username)
     bcc = "%s <%s>" % ("Robot", "*****@*****.**")
     mail.send_mail(sender=EMAIL_FROM_AYST, to=to, subject=subject, body=body, bcc=bcc, html=body)
Example #20
0
  def test_user_suspending(self):
    user = Membership.get_by_email("*****@*****.**")
    # The next one should suspend us.
    user.signins = 9
    user.rfid_tag = "1337"
    user.put()

    params = {"id": "1337"}
    response = self.test_app.post("/api/v1/rfid", params)
    result = json.loads(response.body)

    self.assertEqual(200, response.status_int)
    self.assertEqual(0, result["visits_remaining"])

    user = Membership.get_by_email("*****@*****.**")
    self.assertEqual(10, user.signins)
    self.assertEqual("no_visits", user.status)
Example #21
0
 def get(self, hash):
     member = Membership.get_by_hash(hash)
     c = Config()
     if member:
       success_html = urlfetch.fetch(SUCCESS_HTML_URL).content
       success_html = success_html.replace('joining!', 'joining, %s!' % member.first_name)
       is_prod = c.is_prod
       self.response.out.write(render('templates/success.html', locals()))
Example #22
0
 def get(self, hash):
     member = Membership.get_by_hash(hash)
     conf = Config()
     if member:
         success_html = urlfetch.fetch(conf.SUCCESS_HTML_URL).content
         success_html = success_html.replace("joining!", "joining, %s!" % member.first_name)
         is_prod = conf.is_prod
         self.response.out.write(self.render("templates/success.html", locals()))
Example #23
0
  def setUp(self):
    super(AccountHandlerBase, self).setUp()

    # Start by putting a user in the datastore.
    user = Membership(first_name="Testy", last_name="Testerson",
                      email="*****@*****.**", plan=None,
                      status=None, hash="anunlikelyhash")
    user.put()

    self.user_hash = user.hash

    # Add the plans we need.
    Plan.all_plans = []
    Plan.legacy_pairs = set()
    self.test_plan = Plan("test", 0, 100, "A test plan.")

    # Clear fake usernames between tests.
    ProjectHandler.clear_usernames()
Example #24
0
  def setUp(self):
    super(ReactivatePlanHandlerTest, self).setUp()

    # Add a user to test with.
    self.user = Membership(first_name="Testy", last_name="Testerson",
                           email="*****@*****.**", plan="plan1",
                           spreedly_token="notatoken", hash="notahash",
                           username="******")
    self.user.put()
Example #25
0
 def get(self):
   user = users.get_current_user()
   if not user:
     self.redirect(users.create_login_url("/joinreasonlist"))
   if users.is_current_user_admin():
     all_users = Membership.all().order("created").fetch(10000)
     self.response.out.write(self.render("templates/joinreasonlist.html", locals()))
   else:
     self.response.out.write("Need admin access")
Example #26
0
  def test_retry_no_token(self):
    # Make a user with no token.
    user = Membership.get_by_hash(self.user_hash)
    user.spreedly_token=None
    user.put()

    # Try to create an account for this user.
    response = self.test_app.post("/tasks/create_user", self.params)
    self.assertEqual(200, response.status_int)

    # We should have a new task now.
    taskqueue_stub = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME)
    tasks = taskqueue_stub.GetTasks("default")
    self.assertEqual(1, len(tasks))

    # The user shouldn't have a domain account yet.
    user = Membership.get_by_hash(self.user_hash)
    self.assertFalse(user.domain_user)
Example #27
0
  def test_get(self):
    query = urllib.urlencode({"plan": "newhive"})
    response = self.test_app.get("/account/%s?%s" % (self.user_hash, query))
    self.assertEqual(200, response.status_int)
    # Our username should be templated in.
    self.assertIn("testy.testerson", response.body)

    user = Membership.get_by_hash(self.user_hash)
    self.assertEqual("newhive", user.plan)
Example #28
0
 def post(self):
   user = users.get_current_user()
   if not user:
       self.redirect(users.create_login_url('/key'))
       return
   account = Membership.all().filter('username ='******'templates/error.html', locals()))
         return
   is_park = self.request.get('ispark')
   if is_park == "True": #checks if user input is a parking pass number or an rfid number
     pass_to_add = self.request.get('parking_pass')
     try: #tests if there are only numbers in the parking pass
       float(pass_to_add)
     except ValueError:
       error = "<p>A Parking Pass may only contain numbers.</p><a href=\"/key\">Try Again</a>"
       self.response.out.write(render('templates/error.html', locals()))
       return
     account.parking_pass = pass_to_add
     db.put(account)
     self.response.out.write(render('templates/pass_ok.html', locals())) #outputs the parking number
   else:
     rfid_tag = self.request.get('rfid_tag').strip()
     description = self.request.get('description').strip()
     if rfid_tag.isdigit():
       if Membership.all().filter('rfid_tag =', rfid_tag).get():
         error = "<p>That RFID tag is in use by someone else.</p>"
         self.response.out.write(render('templates/error.html', locals()))
         return
       if not description:
         error = "<p>Please enter a reason why you are associating a replacement RFID key.  Please hit BACK and try again.</p>"
         self.response.out.write(render('templates/error.html', locals()))
         return
       account.rfid_tag = rfid_tag
       account.put()
       bc = BadgeChange(rfid_tag = rfid_tag, username=account.username, description=description)
       bc.put()
       self.response.out.write(render('templates/key_ok.html', locals()))
       return
     else:
       error = "<p>That RFID ID seemed invalid. Hit back and try again.</p>"
       self.response.out.write(render('templates/error.html', locals()))
       return
Example #29
0
    def test_skip_if_account(self):
        plan = Plan("test", 0, 100, "This is a test plan.")

        existing_user = Membership(first_name=self._TEST_PARAMS["first_name"],
                                   last_name=self._TEST_PARAMS["last_name"],
                                   email=self._TEST_PARAMS["email"],
                                   spreedly_token=None,
                                   username="******",
                                   password="******",
                                   plan=plan.name)
        existing_user.put()

        response = self.test_app.post("/", self._TEST_PARAMS)
        self.assertEqual(302, response.status_int)

        self.assertIn("subs.pinpayments.com", response.location)
        self.assertIn(plan.plan_id, response.location)
        self.assertIn(existing_user.username, response.location)
        self.assertNotIn(existing_user.password, response.location)
Example #30
0
    def test_get(self):
        query = urllib.urlencode({"plan": "newhive"})
        response = self.test_app.get("/account/%s?%s" %
                                     (self.user_hash, query))
        self.assertEqual(200, response.status_int)
        # Our username should be templated in.
        self.assertIn("testy.testerson", response.body)

        user = Membership.get_by_hash(self.user_hash)
        self.assertEqual("newhive", user.plan)
Example #31
0
  def test_skip_if_account(self):
    plan = Plan("test", 100, "This is a test plan.")

    existing_user = Membership(first_name=self._TEST_PARAMS["first_name"],
                               last_name=self._TEST_PARAMS["last_name"],
                               email=self._TEST_PARAMS["email"],
                               spreedly_token=None,
                               username="******",
                               password="******",
                               plan=plan.name)
    existing_user.put()

    response = self.test_app.post("/", self._TEST_PARAMS)
    self.assertEqual(302, response.status_int)

    self.assertIn("subs.pinpayments.com", response.location)
    self.assertIn(plan.plan_id, response.location)
    self.assertIn(existing_user.username, response.location)
    self.assertNotIn(existing_user.password, response.location)
Example #32
0
    def test_signin(self):
        params = {"email": "*****@*****.**"}
        response = self.test_app.post("/api/v1/signin", params)
        result = json.loads(response.body)

        self.assertEqual(Config().LITE_VISITS - 1, result["visits_remaining"])

        # Check that our user signing in got recorded.
        user = Membership.get_by_email("*****@*****.**")
        self.assertEqual(1, user.signins)
Example #33
0
 def get(self):
     user = users.get_current_user()
     if not user:
         self.redirect(users.create_login_url("/profile"))
         return
     else:
         account = Membership.get_by_email(user.email())
         email = "%s@%s" % (account.username, Config().APPS_DOMAIN)
         gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(email.lower()).hexdigest()
         self.response.out.write(self.render("templates/profile.html", locals()))
Example #34
0
    def test_post(self):
        query = urllib.urlencode(self._TEST_PARAMS)
        response = self.test_app.post("/account/" + self.user_hash, query)
        self.assertEqual(302, response.status_int)

        user = Membership.get_by_hash(self.user_hash)

        # We should be redirected to a personal spreedly page.
        self.assertIn("subs.pinpayments.com", response.location)
        self.assertIn(self.test_plan.plan_id, response.location)
        self.assertIn(str(user.key().id()), response.location)
        self.assertIn("testy.testerson", response.location)

        # The account information should be in the datastore.
        user = Membership.get_by_hash(self.user_hash)
        self.assertEqual("testy.testerson", user.username)
        self.assertEqual("notasecret", user.password)

        # We shouldn't have a domain account yet.
        self.assertFalse(user.domain_user)
Example #35
0
    def test_already_active(self):
        user = Membership.get_by_hash(self.user_hash)
        user.status = "active"
        user.put()

        query = urllib.urlencode(self._TEST_PARAMS)
        response = self.test_app.post("/account/" + self.user_hash, query)

        self.assertEqual(302, response.status_int)
        self.assertIn("success", response.location)
        self.assertIn(self.user_hash, response.location)
Example #36
0
    def __init__(self, attributes):

        self.name = attributes.get('name')

        self.cpf = attributes.get('name')

        self.billingAddress = Address(attributes.get('billingAddress'))

        if (attributes.get('membership') != None):

            self.membership = Membership(attributes.get('membership'))
Example #37
0
  def __batch_loop(self, cursor = None, *args, **kwargs):
    cursor = cursor
    while True:
      if (args == () and kwargs == {}):
        query = Membership.all()
      else:
        query = Membership.all().filter(*args, **kwargs)
      query.with_cursor(start_cursor = cursor)
      members = query.fetch(self.batch_size)

      if len(members) == 0:
        break
      for member in members:
        member = self.__strip_sensitive(member)
        self.__post_member(member)

      cursor = query.cursor()
      run_info = SyncRunInfo.all().get()
      run_info.cursor = cursor
      run_info.put()
Example #38
0
    def test_user_restore(self):
        self.user.signins = Config().LITE_VISITS + 2
        self.user.status = "no_visits"
        self.user.put()

        response = self.test_app.get("/cron/reset_signins")
        self.assertEqual(200, response.status_int)

        user = Membership.get_by_email("*****@*****.**")
        self.assertEqual(0, user.signins)
        self.assertEqual("active", user.status)
Example #39
0
    def setUp(self):
        super(AccountHandlerBase, self).setUp()

        # Start by putting a user in the datastore.
        user = Membership(first_name="Testy",
                          last_name="Testerson",
                          email="*****@*****.**",
                          plan=None,
                          status=None,
                          hash="anunlikelyhash")
        user.put()

        self.user_hash = user.hash

        # Add the plans we need.
        Plan.all_plans = []
        Plan.legacy_pairs = set()
        self.test_plan = Plan("test", 0, 100, "A test plan.")

        # Clear fake usernames between tests.
        ProjectHandler.clear_usernames()
Example #40
0
 def get(self):
     user = users.get_current_user()
     if not user:
         self.redirect(users.create_login_url("/profile"))
         return
     else:
         account = Membership.get_by_email(user.email())
         email = "%s@%s" % (account.username, Config().APPS_DOMAIN)
         gravatar_url = "http://www.gravatar.com/avatar/" + \
             hashlib.md5(email.lower()).hexdigest()
         self.response.out.write(
             self.render("templates/profile.html", locals()))
Example #41
0
    def test_bad_length_code(self):
        code = "133712345"

        user = Membership.get_by_hash(self.user_hash)
        user.referrer = code
        user.put()

        response = self.test_app.post("/account/" + self.user_hash,
                                      self._TEST_PARAMS,
                                      expect_errors=True)
        self.assertEqual(422, response.status_int)
        self.assertIn("must be 16 digits", response.body)
Example #42
0
    def test_invalid_code(self):
        code = "1337424242424242"

        user = Membership.get_by_hash(self.user_hash)
        user.referrer = code
        user.put()

        response = self.test_app.post("/account/" + self.user_hash,
                                      self._TEST_PARAMS,
                                      expect_errors=True)
        self.assertEqual(422, response.status_int)
        self.assertIn("code was invalid", response.body)
Example #43
0
    def test_post(self):
        response = self.test_app.post("/", self._TEST_PARAMS)
        self.assertEqual(302, response.status_int)

        # It should have put an entry in the datastore.
        user = Membership.get_by_email("*****@*****.**")
        self.assertNotEqual(None, user)
        self.assertEqual("Testy", user.first_name)
        self.assertEqual("Testerson", user.last_name)
        self.assertEqual("ttesterson", user.twitter)
        self.assertEqual("My mom", user.referrer)
        self.assertNotEqual(None, user.hash)
Example #44
0
 def get(self):
   countdown = 0
   for membership in Membership.all().filter("status =", "suspended"):
     if (not membership.unsubscribe_reason and membership.spreedly_token \
         and "Deleted" not in membership.last_name and \
         membership.extra_dnd != True):
       # One e-mail every 90 seconds = 960 e-mails a day.
       countdown += 90
       self.response.out.write("Are you still there %s ?<br/>" % \
                               (membership.email))
       taskqueue.add(url="/tasks/areyoustillthere_mail",
           params={"user": membership.key().id()}, countdown=countdown)
Example #45
0
    def get(self, hash):
        membership = Membership.get_by_hash(hash)
        if not membership:
            self.response.set_status(422)
            self.response.out.write("Unknown member hash.")
            logging.error("Could not find member with hash '%s'." % (hash))
            return

        # Save the plan they want.
        plan = self.request.get("plan", "newfull")
        membership.plan = plan
        membership.put()

        if ((membership.username and membership.password) and not \
            membership.spreedly_token):
            # We've filled out our account information, but we never started a
            # subscription. (This could be reached by going back and trying to
            # change our plan after we were already taken to the PinPayments
            # page.) In this case, just pass them through to PinPayments.
            self.redirect(
                membership.new_subscribe_url(self.request.host, plan=plan))

        # steal this part to detect if they registered with hacker dojo email above
        first_part = re.compile(r"[^\w]").sub(
            "",
            membership.first_name.split(" ")[0])  # First word of first name
        last_part = re.compile(r"[^\w]").sub("", membership.last_name)
        if len(first_part) + len(last_part) >= 15:
            last_part = last_part[0]  # Just last initial
        username = "******".join([first_part, last_part]).lower()

        usernames = self.fetch_usernames()
        if usernames == None:
            # Error page is already rendered.
            return
        if username in usernames:
            # Duplicate username. Use the first part of the email instead.
            username = membership.email.split("@")[0].lower()

            user_number = 0
            base_username = username
            while username in usernames:
                # Still a duplicate. Add a number.
                user_number += 1
                username = "******" % (base_username, user_number)

        if self.request.get("pick_username"):
            pick_username = True

        account_url = str("/account/%s" % membership.hash)
        self.response.out.write(self.render("templates/account.html",
                                            locals()))
Example #46
0
    def get(self, user_hash):
        member = Membership.get_by_hash(user_hash)

        if not member:
            # Hash is invalid.
            logging.error("Invalid hash '%s'." % (user_hash))
            error = self.render("templates/error.html",
                                message="Invalid reactivation link.")
            self.response.out.write(error)
            self.response.set_status(422)
            return

        self._plan_switch_page(member)
Example #47
0
    def test_suspended_user(self):
        user = Membership.get_by_email("*****@*****.**")
        user.status = "suspended"
        user.put()

        params = {"email": "*****@*****.**"}
        response = self.test_app.post("/api/v1/signin",
                                      params,
                                      expect_errors=True)
        result = json.loads(response.body)

        self.assertEqual(422, response.status_int)
        self.assertIn("Could not find", result["message"])
Example #48
0
    def test_cleanup(self):
        response = self.test_app.post("/tasks/clean_row", self.params)
        self.assertEqual(200, response.status_int)

        # Make sure the user is gone.
        user = Membership.get_by_id(self.user_id)
        self.assertEqual(None, user)

        # Make sure our email got sent and looks correct.
        messages = self.mail_stub.get_sent_messages(to=self.user.email)
        self.assertEqual(1, len(messages))
        body = str(messages[0].body)
        self.assertIn(self.user.full_name(), body)
Example #49
0
    def test_legacy_pairing(self):
        self.plan1.member_limit = 2

        user1 = Membership(first_name="Testy1",
                           last_name="Testerson",
                           email="*****@*****.**",
                           plan="plan1")
        user1.put()
        user2 = Membership(first_name="Testy2",
                           last_name="Testerson",
                           email="*****@*****.**",
                           plan="plan4")
        user2.put()

        self.assertTrue(self.plan1.is_full())
Example #50
0
    def setUp(self):
        # Set up testing for application.
        self.test_app = webtest.TestApp(tasks.app)

        # Set up datastore for testing.
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_taskqueue_stub()
        self.testbed.init_mail_stub()
        self.testbed.init_memcache_stub()

        # Add a user to the datastore.
        self.user = Membership(first_name="Testy",
                               last_name="Testerson",
                               email="*****@*****.**",
                               hash="notahash",
                               spreedly_token="notatoken",
                               username="******",
                               password="******")
        self.user.put()

        self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME)
Example #51
0
    def test_bad_user_id(self):
        params = {"user": "******"}
        response = self.test_app.post("/tasks/clean_row", params)
        # The status should still be okay, because we don't want it to retry in this
        # case.
        self.assertEqual(200, response.status_int)

        # The user should still be there.
        user = Membership.get_by_id(self.user_id)
        self.assertNotEqual(None, user)

        # No email should have gotten sent.
        messages = self.mail_stub.get_sent_messages(to=self.user.email)
        self.assertEqual(0, len(messages))
Example #52
0
    def create(cls,
               user_name,
               email,
               password=None,
               locale=None,
               openid_identity=None,
               global_admin=False):
        from group import Group
        from membership import Membership
        from openid import OpenID

        import adhocracy.lib.util as util
        if password is None:
            password = util.random_token()

        import adhocracy.i18n as i18n
        if locale is None:
            locale = i18n.get_default_locale()

        user = User(user_name, email, password, locale)
        meta.Session.add(user)
        default_group = Group.by_code(Group.CODE_DEFAULT)
        default_membership = Membership(user, None, default_group)
        meta.Session.add(default_membership)

        if global_admin:
            admin_group = Group.by_code(Group.CODE_ADMIN)
            admin_membership = Membership(user, None, admin_group)
            meta.Session.add(admin_membership)

        if openid_identity is not None:
            openid = OpenID(unicode(openid_identity), user)
            meta.Session.add(openid)

        meta.Session.flush()
        return user
Example #53
0
 def post(self, id):
     member = Membership.get_by_id(int(id))
     if member:
         unsubscribe_reason = self.request.get("unsubscribe_reason")
         if unsubscribe_reason:
             member.unsubscribe_reason = unsubscribe_reason
             member.put()
             self.response.out.write(
                 self.render("templates/unsubscribe_thanks.html", locals()))
         else:
             self.response.out.write(
                 self.render("templates/unsubscribe_error.html", locals()))
     else:
         self.response.out.write(
             "error: could not locate your membership record.")
Example #54
0
    def test_already_entered(self):
        user = Membership.get_by_hash(self.user_hash)
        user.username = "******"
        user.password = "******"
        user.spreedly_token = None
        user.put()

        response = self.test_app.get("/account/" + self.user_hash,
                                     self._TEST_PARAMS)

        # We should be redirected to a personal spreedly page.
        self.assertEqual(302, response.status_int)
        self.assertIn("subs.pinpayments.com", response.location)
        self.assertIn(self.test_plan.plan_id, response.location)
        self.assertIn(str(user.key().id()), response.location)
        self.assertIn("testy.testerson", response.location)
Example #55
0
class ResetSigninHandlerTest(unittest.TestCase):
    def setUp(self):
        # Set up testing application.
        self.test_app = webtest.TestApp(cron.app)

        # Set up datastore for testing.
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()

        # Add a user to the datastore.
        self.user = Membership(first_name="Testy",
                               last_name="Testerson",
                               email="*****@*****.**")
        self.user.put()

    """ Tests that the cron job restores users properly. """

    def test_user_restore(self):
        self.user.signins = Config().LITE_VISITS + 2
        self.user.status = "no_visits"
        self.user.put()

        response = self.test_app.get("/cron/reset_signins")
        self.assertEqual(200, response.status_int)

        user = Membership.get_by_email("*****@*****.**")
        self.assertEqual(0, user.signins)
        self.assertEqual("active", user.status)

    """ Tests that unused signins rollover properly. """

    def test_rollover(self):
        self.user.signins = Config().LITE_VISITS - 2
        self.user.status = "active"
        self.user.put()

        response = self.test_app.get("/cron/reset_signins")
        self.assertEqual(200, response.status_int)

        user = Membership.get_by_email("*****@*****.**")
        self.assertEqual(-2, user.signins)
        self.assertEqual("active", user.status)

        # Test that signins_remaining gives us the right number.
        test_plan = Plan("test_lite",
                         1,
                         100,
                         "A test plan",
                         signin_limit=Config().LITE_VISITS)
        user.plan = "test_lite"
        remaining = Plan.signins_remaining(user)
        self.assertEqual(Config().LITE_VISITS + 2, remaining)
Example #56
0
    def setUp(self):
        super(MemberListHandlerTest, self).setUp()

        # This handler requires admin access all the time, so give ourselves that
        # right off the bat.
        self.testbed.setup_env(user_email="*****@*****.**",
                               user_is_admin="1",
                               overwrite=True)

        # Make exactly two pages worth of users.
        for i in range(0, 50):
            email = "*****@*****.**" % (i)
            first_name = "Testy%d" % (i)
            user = Membership.create_user(email,
                                          "notasecret",
                                          first_name=first_name,
                                          last_name="Testerson",
                                          status="active")
Example #57
0
    def create(cls, key, label, user, description=None, locale=None):
        from group import Group
        from membership import Membership
        from page import Page

        instance = Instance(unicode(key).lower(), label, user)
        instance.description = description
        instance.default_group = Group.by_code(Group.INSTANCE_DEFAULT)
        if locale is not None:
            instance.locale = locale
        meta.Session.add(instance)
        supervisor_group = Group.by_code(Group.CODE_SUPERVISOR)
        membership = Membership(user, instance, supervisor_group,
                                approved=True)
        meta.Session.add(membership)
        Page.create(instance, label, u"", user)
        meta.Session.flush()
        return instance
Example #58
0
    def test_trivial_failures(self):
        # Give it a bad hash.
        bad_params = {"hash": "badhash"}

        response = self.test_app.post("/tasks/create_user",
                                      bad_params,
                                      expect_errors=True)
        self.assertEqual(422, response.status_int)

        # Give it a user with a username already.
        user = Membership.get_by_hash(self.user_hash)
        user.username = "******"
        user.put()

        response = self.test_app.post("/tasks/create_user", self.params)
        # This should be okay, because we don't want PinPayments to think it needs
        # to retry the call.
        self.assertEqual(200, response.status_int)
Example #59
0
 def get(self):
     suspended_users = Membership.all().filter("status =",
                                               "suspended").filter(
                                                   "last_name !=",
                                                   "Deleted").fetch(10000)
     tokened_users = []
     for user in suspended_users:
         if user.spreedly_token:
             tokened_users.append(user)
     suspended_users = sorted(tokened_users,
                              key=lambda user: user.last_name.lower())
     total = len(suspended_users)
     reasonable = 0
     for user in suspended_users:
         if user.unsubscribe_reason:
             reasonable += 1
     self.response.out.write(
         self.render("templates/suspended.html", locals()))
Example #60
0
    def get(self):
        active_users = Membership.all().filter("status =", "active").filter(
            "plan =", "hardship").fetch(10000)
        active_users = sorted(active_users, key=lambda user: user.created)
        subject = "About your Hacker Dojo membership"
        body1 = "\n\nWe hope you have enjoyed your discounted membership at \
              Hacker Dojo.  As you\nknow, we created the hardship program \
              to give temporary financial support to help\nmembers get \
              started at the Dojo. Our records show you began the program\n \
              on"

        body2 = ", and we hope you feel that you have benefited.\n\nBeginning \
              with your next month's term, we ask that you please sign up \
              at\nour regular rate:\n"

        body3 = "\n\nThank you for supporting the Dojo!"
        self.response.out.write(
            self.render("templates/hardship.html", locals()))