Exemple #1
0
class AuthHelper:

    def __init__(self):
        self.user_cookie = 'uc'
        self.secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)

    def get_authenticated_user(self, request):
        """
            Reads the auth cookie from the request and returns the user entity
            associated to the cookie value.
        """
        cookie_val = request.cookies.get(self.user_cookie)
        uid = self.secure_cookie_serializer.deserialize(self.user_cookie, cookie_val)
        return uid and User.by_username(uid)


    def set_auth_cookie(self, response, uid):
        """
            Takes a valid user id and sets a secure cookie (token) in the
            response used to validate if the user is signed in.
        """
        cookie_val = self.secure_cookie_serializer.serialize(self.user_cookie, uid)
        response.set_cookie(self.user_cookie, cookie_val, httponly=True)

    def destroy_auth_cookie(self, response):
        response.delete_cookie(self.user_cookie)
	def test_instructor_can_create_new_category(self):
		
		qkey = self.q00_key
		respond = ResponseHandler()
		session = {
			'account': self.instructor.username,
			'accounttype': ADMIN,
			'class': self.classy.classname,
			'question_key': qkey.urlsafe(),
		}
		secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
		serialized = secure_cookie_serializer.serialize('session', session)
		headers = {'Cookie':'session=%s' % serialized}
		respond.request = Request.blank('/respond?add_to_category=1&response=test&cname=Default&new_cname=test_category')
		respond.request.method='POST'
		respond.request.headers=headers
		
		#ensure that the vars were passed to test properly
		self.assertTrue(respond.request.get('response') == 'test')
		self.assertTrue(respond.request.get('new_cname') == 'test_category')
		
		temp = Category.query(Category.name=='test_category').fetch()
		for c in temp:
			c.key.delete()
		del temp
		
		response = respond.request.get_response(main.app)
		
		time.sleep(2)
		category = Category.query(Category.name == 'test_category').fetch()
		
		self.assertTrue(len(category)==1) #was created and is unique, also has the correct name
		category = category[0]
		self.assertTrue(category.key.parent() == self.classy.key)
		category.key.delete()
Exemple #3
0
    def test_instructor_can_set_category_to_answer(self):

        qkey = self.q00_key

        respond = ResponseHandler()
        session = {
            'account': self.instructor.username,
            'accounttypr': ADMIN,
            'class': self.classy.classname,
            'question_key': qkey.urlsafe(),
        }
        secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
        serialized = secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}
        respond.request = Request.blank(
            '/respond?response=test&cname=test_category')
        respond.request.method = 'POST'
        respond.request.headers = headers

        #ensure that the vars were passed to test properly
        self.assertTrue(respond.request.get('response') == 'test')
        self.assertTrue(respond.request.get('cname') == 'test_category')

        response = respond.request.get_response(main.app)

        time.sleep(2)
        question = qkey.get()
        cate = Category.query(Category.name == 'test_category').fetch()
        self.assertTrue(
            len(cate) ==
            1)  #was created/found and is unique, also has the correct name
        cate = cate[0]
        self.assertTrue(question.category == cate.key)
        question.key.delete()
        cate.key.delete()
Exemple #4
0
    def test_instructor_can_respond(self):

        qkey = self.q00_key
        respond = ResponseHandler()
        session = {
            'account': self.instructor.username,
            'accounttypr': ADMIN,
            'class': self.classy.classname,
            'question_key': qkey.urlsafe(),
        }
        secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
        serialized = secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}

        respond.request = Request.blank('/respond?response=test')
        respond.request.method = 'POST'
        #respond.request.body = 'response=test'
        respond.request.headers = headers
        #print '\n'+respond.request.get('message')+'\n'

        self.assertTrue(respond.request.get('response') == 'test')

        response = respond.request.get_response(main.app)
        #message = response.get('message')
        question = qkey.get()
        self.assertFalse(question == None)
        self.assertFalse(question.respondentUID == None)
        self.assertFalse(question.response == None)
        self.assertFalse(question.response == '')
        self.assertTrue(question.respondentUID == self.instructor.key)
        self.assertTrue(question.response == 'test')
Exemple #5
0
    def test_instructor_can_respond_with_faq(self):

        qkey = self.q00_key

        respond = ResponseHandler()
        session = {
            'account': self.instructor.username,
            'accounttypr': ADMIN,
            'class': self.classy.classname,
            'question_key': qkey.urlsafe(),
        }
        secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
        serialized = secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}
        respond.request = Request.blank('/respond?response=test&infaq=infaq')
        respond.request.method = 'POST'
        respond.request.headers = headers

        self.assertTrue(respond.request.get('response') == 'test')
        self.assertTrue(respond.request.get('infaq') == 'infaq')

        response = respond.request.get_response(main.app)

        time.sleep(2)

        question = qkey.get()
        self.assertTrue(question.response == R_INFAQ)
Exemple #6
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # create a cookie serializer to emulate our sessions
        self.secure_cookie_serializer = SecureCookieSerializer(
            'no-one-will-guess-kwsfs-secret-key')
        sessionConfig = {}
        sessionConfig['webapp2_extras.sessions'] = {
            'secret_key': 'no-one-will-guess-kwsfs-secret-key',
        }
        # redirect Jinja Env to a directory up
        Base.JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader('../html'),
            extensions=['jinja2.ext.autoescape'],
            autoescape=True)

        # prepare env with only needed URLs
        app = webapp2.WSGIApplication(
            [('/', Login.LoginHandler),
             ('/manage.html', Management.ManagementHandler)],
            debug=True,
            config=sessionConfig)

        self.testapp = webtest.TestApp(app)
Exemple #7
0
def set_cookie(self):
    cookie_val = self.request.cookies.get('uid', default = None)
    serializer = SecureCookieSerializer(app_globals.secure_cookie_pass_phrase)
    self.response.write('cookie value is %s (raw) & %s (deserialized)'%(cookie_val, serializer.deserialize('uid', cookie_val)))
    current_time = gmtime()
    self.response.set_cookie(key = 'uid', value = serializer.serialize('uid', 'lollolo'), path = '/',
      expires = datetime(current_time.tm_year + app_globals.login_cookie_expiry, current_time.tm_mon, current_time.tm_mday))
    self.response.write('----------------------------------')
Exemple #8
0
class CookieHelper():

    cookie = None
    max_age_dir = {}

    def __init__(self, secret_key=None):
        if secret_key:
            self.cookie = SecureCookieSerializer(secret_key)
        else:
            self.cookie = SecureCookieSerializer(SECRET_KEY)

    def _serialize(self, name, value):
        return self.cookie.serialize(name, value)

    def _deserialize(self, name, value, max_age=None):
        return self.cookie.deserialize(name, value, max_age=None)

    def get(self, controller, name, encrypted=True):
        value = controller.request.cookies.get(name)
        max_age = None
        if name in self.max_age_dir:
            max_age = self.max_age_dir[name]
        if encrypted:
            return self._deserialize(name, value, max_age)
        return value

    def write(self,
              controller,
              name,
              value,
              max_age=None,
              path='/',
              domain=None,
              secure=False,
              encrypted=True):
        # Saves a cookie in the client.
        if encrypted:
            value = self._serialize(name, value)
        if max_age:
            self.max_age_dir[name] = max_age
        controller.response.set_cookie(name,
                                       value,
                                       max_age=max_age,
                                       path=path,
                                       domain=domain,
                                       secure=secure)

    def delete(self, controller, name):
        # Deletes a cookie previously set in the client.
        controller.response.delete_cookie(name)

    def unset(self, controller, name):
        # Cancels a cookie previously set in the response.
        controller.response.unset_cookie(name)
Exemple #9
0
    def get(self, path, data=None, session={}):

        secure_cookie_serializer = SecureCookieSerializer(SPLUNK_PROJECT_ID)
        serialized_session = secure_cookie_serializer.serialize(
            'session', session)
        headers = {'Cookie': 'session=%s' % serialized_session}
        if data:
            return self.app.post_json(path,
                                      data,
                                      headers=headers,
                                      expect_errors=True)
        return self.app.get(path, headers=headers)
Exemple #10
0
def login_headers(user_id):
    """Simulate a logged-in session cookie to be included in requests.

    http://www.recursion.org/2011/10/12/testing-webapp2-sessions-with-webtest
    """
    session = {'user': user_id}
    scs = SecureCookieSerializer(config.default_session_cookie_secret_key)
    cookie_value = scs.serialize(config.session_cookie_name, session)
    headers = {
        'Cookie': '{}={}'.format(config.session_cookie_name, cookie_value)
    }
    return headers
Exemple #11
0
    def login(self, user=None, app_name="dashboard"):
        """Return a header containing the auth cookie.

        """
        user = user if user else self.new_user()
        session_name = "session_%s" % app_name
        session = {'user_id': user.key.id(), 'user_domain': 'example.com'}
        secure_cookie_serializer = SecureCookieSerializer(self.secret)
        serialized = secure_cookie_serializer.serialize(
            session_name, session
        )
        return {
            'X-App-Name': app_name,
            'Cookie': '%s=%s' % (session_name, serialized,)
        }
Exemple #12
0
    def login(self, user=None, app_name="dashboard"):
        """Return a header containing the auth cookie.

        """
        user = user if user else self.new_user()
        session_name = "session_%s" % app_name
        session = {'user_id': user.key.id(), 'user_domain': 'example.com'}
        secure_cookie_serializer = SecureCookieSerializer(self.secret)
        serialized = secure_cookie_serializer.serialize(session_name, session)
        return {
            'X-App-Name': app_name,
            'Cookie': '%s=%s' % (
                session_name,
                serialized,
            )
        }
Exemple #13
0
    def get(self, path, data=None, session={}):

        secure_cookie_serializer = SecureCookieSerializer(
            SPLUNK_PROJECT_ID
        )
        serialized_session = secure_cookie_serializer.serialize(
            'session', session
        )
        headers = {'Cookie': 'session=%s' % serialized_session}
        if data:
            return self.app.post_json(
                path,
                data,
                headers=headers,
                expect_errors=True
            )
        return self.app.get(path, headers=headers)
Exemple #14
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # create a cookie serializer to emulate our sessions
        self.secure_cookie_serializer = SecureCookieSerializer('no-one-will-guess-kwsfs-secret-key')
        sessionConfig = {}
        sessionConfig['webapp2_extras.sessions'] = {
            'secret_key': 'no-one-will-guess-kwsfs-secret-key',
        }
        # redirect Jinja Env to a directory up
        Base.JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader('../html'),
            extensions=['jinja2.ext.autoescape'],
            autoescape=True)

        # prepare env with only needed URLs
        app = webapp2.WSGIApplication([
            ('/syllabusStepCalendar.html', Calendar.CalendarHandler),
            ('/deleteCalendarEntry', Calendar.DeleteCalendarEntryHandler),
            ('/updateCalendarEntries', Calendar.UpdateCalendarEntriesHandler)
        ], debug=True, config=sessionConfig)

        self.testapp = webtest.TestApp(app)

        # TODO: replace this with a parser mock once the parser is integrated
        # This is used to verify functionality in tests that are not testing entry's results
        # Entry is tested separately, and these responses allows further test isolation
        self.start_date = date(2015, 8, 1)
        self.end_date = date(2016, 2, 1)
        self.days_of_week = [0, 2, 4]
        self.entry_response = Calendar.generateEntryRange(self.start_date, self.end_date, self.days_of_week)

        # create a test user
        newUser = DBM.User(parent=DBM.UserKey("rock"),
                           username="******", password="******")
        newUser.put()

        # create a test syllabus
        self.syllabusKey = DBM.SyllabusKey("MyTestSyllabus")
        self.syllabusName = "MyTestSyllabus"
        newSyllabus = DBM.Syllabus(parent=self.syllabusKey, name=self.syllabusName,
                                   active=False)
        newSyllabus.put()
Exemple #15
0
    def get_user_or_none(cls, req):
        """
        actual method that return the user or ``None``

        :param req:
        :return:
        """

        uid = None
        ut = None
        # # in case it's test. use remote user.
        # if 'REMOTE_USER' in req.environ and cls.__config_file.DEBUG:
        # token = req.environ['REMOTE_USER']
        # uid, ut = token.split("Token")[1].split("|")
        # even if in test, but the remote user is not found. then...
        if not uid and not ut:
            token = req.headers.get("Authorization")
            if token:
                ret_token = token.split("Token")[1]
                if not ret_token:
                    return None
                uid, ut = ret_token.split("|")
            else:
                scs = SecureCookieSerializer(cls.__config_file.API_APP_CFG[cls.__app_name]['SECRET_KEY'])
                token = req.cookies.get('gc_token')
                if token:
                    token_des = scs.deserialize('Token', token)
                    if not token_des:
                        return None
                    uid, ut = token_des.split("|")
                else:
                    return None
        if uid and ut:
            # user = memcache.get("%s|%s" % (uid, ut))
            # if user:
            # return user
            # else:
            if cls.__user_model.validate_auth_token(long(uid), ut):
                user = cls.__user_model.get_by_auth_token(long(uid), ut)[0]
                return user
                # store in memcace for 1 week
                # memcache.set("%s|%s" % (uid, ut), user, time=60 * 24 * 7)
        return None
    def setUp(self):
        # initializing app engine testing environment
        self.cookie_serializer = SecureCookieSerializer(self.KEY)
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_app_identity_stub()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_files_stub()
        self.testbed.init_blobstore_stub()

        # initializing test user data
        self.test_user_id1 = '1'
        self.test_user_id2 = '2'
        self.test_user_id3 = '3'
        self.test_user_id4 = '4'

        self.test_user_1 = User(
            key_name=self.test_user_id1,
            id=self.test_user_id1,
            name='Test User 1',
            profile_url=' ',
            access_token=' '
        )
        self.test_user_1.put()

        self.test_user_2 = User(
            key_name=self.test_user_id2,
            id=self.test_user_id2,
            name='Test User 2',
            profile_url=' ',
            access_token=' '
        )
        self.test_user_2.put()

        self.test_user_3 = User(
            key_name=self.test_user_id3,
            id=self.test_user_id3,
            name='Test User 3',
            profile_url=' ',
            access_token=' '
        )
        self.test_user_3.put()

        self.test_user_4 = User(
            key_name=self.test_user_id4,
            id=self.test_user_id4,
            name='Test User 4',
            profile_url=' ',
            access_token=' '
        )
        self.test_user_4.put()

        self.challenge_ID_Factory = Challenge_ID_Factory(id_counter=0)
        self.challenge_ID_Factory.put()
Exemple #17
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # create a cookie serializer to emulate our sessions
        self.secure_cookie_serializer = SecureCookieSerializer('no-one-will-guess-kwsfs-secret-key')
        sessionConfig = {}
        sessionConfig['webapp2_extras.sessions'] = {
            'secret_key': 'no-one-will-guess-kwsfs-secret-key',
        }
        # redirect Jinja Env to a directory up
        Base.JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader('../html'),
            extensions=['jinja2.ext.autoescape'],
            autoescape=True)

        # prepare env with only needed URLs
        app = webapp2.WSGIApplication([
            ('/delinkPolicy', CoursePolicy.DelinkPolicyHandler),
            ('/deletePolicy', CoursePolicy.DeletePolicyHandler),
            ('/editPolicy', CoursePolicy.EditPolicyHandler),
            ('/linkPolicy', CoursePolicy.LinkPolicyHandler),
            ('/syllabusStepPoliciesEditor.html', CoursePolicy.CoursePolicyEditHandler),
            ('/policyLib.html', CoursePolicy.PolicyLibHandler)
        ], debug=True, config=sessionConfig)

        self.testapp = webtest.TestApp(app)

        # create a test user
        newUser = DBM.User(parent=DBM.UserKey("rock"),
                           username="******", password="******")
        newUser.put()

        # create a test syllabus
        self.syllabusKey = DBM.SyllabusKey("MyTestSyllabus")
        self.syllabusName = "MyTestSyllabus"
        newSyllabus = DBM.Syllabus(parent=self.syllabusKey, name=self.syllabusName,
                                   active=False)
        newSyllabus.put()
Exemple #18
0
  def log_user_in(self, user):
    user_id = user.put().id()
    session = {
      '_user': [
        user_id,
        False,
        webapp2_extras.appengine.auth.models.User.create_auth_token(user_id),
        0,
        0
      ]
    }
    secure_cookie_serializer = SecureCookieSerializer(
        SUPER_SECRET
    )
    serialized = secure_cookie_serializer.serialize(
        '_simpleauth_sess', session
    )
    os.environ['USER_IS_ADMIN'] = '1' if user.is_admin else '0'
    os.environ['USER_EMAIL'] = '' if user.is_anonymous else user.email

    return {'Cookie': '_simpleauth_sess=%s' % serialized}
class BaseHandler(webapp2.RequestHandler):

    def initialize(self, request, response):
        super(BaseHandler, self).initialize(request, response)
        # initialise with secret key
        self.cookie_serializer = SecureCookieSerializer(SECRET)

    def write(self, *args, **kwgs):
        self.response.out.write(*args, **kwgs)

    def render_str(self, template, **params):
        t = env.get_template(template)
        return t.render(**params)

    def render(self, template, **params):
        self.write(self.render_str(template, **params))

    def get_cookie(self):
        user_cookie = self.request.cookies.get('userid')
        if user_cookie:
            user_cookie = self.cookie_serializer.deserialize(
                'userid',
                user_cookie
            )
            if not user_cookie:
                # invalid cookie signature
                return None, ''
            user_id, username = user_cookie.split('|')
            user_id = int(user_id)
            return user_id, username
        else:
            return None, ''

    def get_user(self):
        user_id, username = self.get_cookie()
        logging.info('get_user -> {}, {}'.format(user_id, username))
        if not user_id:
            # no logged in user cookie
            return None, None

        user = User.get_by_id(user_id)
        return user_id, user
Exemple #20
0
 def get_secure_cookie(cls, token):
     scs = SecureCookieSerializer(cls.__config_file.API_APP_CFG[cls.__app_name]['SECRET_KEY'])
     token = scs.serialize('Token', token)
     return token
Exemple #21
0
 def __init__(self, secret_key=None):
     if secret_key:
         self.cookie = SecureCookieSerializer(secret_key)
     else:
         self.cookie = SecureCookieSerializer(SECRET_KEY)
class BaseTestCase(unittest.TestCase, WebTestCase):
    """
    Base class of unit test cases for challenge request related classes
    and functions.
    """
    APPLICATION = application
    KEY = SECRET_KEY

    def setUp(self):
        # initializing app engine testing environment
        self.cookie_serializer = SecureCookieSerializer(self.KEY)
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_app_identity_stub()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_files_stub()
        self.testbed.init_blobstore_stub()

        # initializing test user data
        self.test_user_id1 = '1'
        self.test_user_id2 = '2'
        self.test_user_id3 = '3'
        self.test_user_id4 = '4'

        self.test_user_1 = User(
            key_name=self.test_user_id1,
            id=self.test_user_id1,
            name='Test User 1',
            profile_url=' ',
            access_token=' '
        )
        self.test_user_1.put()

        self.test_user_2 = User(
            key_name=self.test_user_id2,
            id=self.test_user_id2,
            name='Test User 2',
            profile_url=' ',
            access_token=' '
        )
        self.test_user_2.put()

        self.test_user_3 = User(
            key_name=self.test_user_id3,
            id=self.test_user_id3,
            name='Test User 3',
            profile_url=' ',
            access_token=' '
        )
        self.test_user_3.put()

        self.test_user_4 = User(
            key_name=self.test_user_id4,
            id=self.test_user_id4,
            name='Test User 4',
            profile_url=' ',
            access_token=' '
        )
        self.test_user_4.put()

        self.challenge_ID_Factory = Challenge_ID_Factory(id_counter=0)
        self.challenge_ID_Factory.put()

    def tearDown(self):
        self.testbed.deactivate()

    def set_session_user(self, user):
        """
        Set the user variable in current session.

        :param user: the User object to be set as the session's user
        :return: a header that can be added to a request
        """
        session_user = dict(
            name=user.name,
            profile_url=user.profile_url,
            id=user.id,
            access_token=user.access_token
        )
        session = {"user": session_user}
        serialized = self.cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}
        return headers

    def create_test_challenge(self, creator_id, challenge_id=None):
        """
        Create a test challenge and put it into the test datastore.

        :param creator_id: the user_id of the challenge creator
        :param challenge_id: if None, a id will be generated by the
        challenge_ID_Factory; otherwise, the created challenge will use the
        provide id
        :return: the created challenge.
        """
        if challenge_id is None:
            challenge_id = self.challenge_ID_Factory.get_id()

        test_challenge = Challenge(
            challenge_id=challenge_id,
            creator_id=creator_id,
            title='test challenge ' + str(challenge_id),
            summary="This is the summary of test challenge "
                    + str(challenge_id),
            content="This is the content of test challenge "
                    + str(challenge_id),
            state='ongoing',
            parent=KeyStore.challenge_key())
        test_challenge.category.append(available_category_list[0])
        test_challenge.put()
        return test_challenge

    def create_test_request(self, inviter_id, invitee_id, challenge_id=None,
                            status=RequestStatus.PENDING, file_info=None):
        """
        Create a test challenge request and put it into the test datastore.

        :param inviter_id: the inviter_id of the test request
        :param invitee_id: the invitee_id of the test request
        :param challenge_id: if None, a test challenge will be created with
        creator_id being test_user_id1; otherwise, it will try to find the
        challenge with the provided id; if not found, a new challenge will be
        created with that id.
        :param status: the status of the test request. the default status is
        RequestStatus.PENDING
        :param file_info: if provided, it will be the file_info of the request
        :return: the created challenge request
        """
        if challenge_id is None:
            test_challenge = self.create_test_challenge(self.test_user_id1)
        else:
            test_challenge = Challenge.all()\
                .filter("challenge_id =", challenge_id).get()
            if test_challenge is None:
                test_challenge = self.create_test_challenge(
                    self.test_user_id1, challenge_id)

        request_key = KeyStore.challenge_request_key()
        test_request = ChallengeRequest(
            inviter_id=inviter_id,
            challenge_id=test_challenge.challenge_id,
            invitee_id=invitee_id,
            status=status,
            file_info=file_info,
            parent=request_key)
        test_request.put()
        return test_request
 def initialize(self, request, response):
     super(BaseHandler, self).initialize(request, response)
     # initialise with secret key
     self.cookie_serializer = SecureCookieSerializer(SECRET)
Exemple #24
0
class PolicyTests(unittest.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # create a cookie serializer to emulate our sessions
        self.secure_cookie_serializer = SecureCookieSerializer('no-one-will-guess-kwsfs-secret-key')
        sessionConfig = {}
        sessionConfig['webapp2_extras.sessions'] = {
            'secret_key': 'no-one-will-guess-kwsfs-secret-key',
        }
        # redirect Jinja Env to a directory up
        Base.JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader('../html'),
            extensions=['jinja2.ext.autoescape'],
            autoescape=True)

        # prepare env with only needed URLs
        app = webapp2.WSGIApplication([
            ('/delinkPolicy', CoursePolicy.DelinkPolicyHandler),
            ('/deletePolicy', CoursePolicy.DeletePolicyHandler),
            ('/editPolicy', CoursePolicy.EditPolicyHandler),
            ('/linkPolicy', CoursePolicy.LinkPolicyHandler),
            ('/syllabusStepPoliciesEditor.html', CoursePolicy.CoursePolicyEditHandler),
            ('/policyLib.html', CoursePolicy.PolicyLibHandler)
        ], debug=True, config=sessionConfig)

        self.testapp = webtest.TestApp(app)

        # create a test user
        newUser = DBM.User(parent=DBM.UserKey("rock"),
                           username="******", password="******")
        newUser.put()

        # create a test syllabus
        self.syllabusKey = DBM.SyllabusKey("MyTestSyllabus")
        self.syllabusName = "MyTestSyllabus"
        newSyllabus = DBM.Syllabus(parent=self.syllabusKey, name=self.syllabusName,
                                   active=False)
        newSyllabus.put()

    def tearDown(self):
        self.testbed.deactivate()

    def testBadPolicyLinkSave(self):
        CoursePolicy.savePolicyToSyllabus("Good Header1", "", self.syllabusName)
        assert (len(DBM.Syllabus.query(ancestor=self.syllabusKey).fetch(1)[0].policies) == 0)
        CoursePolicy.savePolicyToSyllabus("", "Good Body", self.syllabusName)
        assert (len(DBM.Syllabus.query(ancestor=self.syllabusKey).fetch(1)[0].policies) == 0)
        CoursePolicy.savePolicyToSyllabus("", "", self.syllabusName)
        assert (len(DBM.Syllabus.query(ancestor=self.syllabusKey).fetch(1)[0].policies) == 0)

    def testGoodPolicyLinkSave(self):
        CoursePolicy.savePolicyToSyllabus("Good Header2", "Good Body", self.syllabusName)
        policies = DBM.Syllabus.query(ancestor=self.syllabusKey).fetch()[0].policies
        assert (len(policies) == 1)
        policy = DBM.Policy.query(ancestor=policies[0]).fetch()[0]
        assert (policy.head == "Good Header2")
        assert (policy.body == "Good Body")

    def testPolicyDelinkage(self):
        CoursePolicy.savePolicyToSyllabus("ToRemove", "Removal Body", self.syllabusName)
        beforeDelink = len(DBM.Syllabus.query(ancestor=self.syllabusKey).fetch(1)[0].policies)
        CoursePolicy.delinkPolicyFromSyllabus("ToRemove", self.syllabusName)
        afterDelink = len(DBM.Syllabus.query(ancestor=self.syllabusKey).fetch(1)[0].policies)
        assert (beforeDelink > afterDelink)

    def testPolicyDelete(self):
        CoursePolicy.savePolicy("ToDelete", "Removal Body")
        beforeDelete = len(DBM.Policy.query().fetch())
        CoursePolicy.deletePolicy("ToDelete")
        afterDelete = len(DBM.Policy.query().fetch())
        assert (beforeDelete > afterDelete)

    def testPolicySave(self):
        savedPolicy = CoursePolicy.savePolicy("CheckIfHere", "Removal Body")
        assert (len(DBM.Policy.query(ancestor=savedPolicy).fetch()) > 0)
        assert ((CoursePolicy.savePolicy("CheckIfHere", "Good Body")) == False)
        assert (len(DBM.Policy.query(ancestor=savedPolicy).fetch()) == 1)

    def testPolicyEdit(self):
        savedPolicy = CoursePolicy.savePolicy("EditThisGarbage", "FirstBody")
        CoursePolicy.editPolicy("EditThisGarbage", "SecondBody")
        assert (DBM.Policy.query(ancestor=savedPolicy).fetch()[0].body == "SecondBody")

    def testPolicyLinkage(self):
        savedPolicy = CoursePolicy.savePolicy("LinkThisGarbage", "FirstBody")
        beforeLink = len(DBM.Syllabus.query(ancestor=self.syllabusKey).fetch(1)[0].policies)
        CoursePolicy.linkPolicyToSyllabus("LinkThisGarbage", self.syllabusName)
        afterLink = len(DBM.Syllabus.query(ancestor=self.syllabusKey).fetch(1)[0].policies)
        assert (beforeLink < afterLink)

    def testSavePolicyCalls(self):
        # overwrite existing session values
        session = {'username': '******', 'currentPassword': '******', 'currentSyllabus': self.syllabusName}

        # prepare the session cookie to be used
        serialized = self.secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}

        # get the savePolicy page and submit information
        with mock.patch('jinja2.Template.render') as r2r:
            params = {'policyHeader': 'My New Head', 'policyBody': 'My New Body'}
            response = self.testapp.post("/syllabusStepPoliciesEditor.html", params, headers=headers)

            r2r.assert_not_called()

    def testGetPolicyStepCalls(self):
        # overwrite existing session values
        session = {'username': '******', 'currentPassword': '******', 'currentSyllabus': self.syllabusName}

        # expected policy time
        now = datetime.datetime.utcnow()
        now = datetime.date(now.year, now.month, now.day)

        # prepare the session cookie to be used
        serialized = self.secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}

        # get the savePolicy page and submit information
        with mock.patch('jinja2.Template.render') as r2r:
            response = self.testapp.get("/syllabusStepPoliciesEditor.html", headers=headers)

            r2r.assert_called_with({'progress': 6, 'importedPolicies': [], 'otherPolicies': []})

        with mock.patch('jinja2.Template.render') as r2r:
            CoursePolicy.savePolicyToSyllabus("LinkedTester", "my body", self.syllabusName)
            response = self.testapp.get("/syllabusStepPoliciesEditor.html", headers=headers)
            r2r.assert_called_with({'progress': 6,
                                    'importedPolicies': [
                                        DBM.Policy(key=ndb.Key('LinkedTester', 'policy header', 'Policy', 3),
                                                   body=u'my body',
                                                   head=u'LinkedTester',
                                                   updatedOn=now)],
                                    'otherPolicies': []})

        with mock.patch('jinja2.Template.render') as r2r:
            CoursePolicy.delinkPolicyFromSyllabus("LinkedTester", self.syllabusName)
            response = self.testapp.get("/syllabusStepPoliciesEditor.html", headers=headers)
            r2r.assert_called_with({'progress': 6,
                                    'importedPolicies': [],
                                    'otherPolicies': [
                                        DBM.Policy(key=ndb.Key('LinkedTester', 'policy header', 'Policy', 3),
                                                   body=u'my body',
                                                   head=u'LinkedTester',
                                                   updatedOn=now)]})

    def testGetPolicyLibCalls(self):
        # overwrite existing session values
        session = {'username': '******', 'currentPassword': '******'}

        # expected time
        now = datetime.datetime.utcnow()
        now = datetime.date(now.year, now.month, now.day)

        # prepare the session cookie to be used
        serialized = self.secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}

        # get the policyLib page and submit information
        with mock.patch('jinja2.Template.render') as r2r:
            response = self.testapp.get("/policyLib.html", headers=headers)

            r2r.assert_called_with({'editMode': False, 'policies': []})

        # ensure we can add policies and they'll show up in the library
        with mock.patch('jinja2.Template.render') as r2r:
            CoursePolicy.savePolicy("Stupid Policy", "No stupids")
            response = self.testapp.get("/policyLib.html", headers=headers)

            r2r.assert_called_with({'editMode': False,
                                    'policies': [
                                        DBM.Policy(key=ndb.Key('Stupid Policy', 'policy header', 'Policy', 3),
                                                   body=u'No stupids',
                                                   head=u'Stupid Policy',
                                                   updatedOn=now)
                                    ]})

        # ensure we can enter edit mode in the library1
        with mock.patch('jinja2.Template.render') as r2r:
            params = {'oldPolicyHead': 'Stupid Policy'}
            response = self.testapp.get("/editPolicy", params, headers=headers)

            r2r.assert_called_with({'oldPolicyBody': u'No stupids',
                                    'editMode': True,
                                    'oldPolicyHeader': u'Stupid Policy'})
Exemple #25
0
  def post(self, **kwargs):
    self.request.charset = 'utf-8'
    # Todo esto es para recuperar la session en funcion de un parametro del post 
    # que nos manda el flash swfupload
    cookie_name  = self.app.config['webapp2_extras.sessions']['cookie_name']
    secret_key   = self.app.config['webapp2_extras.sessions']['secret_key']
    raw_data     = str(self.request.POST[cookie_name])
    
    if raw_data[0] == "\"" and raw_data[-1] == "\"":
      raw_data = raw_data[1:][:-1]
    
    # ALTO HACK: no se por que carajo no funcion el urllib.unquote
    raw_data     = raw_data.decode('string_escape')
    self.session = SecureCookieSerializer(secret_key).deserialize(cookie_name, raw_data)
    
    # Hacemos lo que hacia el decorator
    if not self.is_logged:
      self.abort(500)
    
    property = self.mine_or_404(kwargs['key'])
  
    fs = self.request.POST['file']
    # Create the file
    file_name = files.blobstore.create(mime_type='image/jpg', _blobinfo_uploaded_filename=fs.filename)

    # Open the file and write to it
    img = images.Image(fs.file.getvalue())
    img.resize(width=800, height=600)

    with files.open(file_name, 'a') as f:
      f.write(img.execute_transforms(output_encoding=images.JPEG, quality=70))

    # Finalize the file. Do this before attempting to read it.
    files.finalize(file_name)

    # Get the file's blob key
    blob_key = files.blobstore.get_blob_key(file_name)

    # ------ BEGIN HACK -------- #
    # GAE BUG => http://code.google.com/p/googleappengine/issues/detail?id=5142
    for i in range(1,10):
      if not blob_key:
        time.sleep(0.05)
        blob_key = files.blobstore.get_blob_key(file_name)
      else:
        break
    
    if not blob_key:
      logging.error("no pude obtener el blob_key, hay un leak en el blobstore!")
      abort(500)
    # ------ END HACK -------- #
      
    imgfile = ImageFile()
    imgfile.title     = get_serving_url(blob_key)
    imgfile.file      = blob_key
    imgfile.filename  = fs.filename
    imgfile.realestate= property.realestate.key()
    imgfile.property  = db.Key(encoded=kwargs['key'])
    imgfile.put()
    
    #Update property
    if property.images_count:
      property.images_count = property.images_count + 1
    else:
      property.images_count = 1
      property.main_image_url   = imgfile.title
    
    result = property.save(build_index=False)
    # HACK: No mandamos a regenerar el PropertyIndex
    #if result != 'nones':
    #  taskqueue.add(url=self.url_for('property/update_index'), params={'key': str(property.key()),'action':result})
    
    return self.render_response('backend/includes/img_box.html', image=imgfile)
Exemple #26
0
import unittest
import webapp2
from webtest import TestApp
from config import config
from routes import routes
from webapp2_extras.securecookie import SecureCookieSerializer

app = webapp2.WSGIApplication(routes, config=config)
secure_cookie_serializer = SecureCookieSerializer(
    config['webapp2_extras.sessions']['secret_key'])


class Helper():
    """
    A helper to let TestCase make requests with pre-defined headers and csrf
    """
    def get(self, *args, **kwargs):
        if 'headers' not in kwargs:
            kwargs['headers'] = self.headers
        return self.app.get(*args, **kwargs)

    def post(self, url, params, *args, **kwargs):
        if 'headers' not in kwargs:
            kwargs['headers'] = self.headers
        if 'csrf' in kwargs and kwargs['csrf'] == True and self.csrf_data:
            if params and isinstance(
                    params, dict) and self.csrf_token_name not in params:
                params.update(**self.csrf_data)
            elif 'params' in kwargs and self.csrf_token_name not in params[
                    'kwargs']:
                kwargs['params'].update(**self.csrf_data)
Exemple #27
0
 def __init__(self):
     self.user_cookie = 'uc'
     self.secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
Exemple #28
0
class CalendarTests(unittest.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # create a cookie serializer to emulate our sessions
        self.secure_cookie_serializer = SecureCookieSerializer('no-one-will-guess-kwsfs-secret-key')
        sessionConfig = {}
        sessionConfig['webapp2_extras.sessions'] = {
            'secret_key': 'no-one-will-guess-kwsfs-secret-key',
        }
        # redirect Jinja Env to a directory up
        Base.JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader('../html'),
            extensions=['jinja2.ext.autoescape'],
            autoescape=True)

        # prepare env with only needed URLs
        app = webapp2.WSGIApplication([
            ('/syllabusStepCalendar.html', Calendar.CalendarHandler),
            ('/deleteCalendarEntry', Calendar.DeleteCalendarEntryHandler),
            ('/updateCalendarEntries', Calendar.UpdateCalendarEntriesHandler)
        ], debug=True, config=sessionConfig)

        self.testapp = webtest.TestApp(app)

        # TODO: replace this with a parser mock once the parser is integrated
        # This is used to verify functionality in tests that are not testing entry's results
        # Entry is tested separately, and these responses allows further test isolation
        self.start_date = date(2015, 8, 1)
        self.end_date = date(2016, 2, 1)
        self.days_of_week = [0, 2, 4]
        self.entry_response = Calendar.generateEntryRange(self.start_date, self.end_date, self.days_of_week)

        # create a test user
        newUser = DBM.User(parent=DBM.UserKey("rock"),
                           username="******", password="******")
        newUser.put()

        # create a test syllabus
        self.syllabusKey = DBM.SyllabusKey("MyTestSyllabus")
        self.syllabusName = "MyTestSyllabus"
        newSyllabus = DBM.Syllabus(parent=self.syllabusKey, name=self.syllabusName,
                                   active=False)
        newSyllabus.put()

    def tearDown(self):
        self.testbed.deactivate()

    def testGetCurrentCalendarWhenEmpty(self):
        expectedResult = DBM.Calendar(key=ndb.Key(self.syllabusName, 'calendar name', 'Calendar', 3),
                                      entries=self.entry_response,
                                      name=u'MyTestSyllabus')

        result = Calendar.getCurrentCalendar(self.syllabusName)
        assert (result == expectedResult)

    def testGetCurrentCalendarSyllabusLinkage(self):
        expectedResult = ndb.Key(self.syllabusName, 'calendar name', 'Calendar', 3)

        Calendar.getCurrentCalendar(self.syllabusName)

        result = DBM.Syllabus.query(ancestor=DBM.SyllabusKey(self.syllabusName)).fetch(1)[0].calendar

        assert (result == expectedResult)

    def testGetCurrentCalendarWhenPopulated(self):
        expectedResult = DBM.Calendar(key=ndb.Key(self.syllabusName, 'calendar name', 'Calendar', 3),
                                      entries=self.entry_response,
                                      name=u'MyTestSyllabus')

        Calendar.getCurrentCalendar(self.syllabusName)
        result = Calendar.getCurrentCalendar(self.syllabusName)
        assert (result == expectedResult)

    def testGetCalendarPageCallsWithEmptyCalendar(self):
        # overwrite existing session values
        session = {'username': '******', 'currentPassword': '******', 'currentSyllabus': self.syllabusName}

        # prepare the session cookie to be used
        serialized = self.secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}

        # get the savePolicy page and submit information
        with mock.patch('jinja2.Template.render') as r2r:
            response = self.testapp.get("/syllabusStepCalendar.html", headers=headers)

            r2r.assert_called_with(
                {'progress': 7, 'weekdayPrinter': Calendar.weekdayPrinter, 'date_events': self.entry_response})

    def testGenerateEntryRange(self):
        startDate = date(2015, 1, 5)
        endDate = date(2015, 1, 12)
        daysWeek = [1, 3]

        expectedResult = [DBM.DateEvent(date=date(2015, 1, 6), event="", homework=""),
                          DBM.DateEvent(date=date(2015, 1, 8), event="", homework="")]

        result = Calendar.generateEntryRange(startDate, endDate, daysWeek)

        assert (result == expectedResult)

    def testDeleteCalendarEntry(self):
        startDate = date(2015, 1, 14)
        endDate = date(2015, 1, 15)
        daysWeek = [2]

        # overwrite existing session values
        session = {'username': '******', 'currentPassword': '******', 'currentSyllabus': self.syllabusName}

        # prepare the session cookie to be used
        serialized = self.secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}

        calendar = Calendar.getCurrentCalendar(self.syllabusName)
        calendar.entries = Calendar.generateEntryRange(startDate, endDate, daysWeek)
        calendar.put()

        # there should be one entry in the calendar entries at this point
        assert (calendar.entries == [DBM.DateEvent(date=startDate, event="", homework="")])

        self.testapp.post("/deleteCalendarEntry?toRemove=2015-01-14", headers=headers)

        # get the savePolicy page and submit information
        with mock.patch('jinja2.Template.render') as r2r:
            result = self.testapp.get("/syllabusStepCalendar.html", headers=headers)

            # not there shouldn't be any entries in the current calendar
            r2r.assert_called_with({'progress': 7, 'weekdayPrinter': Calendar.weekdayPrinter, 'date_events': []})

    def testSaveCalendarEntry(self):
        startDate = date(2015, 1, 14)
        endDate = date(2015, 1, 15)
        daysWeek = [2]
        testHW = "my homework"
        testEvent = "my event"

        expectedDateEvent = [DBM.DateEvent(date=startDate, event=testEvent, homework=testHW)]

        # overwrite existing session values
        session = {'username': '******', 'currentPassword': '******', 'currentSyllabus': self.syllabusName}

        # prepare the session cookie to be used
        serialized = self.secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}

        calendar = Calendar.getCurrentCalendar(self.syllabusName)
        calendar.entries = Calendar.generateEntryRange(startDate, endDate, daysWeek)
        calendar.put()

        # there should be one entry in the calendar entries at this point
        assert (calendar.entries == [DBM.DateEvent(date=startDate, event="", homework="")])

        params = {'homework': [testHW], 'event': [testEvent]}
        self.testapp.post("/updateCalendarEntries", params=params, headers=headers)

        # get the savePolicy page and submit information
        with mock.patch('jinja2.Template.render') as r2r:
            result = self.testapp.get("/syllabusStepCalendar.html", headers=headers)

            # not there shouldn't be any entries in the current calendar
            r2r.assert_called_with(
                {'progress': 7, 'weekdayPrinter': Calendar.weekdayPrinter, 'date_events': expectedDateEvent})

    def testGetClassesAndDays(self):
        goodDate = date(2015, 1, 1)
        badDate = date(2015, 2, 1)

        # syllabus I want to hit
        toHit = DBM.Syllabus(active=True, course=DBM.Course(department="cs", course_number=101, section_number=1))
        cal1 = DBM.Calendar(entries=[DBM.DateEvent(date=goodDate, event="")], daysActive=[3])
        cal1.put()
        toHit.calendar = cal1.key
        toHit.put()
        # syllabus I don't want to hit
        toMiss = DBM.Syllabus(active=True, course=DBM.Course(department="ab", course_number=102, section_number=2))
        cal2 = DBM.Calendar(entries=[DBM.DateEvent(date=badDate, event="")], daysActive=[3])
        cal2.put()
        toMiss.calendar = cal2.key
        toMiss.put()

        result = Calendar.getClasssesAndDays(goodDate, goodDate)

        assert (result == [[toHit]])

    def testAddDate(self):
        goodDate = date(2015, 1, 1)
        calendarName = "testCal"
        calendar = DBM.Calendar(parent=DBM.CalendarKey(calendarName), name=calendarName,
                                entries=[DBM.DateEvent(date=goodDate, event="")], daysActive=[0])
        calendar.put()
        toAddDate = date(2015, 1, 2)

        Calendar.addDateToCalendar(calendarName, toAddDate)

        calendar = DBM.Calendar.query(ancestor=DBM.CalendarKey(calendarName)).fetch()[0]

        assert (len(calendar.entries) == 2)
        assert (calendar.entries[1].date == toAddDate)

    def testCopyCalendar(self):
        calendarA = "A calendar"
        calendarB = "B calendar"

        ADate = DBM.DateEvent(date=date(2015, 1, 1), event="thing", homework="read")
        BDate = DBM.DateEvent(date=date(2015, 2, 3))

        DBM.Calendar(parent=DBM.CalendarKey(calendarA), name=calendarA, entries=[ADate]).put()
        DBM.Calendar(parent=DBM.CalendarKey(calendarB), name=calendarB, entries=[BDate]).put()

        Calendar.copyCalendar(calendarA, calendarB)

        calendarB = DBM.Calendar.query(ancestor=DBM.CalendarKey(calendarB)).fetch(1)[0]
        assert (calendarB.entries[0].event == ADate.event)
        assert (calendarB.entries[0].homework == ADate.homework)

        if __name__ == '__main__':
            unittest.main()
Exemple #29
0
def gen_user_cookie():
    session = {'user': {'id': '123', 'googleId': '1'}}
    secure_cookie_serializer = SecureCookieSerializer('abcdefg')
    serialized = secure_cookie_serializer.serialize('session', session)
    return {'Cookie': 'session=%s' % serialized}
Exemple #30
0
class PolicyTests(unittest.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # create a cookie serializer to emulate our sessions
        self.secure_cookie_serializer = SecureCookieSerializer(
            'no-one-will-guess-kwsfs-secret-key')
        sessionConfig = {}
        sessionConfig['webapp2_extras.sessions'] = {
            'secret_key': 'no-one-will-guess-kwsfs-secret-key',
        }
        # redirect Jinja Env to a directory up
        Base.JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader('../html'),
            extensions=['jinja2.ext.autoescape'],
            autoescape=True)

        # prepare env with only needed URLs
        app = webapp2.WSGIApplication(
            [('/', Login.LoginHandler),
             ('/manage.html', Management.ManagementHandler)],
            debug=True,
            config=sessionConfig)

        self.testapp = webtest.TestApp(app)

    def tearDown(self):
        self.testbed.deactivate()

    def testGoodLogin(self):
        # overwrite existing session values
        session = {'username': '******', 'currentPassword': '******'}

        # prepare the session cookie to be used
        serialized = self.secure_cookie_serializer.serialize(
            'session', session)
        headers = {'Cookie': 'session=%s' % serialized}

        # specify good information to be passed to the login method
        params = {'username': '******', 'password': '******'}

        # get the login page and submit information
        self.testapp.get("/", headers=headers)
        response = self.testapp.post("/", params, headers=headers)

        # ensure user is redirected to management when a good login/pass is presented
        assert ("manage" in str(response))

    def testBadLogin(self):
        # overwrite existing session info and prepare cookie
        session = {'username': '******', 'currentPassword': '******'}
        serialized = self.secure_cookie_serializer.serialize(
            'session', session)
        headers = {'Cookie': 'session=%s' % serialized}
        # bad params to be passed to login method
        params = {'username': '******', 'password': '******'}
        # get login page and submit bad information
        self.testapp.get("/", headers=headers)
        response = self.testapp.post("/", params, headers=headers)
        # ensure user goes back to the login page when a bad user/pass is presented
        assert ("302" in str(response))