Esempio n. 1
0
	def on_post(self, req, resp):
		user = req.context['user']

		# Vytvoret novou trofej mohou jen orgove
		if (not user.is_logged_in()) or (not user.is_org()):
			req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Přidání trofeje může provést pouze organizátor.' } ] }
			resp.status = falcon.HTTP_400
			return

		data = json.loads(req.stream.read())['achievement']

		achievement = model.Achievement(
			title = data['title'],
			picture = data['picture'],
			description = data['description'],
		)
		if not data['persistent']: achievement.year = req.context['year']
		else: achievement.year = None

		try:
			session.add(achievement)
			session.commit()
		except SQLAlchemyError:
			session.rollback()
			raise

		req.context['result'] = { 'achievement': util.achievement.to_json(achievement) }

		session.close()
Esempio n. 2
0
	def on_delete(self, req, resp, id):
		try:
			user = req.context['user']

			# Vlnu mohou smazat jen admini
			if (not user.is_logged_in()) or (not user.is_admin()):
				resp.status = falcon.HTTP_400
				return

			wave = session.query(model.Wave).get(id)
			if wave is None:
				resp.status = falcon.HTTP_404
				return

			# Smazat lze jen neprazdnou vlnu.
			tasks_cnt = session.query(model.Task).filter(model.Task.wave == wave.id).count()
			if tasks_cnt > 0:
				resp.status = falcon.HTTP_403
				return

			session.delete(wave)
			session.commit()
			req.context['result'] = {}
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 3
0
	def on_get(self, req, resp, id):
		try:
			user = req.context['user']

			# Kontrola opravneni
			if (not user.is_logged_in()) or (not user.is_org()):
				resp.status = falcon.HTTP_400
				return

			status = {}

			task = session.query(model.Task).get(id)
			if task is None:
				resp.status = falcon.HTTP_404
				return

			log = None
			if os.path.isfile(util.admin.taskDeploy.LOGFILE):
				with open(util.admin.taskDeploy.LOGFILE, 'r') as f:
					data = f.readlines()
				if re.search(r"^(\d*)", data[0]).group(1) == str(id): log = ''.join(data[1:])

			status = {
				'id': task.id,
				'log': log,
				'deploy_date': task.deploy_date.isoformat() if task.deploy_date else None,
				'deploy_status': task.deploy_status
			}

			req.context['result'] = status
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 4
0
	def on_post(self, req, resp):
		try:
			user = req.context['user']
			year = req.context['year']

			# Vytvorit novou vlnu mohou jen admini.
			if (not user.is_logged_in()) or (not user.is_admin()):
				resp.status = falcon.HTTP_400
				return

			data = json.loads(req.stream.read())['wave']

			wave = model.Wave(
				year = year,
				index = data['index'],
				caption = data['caption'],
				garant = data['garant'],
				time_published = data['time_published']
			)

			session.add(wave)
			session.commit()
			req.context['result'] = { 'wave': util.wave.to_json(wave) }
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 5
0
	def on_put(self, req, resp, id):
		try:
			user = req.context['user']

			if (not user.is_logged_in()) or (not user.is_org()):
				resp.status = falcon.HTTP_400
				return

			data = json.loads(req.stream.read())['wave']

			wave = session.query(model.Wave).get(id)
			if wave is None:
				resp.status = falcon.HTTP_404
				return

			# Menit vlnu muze jen ADMIN nebo aktualni GARANT vlny.
			if not user.is_admin() and user.id != wave.garant:
				resp.status = falcon.HTTP_400
				return

			wave.index = data['index']
			wave.caption = data['caption']
			if data['time_published']: wave.time_published = data['time_published']
			wave.garant = data['garant']

			session.commit()
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()

		self.on_get(req, resp, id)
Esempio n. 6
0
	def on_post(self, req, resp):
		email = json.loads(req.stream.read())['email']
		try:
			user = session.query(model.User).filter(model.User.email == email).first()
		except SQLAlchemyError:
			session.rollback()
			raise

		if not user:
			resp.status = falcon.HTTP_400
			req.context['result'] = { 'result': 'error' }
			return

		new_password = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(8))

		user.password = auth.get_hashed_password(new_password)

		try:
			session.add(user)
			session.commit()
		except SQLAlchemyError:
			session.rollback()
			raise

		try:
			util.mail.send(user.email, '[KSI] Nové heslo', u'Ahoj,<br/>na základě tvé žádosti ti bylo vygenerováno nové heslo: %s<br/><br/>KSI' % new_password)
		except SQLAlchemyError:
			exc_type, exc_value, exc_traceback = sys.exc_info()
			traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr)

		session.close()

		req.context['result'] = { 'result': 'ok' }
Esempio n. 7
0
	def on_delete(self, req, resp, id):
		user = req.context['user']
		try:
			user_db = session.query(model.User).get(id)
		except SQLAlchemyError:
			session.rollback()
			raise

		if (not user.is_logged_in()) or (not user.is_admin()):
			resp.status = falcon.HTTP_400
			return

		if not user_db:
			resp.status = falcon.HTTP_404
			return

		profile = session.query(model.Profile).get(id)

		try:
			if profile: session.delete(profile)
			session.delete(user_db)
			session.commit()
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()

		req.context['result'] = {}
Esempio n. 8
0
	def on_get(self, req, resp):
		try:
			user = req.context['user']
			year = req.context['year']

			if (not user.is_logged_in()) or (not user.is_org()):
				req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Přístup k opravovátku mají pouze organizátoři.' } ] }
				resp.status = falcon.HTTP_400
				return

			tasks = session.query(model.Task).\
				join(model.Wave, model.Wave.id == model.Task.wave).\
				filter(model.Wave.year == year).all()

			waves = session.query(model.Wave).\
				filter(model.Wave.year == year).\
				join(model.Task, model.Task.wave == model.Wave.id).all()

			users = session.query(model.User)
			users = set(util.user.active_in_year(users, year).all())
			users |= set(session.query(model.User).\
				join(model.Task, model.Task.author == model.User.id).all())

			req.context['result'] = {
				'correctionsInfos': [ util.correctionInfo.task_to_json(task) for task in tasks ],
				'waves': [ util.wave.to_json(wave) for wave in waves ],
				'users': [ util.correctionInfo.user_to_json(user) for user in users ]
			}
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 9
0
	def _process_achievements(self, corr):
		a_old = util.achievement.ids_list(util.achievement.per_task(corr['user'], corr['task_id']))
		a_new = corr['achievements']
		if a_old != a_new:
			# achievementy se nerovnaji -> proste smazeme vsechny dosavadni a pridame do db ty, ktere nam prisly
			for a_id in a_old:
				try:
					ach = session.query(model.UserAchievement).get((corr['user'], a_id))
					if ach.task_id == corr['task_id']:
						session.delete(ach)
					session.commit()
				except:
					session.rollback()
					raise

			for a_id in a_new:
				try:
					ua = model.UserAchievement(user_id=corr['user'], achievement_id=a_id, task_id=corr['task_id'])
					session.add(ua)
					session.commit()
				except:
					session.rollback()
					raise
				finally:
					session.close()
Esempio n. 10
0
	def on_delete(self, req, resp, id):
		try:
			user = req.context['user']

			if (not user.is_logged_in()) or (not user.is_admin()):
				resp.status = falcon.HTTP_400
				return

			year = session.query(model.Year).get(id)
			if year is None:
				resp.status = falcon.HTTP_404
				return

			# Odstranit lze jen neprazdny rocnik
			waves_cnt = session.query(model.Wave).filter(model.Wave.year == year.id).count()
			if waves_cnt > 0:
				resp.status = falcon.HTTP_403
				return

			session.delete(year)
			session.commit()
			req.context['result'] = {}
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 11
0
	def on_post(self, req, resp):
		try:
			user = req.context['user']

			# Vytvoret novy rocnik mohou jen ADMINI
			if (not user.is_logged_in()) or (not user.is_admin()):
				resp.status = falcon.HTTP_400
				return

			data = json.loads(req.stream.read())['year']

			year = model.Year(
				id = data['index'],
				year = data['year'],
				sealed = data['sealed'] if data['sealed'] else False,
				point_pad = data['point_pad']
			)

			session.add(year)
			session.commit()

			if 'active_orgs' in data:
				for user_id in data['active_orgs']:
					org = model.ActiveOrg(org=user_id, year=year.id)
					session.add(org)

			session.commit()

			req.context['result'] = { 'year': util.year.to_json(year) }

		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 12
0
	def on_post(self, req, resp):
		try:
			user = req.context['user']
			if not user.is_logged_in():
				resp.status = falcon.HTTP_400
				return

			if req.context['year_obj'].sealed:
				resp.status = falcon.HTTP_403
				req.context['result'] = { 'errors': [ { 'status': '403', 'title': 'Forbidden', 'detail': u'Ročník zapečetěn.' } ] }
				return

			data = json.loads(req.stream.read())
			pblic = data['thread']['public'] if data['thread'].has_key('public') else True

			thread = model.Thread(title=data['thread']['title'], public=pblic, year = req.context['year'])
			session.add(thread)
			session.commit()

			req.context['result'] = { 'thread': util.thread.to_json(thread, user.id) }
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 13
0
	def on_delete(self, req, resp, id):
		user = req.context['user']
		try:
			achievement = session.query(model.Achievement).get(id)
		except SQLAlchemyError:
			session.rollback()
			raise

		if (not user.is_logged_in()) or (not user.is_admin()):
			req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Smazání trofeje může provést pouze administrátor.' } ] }
			resp.status = falcon.HTTP_400
			return

		if not achievement:
			req.context['result'] = { 'errors': [ { 'status': '404', 'title': 'Not Found', 'detail': u'Trofej s tímto ID neexsituje.' } ] }
			resp.status = falcon.HTTP_404
			return

		try:
			session.delete(achievement)
			session.commit()
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()

		req.context['result'] = {}
Esempio n. 14
0
    def on_delete(self, req, resp, id):
        user = req.context['user']
        try:
            user_db = session.query(model.User).get(id)
        except SQLAlchemyError:
            session.rollback()
            raise

        if (not user.is_logged_in()) or (not user.is_admin()):
            resp.status = falcon.HTTP_400
            return

        if not user_db:
            resp.status = falcon.HTTP_404
            return

        profile = session.query(model.Profile).get(id)

        try:
            if profile:
                session.delete(profile)
            session.delete(user_db)
            session.commit()
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()

        req.context['result'] = {}
Esempio n. 15
0
    def on_get(self, req, resp, id):
        user = req.context['user']

        if not user.is_logged_in():
            req.context['result'] = {
                'errors': [{
                    'status': '404',
                    'title': 'Not Found',
                    'detail': 'Modul s tímto ID neexistuje.'
                }]
            }
            resp.status = falcon.HTTP_400
            return

        try:
            module = session.query(model.Module).get(id)
            if module is None:
                resp.status = falcon.HTTP_404
            else:
                task = session.query(model.Task).get(module.task)
                if util.task.status(task, user) != util.TaskStatus.LOCKED:
                    req.context['result'] = {
                        'module': util.module.to_json(module, user.id)
                    }
                else:
                    resp.status = falcon.HTTP_403
        except SQLAlchemyError:
            session.rollback()
            raise
Esempio n. 16
0
	def on_get(self, req, resp):
		try:
			user = req.context['user']
			wave = req.get_param_as_int('wave')

			# Zobrazovat task_admin mohou jen orgove
			if (not user.is_logged_in()) or (not user.is_org()):
				req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Přístup odepřen.' } ] }
				resp.status = falcon.HTTP_400
				return

			tasks = session.query(model.Task, model.Wave).join(model.Wave, model.Task.wave == model.Wave.id)
			if wave is None:
				tasks = tasks.filter(model.Wave.year == req.context['year'])
			else:
				tasks = tasks.filter(model.Wave.id == wave)
			tasks = tasks.all()

			max_points = util.task.max_points_dict()

			req.context['result'] = { 'atasks': [ util.task.admin_to_json(task.Task, max_points[task.Task.id]) for task in tasks ] }
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 17
0
	def on_post(self, req, resp, id):
		try:
			user = req.context['user']

			# Kontrola existence ulohy
			task = session.query(model.Task).get(id)
			if task is None:
				req.context['result'] = 'Neexistujici uloha'
				resp.status = falcon.HTTP_404
				return

			# Kontrola existence git_branch a git_path
			if (task.git_path is None) or (task.git_branch is None):
				req.context['result'] = 'Uloha nema zadanou gitovskou vetev nebo adresar'
				resp.status = falcon.HTTP_400
				return

			if task.git_branch == "master":
				req.context['result'] = 'Uloha je j*z ve vetvi master'
				resp.status = falcon.HTTP_400
				return

			wave = session.query(model.Wave).get(task.wave)

			# Merge mohou provadet pouze administratori a garant vlny
			if (not user.is_logged_in()) or ((not user.is_admin()) and (user.id != wave.garant)):
				req.context['result'] = 'Nedostatecna opravneni'
				resp.status = falcon.HTTP_400
				return

			# Kontrola zamku
			lock = util.lock.git_locked()
			if lock:
				req.context['result'] = 'GIT uzamcen zámkem '+lock + "\nNekdo momentalne provadi akci s gitem, opakujte prosim akci za 20 sekund."
				resp.status = falcon.HTTP_409
				return

			try:
				mergeLock = LockFile(util.admin.taskMerge.LOCKFILE)
				mergeLock.acquire(60) # Timeout zamku je 1 minuta

				# Fetch repozitare
				repo = git.Repo(util.git.GIT_SEMINAR_PATH)

				if task.git_branch in repo.heads:
					# Cannot delete branch we are on
					repo.git.checkout("master")
					repo.git.branch('-D', task.git_branch)

				task.git_branch = 'master'

				session.commit()
				resp.status = falcon.HTTP_200
			finally:
				mergeLock.release()
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 18
0
def upsert_contributors(o_data, r_data):
    organization = session.query(Organization).filter(
        Organization.id == o_data.id).first()

    contributors = set()
    for r_item in r_data:
        if not r_item.fork:
            c_data = r_item.get_contributors()
            repo_contributors = []
            for c_item in c_data:
                check_rate_limit(c_item)
                contributor = p_formatter(c_item)
                contributor = upsert(model=Person,
                                     unique_key='id',
                                     item=contributor)
                contributors.add(contributor)
                repo_contributors.append(contributor)

            repository = session.query(Repository).filter(
                Repository.id == r_item.id).first()
            repository.contributors = repo_contributors
            session.add(repository)
            session.commit()

    contributors = list(contributors)
    organization.contributors = contributors

    try:
        session.add(organization)
        session.commit()
    except:
        session.rollback()
Esempio n. 19
0
def updateUser():
    try:
        data = request.json
        print(data["formInput"])
        if data["formInput"]["name"] != "" and data["formInput"][
                "username"] != "" and data["formInput"][
                    "password"] != "" and data["formInput"]["access"] != "":
            name = data["formInput"]["name"]
            username = data["formInput"]["username"]
            password = data["formInput"]["password"]
            access = data["formInput"]["access"]
            try:
                user = session.query(Users).filter(
                    Users.username == username).one()
                user.name = name
                user.username = username
                user.password = password
                user.access = access
                session.commit()
            except Exception as e:
                session.rollback()
                print(e)
            return jsonify({"msg": "success"})
        else:
            return jsonify({"msg": "Failed"})
    except Exception as e:
        print(e)
        return jsonify({"msg": "Failed"})
Esempio n. 20
0
    def on_delete(self, req, resp, id):
        """Delete feedback"""
        try:
            user = req.context['user']

            if not user.is_logged_in():
                resp.status = falcon.HTTP_400
                return

            feedback = session.query(model.Feedback).get((user.get_id(), id))
            if feedback is None:
                req.context['result'] = {
                    'errors': [{
                        'status': '404',
                        'title': 'Not found',
                        'detail': 'Feedback s tímto ID neexistuje.'
                    }]
                }
                resp.status = falcon.HTTP_404
                return

            session.delete(feedback)
            session.commit()
            req.context['result'] = {}

        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 21
0
    def on_post(self, req, resp):
        try:
            user = req.context['user']

            # Vytvoret novy rocnik mohou jen ADMINI
            if (not user.is_logged_in()) or (not user.is_admin()):
                resp.status = falcon.HTTP_400
                return

            data = json.loads(req.stream.read().decode('utf-8'))['year']

            year = model.Year(
                id=data['index'],
                year=data['year'],
                sealed=data['sealed'] if data['sealed'] else False,
                point_pad=data['point_pad'])

            session.add(year)
            session.commit()

            if 'active_orgs' in data:
                for user_id in data['active_orgs']:
                    org = model.ActiveOrg(org=user_id, year=year.id)
                    session.add(org)

            session.commit()

            req.context['result'] = {'year': util.year.to_json(year)}

        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 22
0
    def on_get(self, req, resp, id):
        try:
            user = req.context['user']
            user_id = req.context['user'].get_id()\
                if req.context['user'].is_logged_in() else None

            post = session.query(model.Post).get(id)

            if post is None:
                resp.status = falcon.HTTP_404
                return

            thread = session.query(model.Thread).get(post.thread)

            if thread is None:
                resp.status = falcon.HTTP_404
                return

            # Kontrola pristupu k prispevkum:
            # a) K prispevkum v eval vlakne mohou pristoupit jen orgove a
            #    jeden resitel
            # b) K ostatnim neverejnym prispevkum mohou pristoupit jen orgove.
            if (not thread.public and
                ((not user.is_logged_in()) or
                 (not user.is_org()
                  and not util.thread.is_eval_thread(user.id, thread.id)))):
                resp.status = falcon.HTTP_400
                return

            req.context['result'] = {'post': util.post.to_json(post, user_id)}
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 23
0
    def put(self, id):
        team = session.query(Team).filter(Team.id == id).first()
        if not team:
            abort(404, message="Team {} does not exist".format(id))
        error_message = None
        try:
            # Processing input arguments
            parser.add_argument('name', type=str, required=True, trim=True)
            parsed_args = parser.parse_args()

            # Updating team instance
            team.name = parsed_args['name'] if parsed_args['name'] else team.name

            # Saving to DB
            session.merge(team)
            session.commit()
        except IntegrityError:
            error_message = 'Faulty or a duplicate record'
        except ValueError as e:
            error_message = str(e)
        except Exception as e:
            print(str(e))
            error_message = 'Bad request'
        finally:
            if error_message:
                session.rollback()
                abort(400, message='Unable to create team record: ' + error_message)
            else:
                return team, 202
Esempio n. 24
0
    def post(self):
        error_message = None
        try:
            # Processing input arguments
            parser.add_argument('name', type=str, required=True, trim=True)
            parsed_args = parser.parse_args()

            # Creating team instance
            team = Team(
                created=datetime.datetime.utcnow(),
                name=parsed_args['name'],
                params=parsed_args['params'],
                meta=parsed_args['meta']
            )

            # Saving to DB
            session.add(team)
            session.commit()
        except IntegrityError:
            error_message = 'Faulty or a duplicate record'
        except ValueError as e:
            error_message = str(e)
        except Exception as e:
            print(str(e))
            error_message = 'Bad request'
        finally:
            if error_message:
                session.rollback()
                abort(400, message='Unable to create team record: ' + error_message)
            else:
                return team, 201
Esempio n. 25
0
async def update_todo(item: Todo):
    todo = session.query(TodosTable).\
        filter(TodosTable.id == item.id).filter(
            TodosTable.user_id == item.user_id).first()

    if item.place:
        todo.place = item.place

    if item.url:
        todo.url = item.url

    if item.memo:
        todo.memo = item.memo

    if item.start_date:
        todo.start_date = item.start_date

    if item.end_date:
        todo.end_date = item.end_date

    if item.title:
        todo.title = item.title

    try:
        session.commit()
    except:
        session.rollback()
        raise

    return {}
Esempio n. 26
0
async def create_todo(item: Todo):
    todo = TodosTable()
    todo.user_id = item.user_id
    todo.title = item.title

    if item.place:
        todo.place = item.place

    if item.url:
        todo.url = item.url

    if item.memo:
        todo.memo = item.memo

    if item.start_date:
        todo.start_date = item.start_date

    if item.end_date:
        todo.end_date = item.end_date

    try:
        session.add(todo)
        session.commit()
    except:
        session.rollback()
        raise

    # 作成したtodoのidを返してあげる
    latest = session.query(TodosTable).\
        filter(TodosTable.user_id == todo.user_id).order_by(
            TodosTable.id.desc()).first()

    return {'id': latest.id}
Esempio n. 27
0
def perform_action(module, user, action):
    action = action.split(' ')[1:]
    if len(action) < 1:
        return

    if action[0] == "add_achievement":
        achievement_id = int(action[1])
        already_done = session.query(model.UserAchievement).\
            filter(model.UserAchievement.user_id == user.id,
                   model.UserAchievement.achievement_id == achievement_id).\
            first()

        if already_done:
            return

        achievement = model.UserAchievement(user_id=user.id,
                                            achievement_id=achievement_id,
                                            task_id=module.task)

        try:
            session.add(achievement)
            session.commit()
        except BaseException:
            session.rollback()
            raise
Esempio n. 28
0
    def on_post(self, req, resp, id):
        """
        Params:
            - ?token=auth_token
            - ?type=eval|response|ksi|events|all
        """
        try:
            resp.content_type = 'text/html; charset=utf-8'

            notify = util.user_notify.get(id)
            if req.get_param('token') != notify.auth_token:
                resp.body = 'Chyba 403: špatný autorizační token!'
                resp.status = falcon.HTTP_403
                return

            valid_types = ['eval', 'response', 'ksi', 'events', 'all']
            u_type = req.get_param('type')

            if u_type not in valid_types:
                resp.body = 'Chyba 400: neplatný typ zprávy!'
                resp.status = falcon.HTTP_400
                return

            if u_type == 'eval':
                notify.notify_eval = False
            elif u_type == 'response':
                notify.notify_response = False
            elif u_type == 'ksi':
                notify.notify_ksi = False
            elif u_type == 'events':
                notify.notify_events = False
            elif u_type == 'all':
                notify.notify_eval = False
                notify.notify_response = False
                notify.notify_ksi = False
                notify.notify_events = False

            session.commit()
            resp.body = 'Úspěšně odhlášeno.'

            resp.body += '<br><br>Aktuální stav notifikací pro adresu: %s:' % (
                session.query(model.User).get(id).email)
            resp.body += '<ul>'
            resp.body += '<li>Notifikovat o opravení mého řešení: %s.</li>' % (
                'ano' if notify.notify_eval else 'ne')
            resp.body += '<li>Notifikovat o reakci na můj komentář: %s.</li>' % (
                'ano' if notify.notify_response else 'ne')
            resp.body += '<li>Notifikovat o průběhu semináře (vydání nové vlny, ...): %s.</li>' % (
                'ano' if notify.notify_ksi else 'ne')
            resp.body += '<li>Zasílat pozvánky na spřátelené akce (InterLoS, InterSoB, ...): %s.</li>' % (
                'ano' if notify.notify_events else 'ne')
            resp.body += '</ul>'
            resp.body += 'Další změny je možné provést v nastavení tvého profilu na KSI webu.'

        except SQLAlchemyError:
            resp.body = 'Chyba 500: nastala výjimka, kontaktuj orga!'
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 29
0
def addUser():
    try:
        data = request.json
        print(data["formInput"])
        if data["formInput"]["name"] != "" and data["formInput"][
                "username"] != "" and data["formInput"][
                    "password"] != "" and data["formInput"]["access"] != "":
            name = data["formInput"]["name"]
            username = data["formInput"]["username"]
            password = data["formInput"]["password"]
            access = data["formInput"]["access"]
            try:
                user = Users(name=name,
                             username=username,
                             password=password,
                             access=access)
                session.add(user)
                session.commit()
            except Exception as e:
                session.rollback()
                print(e)
            return jsonify({"msg": "success"})
        else:
            return jsonify({"msg": "Failed"})
    except Exception as e:
        print(e)
        return jsonify({"msg": "Failed"})
Esempio n. 30
0
    def on_post(self, req, resp):
        try:
            user = req.context['user']
            year = req.context['year']

            # Vytvorit novou vlnu mohou jen admini.
            if (not user.is_logged_in()) or (not user.is_admin()):
                resp.status = falcon.HTTP_400
                return

            data = json.loads(req.stream.read().decode('utf-8'))['wave']

            wave = model.Wave(year=year,
                              index=data['index'],
                              caption=data['caption'],
                              garant=data['garant'],
                              time_published=dateutil.parser.parse(
                                  data['time_published']))

            session.add(wave)
            session.commit()
            req.context['result'] = {'wave': util.wave.to_json(wave)}
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 31
0
def todayWord():
    if current_user.task is None:
        current_user.task=Task(user=current_user,wordNumPerDay=0)
        session.commit()
    if session.query(HistoryTask).filter(HistoryTask.user==current_user,HistoryTask.taskTime==date.today()).count()==0:
        history=HistoryTask(userId=current_user.id,taskTime=date.today(),plan=current_user.task.wordNumPerDay,complete=0)
        session.add(history)
        session.commit()
    else:
        history=session.query(HistoryTask).filter(HistoryTask.user==current_user,HistoryTask.taskTime==date.today()).first()
    need=history.plan-history.complete
    # print(need)
    count=session.query(Word).filter(Word.progresses.any(and_(Progress.progress<5,Progress.userId==current_user.id))).count()
    # print(count)
    try:
        if count<need:
            extendProgressCount=extendProgress(current_user, 1000)
            if count==0 and extendProgressCount.rowcount==0:
                return error({'message':'您已背完所有单词!'})
        if need<=0:
            return success({'words':[]})
        progresses=session.query(Progress).filter(Progress.userId==current_user.id,Progress.progress<5).order_by(Progress.progress).limit(need).all()
        # print(progresses)
        words=[progress.word.asDict() for progress in progresses]
        return success({'words':words})
    except Exception as e:
        print(e)
        import traceback
        traceback.print_exc()
        session.rollback()
        return error({'message':"抱歉出现错误,请发送详细内容到[email protected]"})
Esempio n. 32
0
    def on_delete(self, req, resp, id):
        try:
            user = req.context['user']

            # Vlnu mohou smazat jen admini
            if (not user.is_logged_in()) or (not user.is_admin()):
                resp.status = falcon.HTTP_400
                return

            wave = session.query(model.Wave).get(id)
            if wave is None:
                resp.status = falcon.HTTP_404
                return

            # Smazat lze jen neprazdnou vlnu.
            tasks_cnt = session.query(model.Task).\
                filter(model.Task.wave == wave.id).\
                count()

            if tasks_cnt > 0:
                resp.status = falcon.HTTP_403
                return

            session.delete(wave)
            session.commit()
            req.context['result'] = {}

        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 33
0
def recite():
    wordId=request.form['wordId']
    remember=request.form['remember']
    try:
        if session.query(Progress).filter(Progress.user==current_user,Progress.wordId==wordId).count()==0:
            progress=Progress(user=current_user,wordId=wordId)
            session.add(progress)
        else:
            progress=session.query(Progress).filter(Progress.user==current_user,Progress.wordId==wordId).first()

        if session.query(HistoryTask).filter(HistoryTask.user==current_user,HistoryTask.taskTime==date.today()).count()==0:
            history=HistoryTask(userId=current_user.id,taskTime=date.today(),plan=current_user.task.wordNumPerDay,complete=0)
            session.add(history)
        else:
            history=session.query(HistoryTask).filter(HistoryTask.user==current_user,HistoryTask.taskTime==date.today()).first()

        if remember:
            progress.progress=progress.progress+1
            history.complete=history.complete+1
        else:
            progress.progress=progress.progress-1
            if progress.progress<-5:
                progress.progress=-5
        session.commit()
        return success({})
    except Exception as e:
        # print(e)
        session.rollback()
        return error({'message':"抱歉出现错误,请发送详细内容到[email protected]"})
Esempio n. 34
0
    def on_delete(self, req, resp, id):
        try:
            user = req.context['user']

            if (not user.is_logged_in()) or (not user.is_admin()):
                resp.status = falcon.HTTP_400
                return

            year = session.query(model.Year).get(id)
            if year is None:
                resp.status = falcon.HTTP_404
                return

            # Odstranit lze jen neprazdny rocnik
            waves_cnt = session.query(model.Wave).\
                filter(model.Wave.year == year.id).\
                count()

            if waves_cnt > 0:
                resp.status = falcon.HTTP_403
                return

            session.delete(year)
            session.commit()
            req.context['result'] = {}

        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 35
0
    def _auth(self, req, resp):
        username = req.get_param('username')
        password = req.get_param('password')

        try:
            challenge = session.query(
                model.User).filter(model.User.email == username).first()

            if username and password and challenge:
                if not challenge.enabled:
                    req.context['result'] = {'error': Error.ACCOUNT_DISABLED}
                    resp.status = falcon.HTTP_400
                    return

                if auth.check_password(password, challenge.password):
                    req.context['result'] = auth.OAuth2Token(challenge.id).data
                else:
                    req.context['result'] = {
                        'error': Error.UNAUTHORIZED_CLIENT
                    }
                    resp.status = falcon.HTTP_400
            else:
                req.context['result'] = {'error': Error.UNAUTHORIZED_CLIENT}
                resp.status = falcon.HTTP_400
        except SQLAlchemyError:
            session.rollback()
            raise
Esempio n. 36
0
	def on_post(self, req, resp, id):
		try:
			user = req.context['user']
			if not user.is_logged_in():
				resp.status = falcon.HTTP_400
				return

			data = json.loads(req.stream.read())['content']
			module = session.query(model.Module).get(id)

			if not module:
				resp.status = falcon.HTTP_400
				return

			task_status = util.task.status(session.query(model.Task).get(module.task), user)

			if task_status == util.TaskStatus.LOCKED:
				resp.status = falcon.HTTP_400
				return

			req.context['result'] = util.programming.run(module, user.id, data)
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 37
0
    def on_get(self, req, resp, id):
        try:
            user = req.context['user']
            task = session.query(model.Task).get(id)

            # task_admin mohou ziskat jen orgove
            if (not user.is_logged_in()) or (not user.is_org()):
                req.context['result'] = {
                    'errors': [{
                        'status': '401',
                        'title': 'Unauthorized',
                        'detail': 'Přístup odepřen.'
                    }]
                }
                resp.status = falcon.HTTP_400
                return

            if task is None:
                req.context['result'] = {
                    'errors': [{
                        'status': '404',
                        'title': 'Not Found',
                        'detail': 'Úloha s tímto ID neexistuje.'
                    }]
                }
                resp.status = falcon.HTTP_404
                return

            req.context['result'] = {'atask': util.task.admin_to_json(task)}
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 38
0
    def _process_thread(self, corr):
        """ PUT: propojeni diskuzniho vlakna komentare """

        curr_thread = util.task.comment_thread(corr['task_id'], corr['user'])

        if (corr['comment'] is not None) and (curr_thread is None):
            # pridavame diskuzni vlakno
            try:
                comment = model.SolutionComment(thread=corr['comment'],
                                                user=corr['user'],
                                                task=corr['task_id'])
                session.add(comment)
                session.commit()
            except SQLAlchemyError:
                session.rollback()
                raise

        if (corr['comment'] is None) and (curr_thread is not None):
            # mazeme diskuzni vlakno
            try:
                comment = session.query(model.SolutionComment).\
                    get((curr_thread, corr['user'], corr['task_id']))
                session.delete(comment)
                session.commit()
            except SQLAlchemyError:
                session.rollback()
                raise
Esempio n. 39
0
    def on_get(self, req, resp, id):
        """
        Specifikace GET pozadavku:
        ?public=(1|0)
            tento argument je nepovinny, pokud neni vyplnen, dojde ke
            zverejneni

        """
        try:
            user = req.context['user']
            public = req.get_param_as_bool('public')

            if (not user.is_logged_in()) or (not user.is_org()):
                resp.status = falcon.HTTP_400
                return

            if public is None:
                public = True

            task = session.query(model.Task).get(id)
            if task is None:
                resp.status = falcon.HTTP_404
                return
            task.evaluation_public = public
            session.commit()
            req.context['result'] = {}
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 40
0
    def on_get(self, req, resp, id):
        """
        GET pozadavek na konkretni correction se spousti prevazne jako odpoved
        na POST.
        id je umele id, konstrukce viz util/correction.py
        Parametry: moduleX_version=Y (X a Y jsou cisla)

        """

        try:
            user = req.context['user']

            if (not user.is_logged_in()) or (not user.is_org()):
                resp.status = falcon.HTTP_400
                return

            evaluation = session.query(model.Evaluation).get(id)
            if evaluation is None:
                resp.status = falcon.HTTP_404
                return

            module = session.query(model.Module).get(evaluation.module)

            req.context['result'] = {
                'evaluation':
                util.correction.corr_eval_to_json(module, evaluation)
            }
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 41
0
    def on_get(self, req, resp, id):
        try:
            user = session.query(model.User).get(id)
        except SQLAlchemyError:
            session.rollback()
            raise

        if user is None:
            req.context['result'] = {
                'errors': [{
                    'status': '404',
                    'title': 'Not found',
                    'detail': 'Uživatel s tímto ID neexistuje.'
                }]
            }
            resp.status = falcon.HTTP_404
            return

        try:
            req.context['result'] = {
                'user':
                util.user.to_json(user,
                                  req.context['year_obj'],
                                  admin_data=req.context['user'].is_org())
            }
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()
Esempio n. 42
0
def upsert_repositories(o_data):
    organization = session.query(Organization).filter(
        Organization.id == o_data.id).first()

    r_data = o_data.get_repos()
    repositories = []
    for r_item in r_data:
        check_rate_limit(r_item)
        repository = r_formatter(r_item)
        source_login = repository['source_owner_login']
        if source_login:
            repository['source_civic'] = source_login.lower(
            ) in organizations_civic
            repository['source_government'] = source_login.lower(
            ) in organizations_government
        else:
            repository['source_government'] = True
        repository = upsert(model=Repository, unique_key='id', item=repository)
        repositories.append(repository)

    organization.repositories = repositories

    try:
        session.add(organization)
        session.commit()
        return r_data
    except:
        session.rollback()
Esempio n. 43
0
	def on_get(self, req, resp, id):
		try:
			user = req.context['user']
			user_id = req.context['user'].id if req.context['user'].is_logged_in() else None
			thread = session.query(model.Thread).get(id)

			if not thread:
				req.context['result'] = { 'errors': [ { 'status': '404', 'title': 'Not Found', 'detail': u'Toto vlákno neexistuje.' } ] }
				resp.status = falcon.HTTP_404
				return

			if (not thread) or (not thread.public and not (user.is_org() or util.thread.is_eval_thread(user.id, thread.id))):
				req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Přístup k vláknu odepřen.' } ] }
				resp.status = falcon.HTTP_400
				return

			# Pocet vsech prispevku
			posts_cnt = session.query(model.Post).filter(model.Post.thread == thread.id).count()
			# Pocet neprectenych prispevku
			if not user.is_logged_in():
				unread_cnt = posts_cnt
			else:
				visit = session.query(model.ThreadVisit).filter(model.ThreadVisit.user == user.id, model.ThreadVisit.thread == thread.id).first()
				if visit:
					unread_cnt = session.query(model.Post).filter(model.Post.thread == thread.id, model.Post.published_at > visit.last_visit).count()
				else:
					unread_cnt = posts_cnt

			req.context['result'] = { 'thread': util.thread.to_json(thread, user_id, unread_cnt, posts_cnt) }
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 44
0
 def try_session_commit(self):
     try:
         session.flush()
     except IntegrityError as ex:
         session.rollback()
         abort(409, message=f"Integrity Error: {ex.orig}")
     session.commit()
Esempio n. 45
0
def upsert_repositories(o_data):
    organization = session.query(Organization).filter(Organization.id==o_data.id).first()

    r_data = o_data.get_repos()
    repositories = []
    for r_item in r_data:
        check_rate_limit(r_item)
        repository = r_formatter(r_item)
        source_login = repository['source_owner_login']
        if source_login:
            repository['source_civic'] = source_login.lower() in organizations_civic            
            repository['source_government'] = source_login.lower() in organizations_government
        else:
            repository['source_government'] = True
        repository = upsert(model=Repository, unique_key='id', item=repository)
        repositories.append(repository)

    organization.repositories = repositories

    try:
        session.add(organization)
        session.commit()
        return r_data
    except:
        session.rollback()
 def insert(self, item):
     try:
         session.add(item)
         session.commit()
     except Exception as exc:
         session.rollback()
         log.error(f"Error inserting object in db (rolled back): {exc}")
Esempio n. 47
0
def upsert_contributors(o_data, r_data):
    organization = session.query(Organization).filter(Organization.id==o_data.id).first()

    contributors = set()
    for r_item in r_data:
        if not r_item.fork:
            c_data = r_item.get_contributors()
            repo_contributors = []
            for c_item in c_data:
                check_rate_limit(c_item)
                contributor = p_formatter(c_item)
                contributor = upsert(model=Person, unique_key='id', item=contributor)
                contributors.add(contributor)
                repo_contributors.append(contributor)

            repository = session.query(Repository).filter(Repository.id==r_item.id).first()
            repository.contributors = repo_contributors
            session.add(repository)
            session.commit()

    contributors = list(contributors)
    organization.contributors = contributors

    try:
        session.add(organization)
        session.commit()
    except:
        session.rollback()
Esempio n. 48
0
    def on_put(self, req, resp, id):
        try:
            user = req.context['user']

            if (not user.is_logged_in()) or (not user.is_org()):
                resp.status = falcon.HTTP_400
                return

            data = json.loads(req.stream.read().decode('utf-8'))['wave']

            wave = session.query(model.Wave).get(id)
            if wave is None:
                resp.status = falcon.HTTP_404
                return

            # Menit vlnu muze jen ADMIN nebo aktualni GARANT vlny.
            if not user.is_admin() and user.id != wave.garant:
                resp.status = falcon.HTTP_400
                return

            wave.index = data['index']
            wave.caption = data['caption']
            if data['time_published']:
                wave.time_published = dateutil.parser.parse(
                    data['time_published'])
            wave.garant = data['garant']

            session.commit()
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()

        self.on_get(req, resp, id)
Esempio n. 49
0
    def _process_achievements(self, corr):
        """ PUT: pridavani a mazani achievementu """

        a_old = util.achievement.ids_list(
            util.achievement.per_task(corr['user'], corr['task_id']))
        a_new = corr['achievements']
        if a_old != a_new:
            # achievementy se nerovnaji -> proste smazeme vsechny dosavadni
            # a pridame do db ty, ktere nam prisly.
            for a_id in a_old:
                try:
                    ach = session.query(model.UserAchievement).\
                        get((corr['user'], a_id))
                    if ach.task_id == int(corr['task_id']):
                        session.delete(ach)
                    session.commit()
                except SQLAlchemyError:
                    session.rollback()
                    raise

            for a_id in a_new:
                try:
                    ua = model.UserAchievement(user_id=corr['user'],
                                               achievement_id=a_id,
                                               task_id=corr['task_id'])
                    session.add(ua)
                    session.commit()
                except SQLAlchemyError:
                    session.rollback()
                    raise
                finally:
                    session.close()
Esempio n. 50
0
	def on_put(self, req, resp, id):
		try:
			user_id = req.context['user'].id if req.context['user'].is_logged_in() else None

			if not user_id:
				return

			if session.query(model.Thread).get(id) is None:
				status = falcon.HTTP_400
				return

			visit = util.thread.get_visit(user_id, id)

			if visit:
				visit.last_last_visit = visit.last_visit
				visit.last_visit = text('CURRENT_TIMESTAMP')
			else:
				visit = model.ThreadVisit(thread=id, user=user_id, last_visit=text('CURRENT_TIMESTAMP'))
				session.add(visit)

			session.commit()
			req.context['result'] = "{}"
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 51
0
	def on_post(self, req, resp):
		user = req.context['user']
		if (not user.is_logged_in()) or (not user.is_org()):
			req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Přidat článek může pouze organizátor.' } ] }
			resp.status = falcon.HTTP_400
			return

		data = json.loads(req.stream.read())['article']

		try:
			article = model.Article(
				author = user.id,
				title = data['title'],
				body = data['body'],
				published = data['published'],
				year = req.context['year'],
				time_created = dateutil.parser.parse(data['time_published']),
				picture = data['picture']
			)

			session.add(article)
			session.commit()

			article.resource = 'articles/' + str(article.id)
			session.commit()
		except SQLAlchemyError:
			session.rollback()
			raise

		req.context['result'] = { 'article': _artice_to_json(article) }

		session.close()
Esempio n. 52
0
	def on_put(self, req, resp, id):
		user = req.context['user']
		if (not user.is_logged_in()) or (not user.is_org()):
			req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Upravit článek může pouze organizátor.' } ] }
			resp.status = falcon.HTTP_400
			return

		data = json.loads(req.stream.read())['article']

		try:
			article = session.query(model.Article).get(id)
			if article is None:
				req.context['result'] = { 'errors': [ { 'status': '404', 'title': 'Not Found', 'detail': u'Článek s tímto ID neexistuje.' } ] }
				resp.status = falcon.HTTP_404
				return

			article.title = data['title']
			article.body = data['body']
			article.published = data['published']
			article.time_created = data['time_published']
			article.picture = data['picture']

			session.commit()
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()

		self.on_get(req, resp, id)
Esempio n. 53
0
 def process_request(self, req, resp):
     if req.method == 'OPTIONS':
         return
     try:
         if ('YEAR' in req.headers):
             req.context['year'] = req.headers['YEAR']
             req.context['year_obj'] = session.query(model.Year).\
                                       get(req.context['year'])
         else:
             year_obj = session.query(model.Year).\
                        order_by(desc(model.Year.id)).first()
             req.context['year_obj'] = year_obj
             req.context['year'] = year_obj.id
     except SQLAlchemyError:
         session.rollback()
         try:
             if ('YEAR' in req.headers):
                 req.context['year'] = req.headers['YEAR']
                 req.context['year_obj'] = session.query(model.Year).\
                                           get(req.context['year'])
             else:
                 year_obj = session.query(model.Year).\
                            order_by(desc(model.Year.id)).first()
                 req.context['year_obj'] = year_obj
                 req.context['year'] = year_obj.id
         except:
             session.rollback()
             raise
Esempio n. 54
0
	def on_get(self, req, resp):
		user = req.context['user']

		try:
			query = session.query(model.Article).filter(model.Article.year == req.context['year'])
			if user is None or user.id is None or user.role == 'participant' or user.role == 'participant_hidden':
				query = query.filter(model.Article.published)
			query = query.order_by(desc(model.Article.time_created))

			limit = req.get_param_as_int('_limit')
			start = req.get_param_as_int('_start')
			count = query.count()

			data = query.all() if limit is None or start is None else query.slice(start, start + limit)
		except SQLAlchemyError:
			session.rollback()
			raise

		articles = [ _artice_to_json(inst) for inst in data ]
		resources = [ util.content.dir_to_json(inst.resource) for inst in data if inst.resource is not None ] if user.is_org() else []

		req.context['result'] = {
			'articles': articles,
			'meta': { 'total': count },
			'contents': resources
		}
Esempio n. 55
0
    def process_request(self, req, resp):
        if req.auth:
            token_str = req.auth.split(' ')[-1]
            try:
                token = session.query(model.Token).get(token_str)

                if token is not None:
                    if (req.relative_uri != '/auth' and
                       token.expire < datetime.utcnow()):
                        # user timeouted
                        req.context['user'] = UserInfo()
                        return

                    try:
                        req.context['user'] = UserInfo(
                            session.query(model.User).get(token.user),
                            token_str
                        )
                        return
                    except AttributeError:
                        pass
            except:
                session.rollback()

        req.context['user'] = UserInfo()
Esempio n. 56
0
	def on_get(self, req, resp, eval_id):
		try:
			user = req.context['user']

			if (not user.is_logged_in()) or (not user.is_org()):
				resp.status = falcon.HTTP_400
				return

			inMemoryOutputFile = StringIO()
			zipFile = ZipFile(inMemoryOutputFile, 'w')

			files = [ r for (r, ) in session.query(model.SubmittedFile.path).\
				filter(model.SubmittedFile.evaluation == eval_id).distinct() ]

			for fname in files:
				if os.path.isfile(fname):
					zipFile.write(fname, os.path.basename(fname))

			zipFile.close()

			resp.set_header('Content-Disposition', "inline; filename=\"eval_" + str(eval_id) + ".zip\"")
			resp.content_type = "application/zip"
			resp.stream_len = inMemoryOutputFile.len
			resp.body = inMemoryOutputFile.getvalue()

			inMemoryOutputFile.close()
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 57
0
	def on_get(self, req, resp, id):
		try:
			user = req.context['user']
			user_id = req.context['user'].get_id() if req.context['user'].is_logged_in() else None

			post = session.query(model.Post).get(id)

			if post is None:
				resp.status = falcon.HTTP_404
				return

			thread = session.query(model.Thread).get(post.thread)

			if thread is None:
				resp.status = falcon.HTTP_404
				return

			# Kontrola pristupu k prispevkum:
			# a) K prispevkum v eval vlakne mohou pristoupit jen orgove a jeden resitel
			# b) K ostatnim neverejnym prispevkum mohou pristoupit jen orgove.
			if not thread.public and ((not user.is_logged_in()) or (not user.is_org() and not util.thread.is_eval_thread(user.id, thread.id))):
				resp.status = falcon.HTTP_400
				return

			req.context['result'] = { 'post': util.post.to_json(post, user_id) }
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()
Esempio n. 58
0
	def on_put(self, req, resp, id):
		try:
			user = req.context['user']

			if (not user.is_logged_in()) or (not user.is_org()):
				# Toto tady musi byt -- jinak nefunguje frontend.
				self.on_get(req, resp, id)
				return

			data = json.loads(req.stream.read())['post']

			post = session.query(model.Post).get(id)
			if post is None:
				resp.status = falcon.HTTP_404
				return

			post.author = data['author']
			post.body = data['body']

			session.commit()
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()

		self.on_get(req, resp, id)
Esempio n. 59
0
	def on_get(self, req, resp):
		try:
			achievements = session.query(model.Achievement).\
				filter(or_(model.Achievement.year == None, model.Achievement.year == req.context['year'])).all()
		except SQLAlchemyError:
			session.rollback()
			raise

		req.context['result'] = { 'achievements': [ util.achievement.to_json(achievement) for achievement in achievements ] }
Esempio n. 60
0
	def on_post(self, req, resp):
		try:
			userinfo = req.context['user']

			if not userinfo.is_logged_in():
				resp.status = falcon.HTTP_400
				return

			user = session.query(model.User).filter(model.User.id == userinfo.get_id()).first()

			files = multipart.MultiDict()
			content_type, options = multipart.parse_options_header(req.content_type)
			boundary = options.get('boundary','')

			if not boundary:
				raise multipart.MultipartError("No boundary for multipart/form-data.")

			for part in multipart.MultipartParser(req.stream, boundary, req.content_length):
				files[part.name] = part

			file = files.get('file')
			user_id = req.context['user'].get_id()
			tmpfile = tempfile.NamedTemporaryFile(delete = False)

			file.save_as(tmpfile.name)

			mime = magic.Magic(mime=True).from_file(tmpfile.name)

			if mime not in ALLOWED_MIME_TYPES:
				resp.status = falcon.HTTP_400
				return

			if not os.path.isdir(UPLOAD_DIR):
				try:
					os.makedirs(UPLOAD_DIR)
				except OSError:
					print 'Unable to create directory for profile pictures'
					resp.status = falcon.HTTP_500
					return

			new_picture = os.path.join(UPLOAD_DIR, 'user_%d.%s' % (user_id, ALLOWED_MIME_TYPES[mime]))

			self._crop(tmpfile.name, new_picture)
			try:
				os.remove(tmpfile.name)
			except OSError:
				print 'Unable to remove temporary file %s' % tmpfile.name

			user.profile_picture = new_picture

			session.add(user)
			session.commit()
		except SQLAlchemyError:
			session.rollback()
			raise
		finally:
			session.close()