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()
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()
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'] = {}
def post(self): args = classParser.parse_args() existingCourse = session.query(CourseModel).filter( CourseModel.crn == args['crn']).one_or_none() if (existingCourse): abort(400, message="Course with the crn {} already exists".format( args['crn'])) newCourse = CourseModel(args['crn'], args['faculty_id'], args['course_number'], args['course_name'], args['course_type'], args['semester'], args['course_year']) validSLOs = [] for sloObject in args['assigned_slos']: slo = session.query(SLOModel).filter( SLOModel.slo_id == sloObject['slo_id']).one_or_none() if slo: validSLOs.append( AssignedSLOModel(args['crn'], sloObject['slo_id'], sloObject['comments'])) else: abort(404, message="SLO with this slo_id {} does not exist.".format( slo['slo_id'])) session.add(newCourse) newCourse.assigned_slos = validSLOs session.commit() #commits to a database session.close() return session.query(CourseModel).filter( CourseModel.crn == args['crn']).first()
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)
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()
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()
def insert(company_name, company_group_name, language_code): success = True error_msg = None company_group_id = CompanyGroupModel.select_company_group_id_by_company_group_name( company_group_name) if not company_group_id: success = False error_msg = "No record found for the company group name: {}".format( company_group_name) return success, error_msg language_id = LanguageModel.select_language_id_by_code(language_code) if not language_id: success = False error_msg = "No record found for the language code: {}".format( language_code) return success, error_msg company = CompanyModel(name=company_name, company_group_id=company_group_id, language_id=language_id) try: session.add(company) session.commit() except (connector.Error, SQLAlchemyError) as e: session.rollback() success = False error_msg = e.__cause__ finally: session.close() return success, error_msg
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' }
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()
def on_delete(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': 'Smazat článek může pouze organizátor.' }] } resp.status = falcon.HTTP_400 return try: article = session.query(model.Article).get(id) if article is None: req.context['result'] = { 'errors': [{ 'status': '404', 'title': 'Not Found', 'detail': 'Článek s tímto ID neexistuje.' }] } resp.status = falcon.HTTP_404 return session.delete(article) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
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()
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)
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()
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()
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()
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)
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'] = {}
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()
def add_test(): data = request.json t_obj = test(name=data['name']) session.add(t_obj) session.commit() session.close() return json.dumps({"data": "{} Added Succesfully".format(data['name'])})
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()
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()
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()
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()
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()
def add_choice(): data = request.json c_obj = choice(name=data['name']) session.add(c_obj) session.commit() session.close() return json.dumps({"data": "{} - Added Succesfully ".format(data['name'])})
def test_sumbission(): """ This function accepts question id and selected choice id and test id and teacher id who creates the test and pupil id who writes the test input format: { "question_ans": {"1": 2, "2": 3, "4":1}, "test_id": 1, "teacher_id": 1 "pupil_id": 1 } """ data = request.json if isinstance(data['question_ans'], dict) and isinstance(data['test_id'], int) and isinstance(data['teacher_id'], int)\ and isinstance(data['pupil_id'], int): for que, ans in data['question_ans'].items(): test_submission_obj = test_submission( pupil_id=data['pupil_id'], ques_id=int(que), test_id=data['test_id'], teacher_id=data['teacher_id'], choice_id=ans) session.add(test_submission_obj) session.commit() session.close() return json.dumps({"data": "Test Succesfully submitted"}) else: return json.dumps({"data": "Invalid data format"})
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()
def delete(tag_name, tag_group_name, language_code): success = True error_msg = None tag_group_id = TagGroupModel.select_tag_group_id_by_tag_group_name( tag_group_name) language_id = LanguageModel.select_language_id_by_code(language_code) try: tag = session.\ query(TagModel).\ filter(TagModel.name == tag_name, TagModel.tag_group_id == tag_group_id, TagModel.language_id == language_id).\ one() session.delete(tag) session.commit() except (connector.Error, SQLAlchemyError) as e: session.rollback() success = False error_msg = e.__cause__ finally: session.close() return success, error_msg
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()
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()
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()
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()
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()
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()
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()
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()
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()
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()
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()
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()
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()
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()
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)
def on_delete(self, req, resp, id): """ Smazani ulohy """ try: user = req.context['user'] # Ulohu mohou smazat jen admini if (not user.is_logged_in()) or (not user.is_admin()): resp.status = falcon.HTTP_400 return task = session.query(model.Task).get(id) if task is None: resp.status = falcon.HTTP_404 return # Ulohu lze smazat jen pred casem zverejneni vlny wave = session.query(model.Wave).get(task.wave) if datetime.datetime.utcnow() > wave.time_published: resp.status = falcon.HTTP_403 return execs = session.query(model.CodeExecution).\ join( model.Module, model.Module.id == model.CodeExecution.module ).\ filter(model.Module.task == id).all() for _exec in execs: session.delete(_exec) evals = session.query(model.Evaluation).\ join(model.Module, model.Module.id == model.Evaluation.module).\ filter(model.Module.task == id).all() for _eval in evals: session.delete(_eval) session.query(model.Module).\ filter(model.Module.task == id).delete() thread = session.query(model.Thread).get(task.thread) prer = task.prerequisite_obj if prer is not None: session.delete(task.prerequisite_obj) session.delete(task) session.commit() if thread is not None: session.delete(thread) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_post(self, req, resp): """Create new feedback""" try: user = req.context['user'] if not user.is_logged_in(): resp.status = falcon.HTTP_400 return data = json.loads(req.stream.read().decode('utf-8'))['feedback'] if session.query(model.Task).get(int(data['taskId'])) is None: req.context['result'] = { 'errors': [{ 'status': '404', 'title': 'Not found', 'detail': 'Úloha s tímto ID neexistuje.' }] } resp.status = falcon.HTTP_404 return content = json.dumps( util.feedback.parse_feedback(data['categories']), indent=2, ensure_ascii=False, ) feedback = model.Feedback( user=user.get_id(), task=int(data['taskId']), content=content, lastUpdated=datetime.datetime.utcnow(), ) session.add(feedback) session.commit() req.context['result'] = { 'feedback': util.feedback.to_json(feedback) } except (EForbiddenType, EUnmatchingDataType, EMissingAnswer, EOutOfRange) as e: req.context['result'] = { 'errors': [{ 'status': '400', 'title': 'Bad Request', 'detail': str(e) }] } resp.status = falcon.HTTP_400 return except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_post(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 # Kontrola zamku lock = util.lock.git_locked() if lock: req.context['result'] = ('GIT uzamcen zamkem ' + lock + '\nNekdo momentalne provadi akci s ' 'gitem, opakujte prosim akci za 20 ' 'sekund.') resp.status = falcon.HTTP_409 return pullLock = LockFile(util.admin.waveDiff.LOCKFILE) pullLock.acquire(60) # Timeout zamku je 1 minuta # Fetch repo = git.Repo(util.git.GIT_SEMINAR_PATH) repo.remotes.origin.fetch() # Ulohy ve vlne tasks = session.query(model.Task).\ filter(model.Task.wave == id).all() # Diffujeme adresare uloh task.git_commit oproti HEAD for task in tasks: if ((not task.git_branch) or (not task.git_path) or (not task.git_commit)): task.deploy_status = 'default' continue # Checkout && pull vetve ve ktere je uloha repo.git.checkout(task.git_branch) repo.remotes.origin.pull() # Kontrola existence adresare ulohy if os.path.isdir(util.git.GIT_SEMINAR_PATH + task.git_path): hcommit = repo.head.commit diff = hcommit.diff(task.git_commit, paths=[task.git_path]) if len(diff) > 0: task.deploy_status = 'diff' else: task.deploy_status = 'default' session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() req.context['result'] = 'Nastala vyjimka backendu' raise finally: pullLock.release() session.close()
def add_question(): data = request.json if isinstance(data['name'], str): return json.dumps({"data": "Submit questions must be in valid format"}) q_obj = question(name=data['name']) session.add(q_obj) session.commit() session.close() return json.dumps({"data": "{} - Added Succesfully ".format(data['name'])})
def create_test_record(): person = Person.Person() person.name = 'test user 2' person.gender = False person.date_of_birth = datetime.utcnow() session.add(person) session.commit() session.close() print('data saved')
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()
def contact(): if request.method == 'POST': g_recaptcha_response = request.form.get('g-recaptcha-response') secret = config.reCaptcha.secret url = config.reCaptcha.uri if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] else: ip = request.remote_addr site_key = config.reCaptcha.site_key data = { 'secret': secret, 'response': g_recaptcha_response, 'remoteip': ip } r = requests.post(url, data=data) if r.status_code != 200: errors.append('reCAPTCHA service failure') return render_template('error.html', errors=errors), 400 result = r.json() success = result.get('success') if success is not True: errors.append('reCAPTCHA failure') for error in result.get('error-codes'): errors.append(error) return render_template('error.html', errors=errors), 429 contact = Contact() contact.name = request.form.get('name') contact.email = request.form.get('email') contact.message = request.form.get('message') contact.ip = ip session.add(contact) session.commit() session.close() date = datetime.datetime.now( timezone('US/Mountain')).strftime('%Y-%m-%d %I:%M:%S %p') msg = MIMEText("Date/Time: {}\nName: {}\nEmail: {}\n\n{}".format( date, contact.name, contact.email, contact.message)) msg['Subject'] = "Website Comment {}".format(date) msg['Reply-To'] = '"{}" <{}>'.format(contact.name, contact.email) msg['From'] = "*****@*****.**" msg['To'] = "[email protected], [email protected]" server = smtplib.SMTP(config.mail.host, config.mail.port) server.ehlo() server.starttls() server.login(config.mail.user, config.mail.password) server.sendmail("*****@*****.**", ["*****@*****.**", "*****@*****.**"], msg.as_string()) server.quit() return render_template('contact_thanks.html') else: site_key = config.reCaptcha.site_key return render_template('contact.html', site_key=site_key)
def pupil_register(): data = request.json p_obj = pupil(first_name=data['first_name'], sur_name=data['sur_name'], email_add=data['email_add']) session.add(p_obj) session.commit() session.close() return json.dumps( {"data": "{} - Added Succesfully ".format(data['first_name'])})
def on_post(self, req, resp, id): try: user = req.context['user'] # Kontrola opravneni if (not user.is_logged_in()) or (not user.is_org()): req.context['result'] = 'Nedostatecna opravneni' resp.status = falcon.HTTP_400 return # 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 # Zverejnene ulohy mohou deployovat pouze admini wave = session.query(model.Wave).get(task.wave) if (datetime.datetime.utcnow() > wave.time_published) and (not user.is_admin()): req.context['result'] = 'Po zverejneni ulohy muze deploy provest pouze administrator' resp.status = falcon.HTTP_404 return # Kontrola existence gitovske vetve a adresare v databazi if (task.git_branch is None) or (task.git_path is None): req.context['result'] = 'Uloha nema zadanou gitovskou vetev nebo adresar' resp.status = falcon.HTTP_400 return # Kontrola zamku lock = util.lock.git_locked() if lock: req.context['result'] = 'GIT uzamcen zamkem ' + lock + "\nNekdo momentalne provadi akci s gitem, opakujte prosim akci za 20 sekund." resp.status = falcon.HTTP_409 return # Stav na deploying je potreba nastavit v tomto vlakne task.deploy_status = 'deploying' session.commit() try: deployLock = LockFile(util.admin.taskDeploy.LOCKFILE) deployLock.acquire(60) # Timeout zamku je 1 minuta deployThread = threading.Thread(target=util.admin.taskDeploy.deploy, args=(task.id, deployLock, scoped_session(_session)), kwargs={}) deployThread.start() finally: deployLock.release() resp.status = falcon.HTTP_200 except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_put(self, req, resp, id): user = req.context['user'] # Upravovat trofeje mohou jen orgove if (not user.is_logged_in()) or (not user.is_org()): req.context['result'] = { 'errors': [{ 'status': '401', 'title': 'Unauthorized', 'detail': 'Úpravu trofeje může provést pouze organizátor.' }] } resp.status = falcon.HTTP_400 return data = json.loads(req.stream.read().decode('utf-8'))['achievement'] try: achievement = session.query(model.Achievement).get(id) except SQLAlchemyError: session.rollback() raise if achievement is None: req.context['result'] = { 'errors': [{ 'status': '404', 'title': 'Not Found', 'detail': 'Trofej s tímto ID neexistuje.' }] } resp.status = falcon.HTTP_404 return achievement.title = data['title'] achievement.picture = data['picture'] achievement.description = data['description'] if not data['persistent']: achievement.year = req.context['year'] else: achievement.year = None try: session.commit() except SQLAlchemyError: session.rollback() raise finally: session.close() self.on_get(req, resp, id)
def on_get(self, req, resp): try: years = session.query(model.Year).all() sum_points = util.task.max_points_year_dict() req.context['result'] = { 'years': [ util.year.to_json(year, sum_points[year.id]) for year in years ] } except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_delete(self, req, resp, id): try: submittedFile = self._get_submitted_file(req, resp, id) if submittedFile: # Kontrola casu (soubory lze mazat jen pred deadline) eval_id = submittedFile.evaluation task = session.query(model.Task).\ join(model.Module, model.Module.task == model.Task.id).\ join(model.Evaluation, model.Evaluation.module == model.Module.id).\ filter(model.Evaluation.id == submittedFile.evaluation).first() if task.time_deadline < datetime.datetime.utcnow(): req.context['result'] = { 'result': 'error', 'error': u'Nelze smazat soubory po termínu odevzdání úlohy' } return try: os.remove(submittedFile.path) evaluation = session.query(model.Evaluation).get(eval_id) if evaluation: evaluation.full_report += str(datetime.datetime.now()) + " : removed file " + submittedFile.path + '\n' session.delete(submittedFile) session.commit() # Pokud resitel odstranil vsechny soubory, odstranime evaluation if evaluation: files_cnt = session.query(model.SubmittedFile).filter(model.SubmittedFile.evaluation == eval_id).count() if files_cnt == 0: session.delete(evaluation) session.commit() req.context['result'] = { 'status': 'ok' } except OSError: req.context['result'] = { 'status': 'error', 'error': u'Soubor se nepodařilo odstranit z filesystému' } return except exc.SQLAlchemyError: req.context['result'] = { 'status': 'error', 'error': u'Záznam o souboru se nepodařilo odstranit z databáze' } return else: if resp.status == falcon.HTTP_404: req.context['result'] = { 'status': 'error', 'error': u'Soubor nenalezen na serveru' } elif resp.status == falcon.HTTP_403: req.context['result'] = { 'status': 'error', 'error': u'K tomuto souboru nemáte oprávnění' } else: req.context['result'] = { 'status': 'error', 'error': u'Soubor se nepodařilo získat' } resp.status = falcon.HTTP_200 except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_post(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 # Kontrola zamku lock = util.lock.git_locked() if lock: req.context['result'] = 'GIT uzamcen zamkem ' + lock + "\nNekdo momentalne provadi akci s gitem, opakujte prosim akci za 20 sekund." resp.status = falcon.HTTP_409 return pullLock = LockFile(util.admin.waveDiff.LOCKFILE) pullLock.acquire(60) # Timeout zamku je 1 minuta # Fetch repo = git.Repo(util.git.GIT_SEMINAR_PATH) repo.remotes.origin.fetch() # Ulohy ve vlne tasks = session.query(model.Task).\ filter(model.Task.wave == id).all() # Diffujeme adresare uloh task.git_commit oproti HEAD for task in tasks: if (not task.git_branch) or (not task.git_path) or (not task.git_commit): task.deploy_status = 'default' continue # Checkout && pull vetve ve ktere je uloha repo.git.checkout(task.git_branch) repo.remotes.origin.pull() # Kontrola existence adresare ulohy if os.path.isdir(util.git.GIT_SEMINAR_PATH+task.git_path): hcommit = repo.head.commit diff = hcommit.diff(task.git_commit, paths=[task.git_path]) if len(diff) > 0: task.deploy_status = 'diff' else: task.deploy_status = 'default' session.commit() except SQLAlchemyError: session.rollback() req.context['result'] = 'Nastala vyjimka backendu' raise finally: pullLock.release() session.close()
def on_post(self, req, resp): 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())['e-mail'] # Filtrovani uzivatelu if data['To'] != []: active = util.user.active_years_all() active = [ user for (user,year) in filter(lambda (user,year): (user.role == 'participant') and (year.id in data['To']), active) ] if ('Gender' in data) and (data['Gender'] != 'both'): active = filter(lambda user: user.sex == data['Gender'], active) to = active else: query = session.query(model.User).filter(model.User.role == 'participant') if ('Gender' in data) and (data['Gender'] != 'both'): query = query.filter(model.User.sex == data['Gender']) to = query.all() if ("Successful" in data) and (data['Successful']): succ = set() for year in data['To']: year_obj = session.query(model.Year).get(year) succ |= set(map(lambda (user,points): user.id, util.user.successful_participants(year_obj))) to = filter(lambda user: user.id in succ, to) to = set([ user.email for user in to ]) params = { 'Reply-To': data['Reply-To'], 'Sender': data['Sender'] } body = data['Body'] if ('KarlikSign' in data) and (data['KarlikSign']): body = body + util.config.karlik_img() if ('Easteregg' in data) and (data['Easteregg']): body = body + util.mail.easteregg() try: util.mail.send_multiple(to, data['Subject'], body, params, data['Bcc']) req.context['result'] = { 'count': len(to) } except Exception as e: req.context['result'] = { 'error': str(e) } resp.status = falcon.HTTP_500 except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_get(self, req, resp): try: user = req.context['user'] waves = session.query(model.Wave).\ filter(model.Wave.year == req.context['year']).all() max_points = util.task.max_points_wave_dict() req.context['result'] = { 'waves': [ util.wave.to_json(wave, max_points[wave.id]) for wave in waves ] } except SQLAlchemyError: session.rollback() raise finally: session.close()