コード例 #1
0
    def get(self, router_name='REGION_PREFERENCE'):

        try:
            username = self.session['user']['name']
            user = cache.get_user(username)
            if not user:
                raise KeyError
                # TODO: use proper page redirects and redirect to login page.

        except KeyError:
            return self.response.write('You must be logged in!')

        router = None
        if router_name == 'DUMMY':
            router = DummyRouter()
        elif router_name == 'SIMPLE':
            router = SimpleRouter()
        elif router_name == "REGION_PREFERENCE":
            router = PreferenceRouter()
        else:
            result_str = "Specified router not found"
            logging.error(result_str)
            self.response.set_status(404)
            return self.response.write(result_str)

        result = router.get_next_observation_task(user)
        if result is None:
            self.response.set_status(404)
            return self.response.write("No uncompleted tasks available")

        return self.response.write(result.to_JSON())
        self.response.set_status(200)
コード例 #2
0
    def populate_user_session(self, user=None):
        """This should be called any time the session data needs to be updated.
        session['var'] = var should never be used, except in this function
        This function adds the below data to the data returned to the template.
        """

        if 'user' not in self.session and not user:
            logging.error("populate_user_session() - no user!")
            return
        elif not user:
            user = cache.get_user(self.session['user']['name'])

        self.session['user'] = {
            'admin': users.is_current_user_admin(),
            'avatar': user.gravatar(),
            'email': user.email,
            'key': user.key,  # .urlsafe(),
            'name': user.name,
            'token': user.token,
            'role': user.role
        }
        user_key = self.session['user']['key']

        self.session['journals'] = cache.get_journal_list(user_key)
        self.session['areas_list'] = cache.get_areas_list(
            user_key)  # TODO This list can be long and expensive.
        self.session['following_areas_list'] = cache.get_following_areas_list(
            user_key)  # used for basehandler menu.
コード例 #3
0
    def populate_user_session(self, user=None):
        """This should be called any time the session data needs to be updated.
        session['var'] = var should never be used, except in this function
        This function adds the below data to the data returned to the template.
        """

        if 'user' not in self.session and not user:
            logging.error("populate_user_session() - no user!")
            return
        elif not user:
            user = cache.get_user(self.session['user']['name'])

        self.session['user'] = {
            'admin': users.is_current_user_admin(),
            'avatar': user.gravatar(),
            'email': user.email,
            'key': user.key,  # .urlsafe(),
            'name': user.name,
            'token': user.token,
            'role': user.role
        }
        user_key = self.session['user']['key']

        self.session['journals'] = cache.get_journal_list(user_key)
        self.session['areas_list'] = cache.get_areas_list(user_key)  # TODO This list can be long and expensive.
        self.session['following_areas_list'] = cache.get_following_areas_list(user_key)  # used for basehandler menu.
コード例 #4
0
ファイル: auth.py プロジェクト: gray0018/tornado-storminton
def check_user(login, password):
    login_info = conn.get("SELECT entity_id FROM index_login WHERE login = %s",
                          login)
    if login_info:
        user_id = login_info["entity_id"]
        # user = nomagic._get_entity_by_id(user_id)
        user = get_user(user_id)
        if user["password"] == hashlib.sha1(password +
                                            user.get("salt", "")).hexdigest():
            return (user_id, user)
    return (None, None)
コード例 #5
0
ファイル: json.py プロジェクト: cristo92/growbots-recrutation
def get_followers_json(request, user_id):
    if not user_id:
        return JsonResponse({'message': 'You should provide user_id.'})

    frs_followers_ids = get_followers(user_id)
    if not frs_followers_ids:
        return JsonResponse({'message': 'Link has been expired.'})
    snd_followers_ids = []
    for uid in frs_followers_ids:
        snd_followers_ids += get_followers(uid)

    ret = defaultdict(int)
    for uid in snd_followers_ids:
        user = get_user(uid)
        if user:
            ret[user.screen_name] += 1

    return JsonResponse(ret)
コード例 #6
0
    def get(self):

        try:
            username = self.session['user']['name']
            user = cache.get_user(username)
            if not user:
                raise KeyError

        except KeyError:
            # TODO: use proper page redirects and redirect to login page.
            return self.response.write('You must be logged in as an administrator to seed glad cluster / case data')

        success, message = glad_data_seeder.seed_data(user)
        if success:
            self.response.set_status(200)
        else:
            self.response.set_status(400)

        return self.response.write(message)
コード例 #7
0
    def get(self):

        try:
            username = self.session['user']['name']
            user = cache.get_user(username)
            if not user:
                raise KeyError

        except KeyError:
            # TODO: use proper page redirects and redirect to login page.
            return self.response.write(
                'You must be logged in as an administrator to seed glad cluster / case data'
            )

        success, message = glad_data_seeder.seed_data(user)
        if success:
            self.response.set_status(200)
        else:
            self.response.set_status(400)

        return self.response.write(message)
コード例 #8
0
def feed(feed, token):
	if feed == 'activity':
		title = 'bunjil user activity'
		link = webapp2.uri_for('activity')
		subtitle = 'Recent activity by bunjil users'

		items = []
		for i in cache.get_activities():
			items.append(mk_item(
				'%s %s' %(i.user, i.get_action()),
				None,
				'%s %s' %(i.user, i.get_action()),
				i.key.id,
				i.date
			))

	elif feed == 'blog':
		title = 'bunjil blog'
		link = webapp2.uri_for('blog')
		subtitle = 'Recent bunjil blog posts'

		items = []
		for i in cache.get_blog_entries_page(1):
			items.append(mk_item(
				i.title,
				i.url,
				i.rendered,
				i.key.id,
				i.date
			))

	elif feed.startswith('user-'):
		username = feed.partition('-')[2]
		#user_key = db.Key.from_path('User', username)
		user = cache.get_user(username)

		if user.token == token:
			title = '%s\'s journalr feed' %username
			link = webapp2.uri_for('user', username=username)
			subtitle = 'Recent activity by followed by %s' %username

			items = []
			for i in cache.get_activities_follower(username):
				items.append(mk_item(
					'%s %s' %(i.user, i.get_action()),
					None,
					'%s %s' %(i.user, i.get_action()),
					i.key.id(),
					i.date
				))
		else:
			title = '%s activity feed' %username
			link = webapp2.uri_for('user', username=username)
			subtitle = 'Recent activity by %s' %username

			items = []
			for i in cache.get_activities(username=username):
				items.append(mk_item(
					'%s %s' %(i.user, i.get_action()),
					None,
					'%s %s' %(i.user, i.get_action()),
					i.key.id(),
					i.date
				))

	else:
		return ''

	d = {
		'title': title,
		'link': mk_link(link),
		'subtitle': subtitle,
		'updated': datetime.datetime.utcnow(),
		'items': items,
		'host': os.environ['HTTP_HOST'],
		'journal_url': mk_link(webapp2.uri_for('main')),
		'self_link': mk_link(webapp2.uri_for('feeds', feed=feed)),
	}

	return utils.render('atom.xml', d)
コード例 #9
0
ファイル: json.py プロジェクト: cristo92/growbots-recrutation
 def get_user_or_generate(uid):
     user = get_user(uid)
     if (user):
         snd_followers.append(user)
         return False
     return True
コード例 #10
0
    def post(self):
        """
            Accepts an observation task response

            Example request body
            {
                "vote_category": "FIRE",
                "case_id": 4573418615734272
            }
        :return:
        """
        try:
            username = self.session['user']['name']
            user = cache.get_user(username)
            if not user:
                raise KeyError

        except KeyError:
            self.response.set_status(401)
            return

        observation_task_response = json.loads(self.request.body)
        # TODO: use a json encoder and us a Decoding Error for the validation
        if observation_task_response['vote_category'] is not None:
            if observation_task_response['case_id'] is not None:
                # TODO: consider moving this check down into a JSON decoding function or BLL module
                if observation_task_response['vote_category'] in models.VOTE_CATEGORIES:
                    case = models.Case.get_by_id(id=observation_task_response['case_id'])
                    if case is None:
                        # TODO: consider moving this check down into a BLL module
                        self.response.set_status(404)
                        return

                    # Check if user has already completed task
                    if models.ObservationTaskResponse \
                            .query(models.ObservationTaskResponse.user == user.key,
                                   models.ObservationTaskResponse.case == case.key).fetch():
                        self.response.set_status(400)
                        return

                    observation_task_entity = models.ObservationTaskResponse(user=user.key,
                                                                             case=case.key,
                                                                             vote_category=
                                                                             observation_task_response['vote_category'],
                                                                             case_response=
                                                                             observation_task_response,
                                                                             task_duration_seconds=
                                                                             observation_task_response[
                                                                                 'task_duration_seconds'])
                    observation_task_entity.put()

                    vote_calculator = SimpleVoteCalculator()
                    case.votes.add_vote(observation_task_response['vote_category'],
                                        vote_calculator.get_weighted_vote(
                                            user, case, observation_task_response['task_duration_seconds']))
                    case.put()

                    case_manager = case_workflow.case_workflow_manager.CaseWorkflowManager()
                    case_manager.update_case_status(case)

                    self.response.set_status(201)

                    return

        self.reponse.set_status(400)
        return
コード例 #11
0
    def post(self):
        """
            Accepts an observation task response

            Example request body
            {
                "vote_category": "FIRE",
                "case_id": 4573418615734272
            }
        :return:
        """
        try:
            username = self.session['user']['name']
            user = cache.get_user(username)
            if not user:
                raise KeyError

        except KeyError:
            self.response.set_status(401)
            return

        observation_task_response = json.loads(self.request.body)
        # TODO: use a json encoder and us a Decoding Error for the validation
        if observation_task_response['vote_category'] is not None:
            if observation_task_response['case_id'] is not None:
                # TODO: consider moving this check down into a JSON decoding function or BLL module
                if observation_task_response['vote_category'] in models.VOTE_CATEGORIES:
                    case = models.Case.get_by_id(id=observation_task_response['case_id'])
                    if case is None:
                        # TODO: consider moving this check down into a BLL module
                        self.response.set_status(404)
                        return

                    # Check if user has already completed task
                    if models.ObservationTaskResponse \
                            .query(models.ObservationTaskResponse.user == user.key,
                                   models.ObservationTaskResponse.case == case.key).fetch():
                        self.response.set_status(400)
                        return

                    observation_task_entity = models.ObservationTaskResponse(user=user.key,
                                                                             case=case.key,
                                                                             vote_category=
                                                                             observation_task_response['vote_category'],
                                                                             case_response=
                                                                             observation_task_response,
                                                                             task_duration_seconds=
                                                                             observation_task_response[
                                                                                 'task_duration_seconds'])
                    observation_task_entity.put()

                    vote_calculator = SimpleVoteCalculator()
                    case.votes.add_vote(observation_task_response['vote_category'],
                                        vote_calculator.get_weighted_vote(
                                            user, case, observation_task_response['task_duration_seconds']))
                    case.put()

                    case_manager = case_workflow.case_workflow_manager.CaseWorkflowManager()
                    case_manager.update_case_status(case)

                    self.response.set_status(201)

                    return
コード例 #12
0
def feed(feed, token):
    if feed == 'activity':
        title = 'bunjil user activity'
        link = webapp2.uri_for('activity')
        subtitle = 'Recent activity by bunjil users'

        items = []
        for i in cache.get_activities():
            items.append(
                mk_item('%s %s' % (i.user, i.get_action()), None,
                        '%s %s' % (i.user, i.get_action()), i.key.id, i.date))

    elif feed == 'blog':
        title = 'bunjil blog'
        link = webapp2.uri_for('blog')
        subtitle = 'Recent bunjil blog posts'

        items = []
        for i in cache.get_blog_entries_page(1):
            items.append(mk_item(i.title, i.url, i.rendered, i.key.id, i.date))

    elif feed.startswith('user-'):
        username = feed.partition('-')[2]
        #user_key = db.Key.from_path('User', username)
        user = cache.get_user(username)

        if user.token == token:
            title = '%s\'s journalr feed' % username
            link = webapp2.uri_for('user', username=username)
            subtitle = 'Recent activity by followed by %s' % username

            items = []
            for i in cache.get_activities_follower(username):
                items.append(
                    mk_item('%s %s' % (i.user, i.get_action()), None,
                            '%s %s' % (i.user, i.get_action()), i.key.id(),
                            i.date))
        else:
            title = '%s activity feed' % username
            link = webapp2.uri_for('user', username=username)
            subtitle = 'Recent activity by %s' % username

            items = []
            for i in cache.get_activities(username=username):
                items.append(
                    mk_item('%s %s' % (i.user, i.get_action()), None,
                            '%s %s' % (i.user, i.get_action()), i.key.id(),
                            i.date))

    else:
        return ''

    d = {
        'title': title,
        'link': mk_link(link),
        'subtitle': subtitle,
        'updated': datetime.datetime.utcnow(),
        'items': items,
        'host': os.environ['HTTP_HOST'],
        'journal_url': mk_link(webapp2.uri_for('main')),
        'self_link': mk_link(webapp2.uri_for('feeds', feed=feed)),
    }

    return utils.render('atom.xml', d)