def rate(request): if not request.GET: return generate_response('fail', reason='not_get') username = request.GET['username'] if '.' in request.GET['rating']: return generate_response('fail', reason='incorrect_rating') try: rating = int(request.GET['rating']) except ValueError: return generate_response('fail', reason='incorrect_rating') if not User.objects.filter(username=username).exists(): return generate_response('fail', reason='user_not_exists') user = MyUser(username) try: user.rate(rating) except ValueError as e: return generate_response('fail', reason=str(e)) return generate_response('success')
def create_complaint(self, violator_nickname, description, evidence): """ create a new complaint :raise FieldContainsForbiddenException: if field 'issuer_nickname' or 'violator_nickname' contains authorized user's username """ if MyUser(self.issuer_nickname).has_access('staff'): raise FieldContainsForbiddenException("Ваш ник", self.issuer_nickname) if MyUser(violator_nickname).has_access('staff'): raise FieldContainsForbiddenException("Ник нарушителя", violator_nickname) self.ticket_type = self.COMPLAINT self.complaints.create(violator_nickname=violator_nickname, description=description, evidence=evidence) self.save() emailer = Emailer() emailer.send_email( self.email, emailer.get_mail_message_new_ticket( 'https://support.mc-magicstore.ru/tickets/%s' % self.secret_key, self.secret_key))
def create(self): """ save files, add week and date, send notification to osx11 & save a report """ if self.files: files_to_upload = dict() for file in self.files: files_to_upload[file] = cdefs.generate_file_name() files = cdefs.handle_uploaded_file(files_to_upload) files = dumps({'files': files}) self.files = files now = dt.now() self.year = now.isocalendar()[0] self.week = now.isocalendar()[1] self.date = now.strftime('%Y-%m-%d %H:%M:%S') self.save() pinned_admin_user = self.__get_pinned_admin_user() if self.isImportant and 'osx11' not in self.pinned_admin: notify.send(pinned_admin_user, recipient=MyUser('osx11').user, verb='%s отправил важный отчет (#%d)' % (pinned_admin_user.username, self.id)) if not settings.TEST_IN_PROGRESS: notify.send(pinned_admin_user, recipient=MyUser('Ravelbpylb').user, verb='%s отправил важный отчет (#%d)' % (pinned_admin_user.username, self.id))
class TestViews(TestCase): def setUp(self): self.username = '******' self.moderator = MyUser(self.username) self.moderator.create(True, False, 'pass', 'first', 'last') self.moderator.manage_access(['moders']) self.year = dt.now().isocalendar()[0] @staticmethod def __get_current_week(): return dt.now().isocalendar()[1] def __create_report_with_custom_week(self, week): report = Reports(violator_nickname='violator', violator_donate='donate', violation='violation', comment='comment', server='server', evidence_text='evidence_text', pinned_admin=self.username, date=dt.now().strftime('%Y-%m-%d %H:%M:%S'), week=week, year=self.year, isImportant=False, isWarning=False, files=None, dialogue=None) return report def test_weekly(self): report = self.__create_report_with_custom_week( self.__get_current_week() - 1) report.save() report = self.__create_report_with_custom_week( self.__get_current_week() - 1) report.save() report = self.__create_report_with_custom_week( self.__get_current_week()) report.save() client = Client() client.login(username=self.username, password='******') response = client.get(reverse('weekly')) filled_weeks = response.context['filled_weeks'] self.assertEquals( filled_weeks[self.__get_current_week()][1]['moderator'][0], 1) self.assertEquals( filled_weeks[self.__get_current_week()][1]['moderator'][1], -1) self.assertEquals( filled_weeks[self.__get_current_week() - 1][1]['moderator'][0], 2) self.assertEquals( filled_weeks[self.__get_current_week() - 1][1]['moderator'][1], 2)
def get_rank_title(context): request = context['request'] if request.user.is_anonymous: return False username = get_user(request.user).split(' ')[0] user = MyUser(username) return user.get_rank_title()
def test_rate_normal(self): client = Client() response = client.get(reverse('rate'), data={'username': '******', 'rating': '5'}) response_content = self.get_json_content(response) self.assertEquals(response_content['status'], 'success') self.assertEquals(MyUser('test').get_rating(), 5.0) client.get(reverse('rate'), data={'username': '******', 'rating': '2'}) self.assertEquals(MyUser('test').get_rating(), 3.5)
def test_add_online_normal(self): client = Client() response = client.get(reverse('add_online'), data={'username': '******', 'hours': '2'}) response_content = self.get_json_content(response) self.assertEquals(response_content['status'], 'success') self.assertEquals(MyUser('test').get_online(), 2) client.get(reverse('add_online'), data={'username': '******', 'hours': '5'}) self.assertEquals(MyUser('test').get_online(), 7)
def wrap(request, *args, **kwargs): """ this function uses to prevent unauthorized access to some apps (such as 'staff', 'control' and so on) user must have passed 'access' option in access_list json object in order to visit page :return: render a template if user is not authorized """ user = MyUser(request.user.username) if not user.has_access(access): return render(request, 'main/admin_wrapper.html', {'unauthorized': True}) return function(request, *args, **kwargs)
def create(request): if not request.POST: return HttpResponseRedirect('/moders/') form = ReportForm(request.POST) if form.is_valid(): if not request.recaptcha_is_valid: return HttpResponseRedirect('/moders/new_report/') violator_nickname = request.POST['violator_nickname'] violator_donate = request.POST['violator_donate'] violation = request.POST['violation'] comment = request.POST['comment'].replace('\r\n', '<br>') server = request.POST['server'] evidence_text = request.POST['evidence_text'].replace('\r\n', '<br>') pinned_admin = get_username(request.user) isimportant = True if request.POST.get('isImportant') == 'on' else False iswarning = True if request.POST.get('isWarning') == 'on' else False files = request.FILES.getlist('dropZone', None) report = Reports(violator_nickname=violator_nickname, violator_donate=violator_donate, violation=violation, comment=comment, server=server, evidence_text=evidence_text, pinned_admin=pinned_admin, isImportant=isimportant, isWarning=iswarning, files=files) report.create() messages.success(request, 'Отчет сохранен.') else: messages.error(request, 'Форма заполнена неверно.') return HttpResponseRedirect('/moders/new_report/') user = MyUser(request.user.username) if user.has_access('moders'): return HttpResponseRedirect('/moders/') return HttpResponseRedirect('/moders/new_report/')
def add_online(request): if not request.GET: return generate_response('fail', reason='not_get') username = request.GET['username'] hours = float(request.GET['hours']) if not User.objects.filter(username=username).exists(): return generate_response('fail', reason='user_not_exists') user = MyUser(username) try: user.add_online(hours) except ValueError as e: return generate_response('fail', reason=str(e)) return generate_response('success')
def setUp(self): self.username = '******' self.moderator = MyUser(self.username) self.moderator.create(True, False, 'pass', 'first', 'last') self.osx11 = MyUser('osx11') self.osx11.create(False, False, 'pass', 'Grigory', 'Albertov') self.report = Reports(violator_nickname='test_violator', violator_donate='test_donate', violation='test_violation', comment='test_comment', server='test_server', evidence_text='test_evidence', pinned_admin=self.username, isImportant=True, isWarning=False, files=load_test_files())
def __get_pinned_admin_user(self): """ :return: user of report's creator (django user) """ pinned_admin_username = self.pinned_admin.split(' ')[0] # get only a username pinned_admin_user = MyUser(pinned_admin_username).user # receive user return pinned_admin_user
def wrap(request, *args, **kwargs): """ this function uses in main urls.py file in order to restrict access for everyone, except authorized users (users which are have 'maintenance' option in access_list), when config('MAINTENANCE') is True if user has 'maintenance' option in access_list, then it can visit on page with constant 'Maintenance access' message else it will be not able to visit page :return: render maintenance template if maintenance is on and user is not authorized """ if settings.MAINTENANCE: user = MyUser(request.user.username) if not user.has_access('maintenance'): return render(request, 'main/errors/maintenance.html') messages.warning(request, 'Maintenance access') return function(request, *args, **kwargs)
def use_dark_theme_tag(context): request = context['request'] if request.user.is_anonymous: return False username = get_user(request.user).split(' ')[0] user = MyUser(username) return user.use_dark_theme
def test_create_complaint_forbidden_violator(self): user = MyUser('osx11') user.create(True, False, 'pass', 'fist', 'last') user.manage_access(['staff']) with self.assertRaises(FieldContainsForbiddenException): self.ticket.create_complaint(violator_nickname='osx11', description='test_description', evidence=None)
def test_resend_multiple(self): schedule.clear() user = MyUser('authorized_2') user.create(True, False, 'pass', 'fist', 'last') user.manage_access(['control']) ticket1 = Tickets(issuer_nickname='test', server='server', email='*****@*****.**', ip_address='127.0.0.2', ) ticket1.create() ticket2 = Tickets(issuer_nickname='test', server='server', email='*****@*****.**', ip_address='127.0.0.2', ) ticket2.create() ticket_2_current_time = ticket2.datetime schedule.jobs[0].tag('TICKET 1') schedule.jobs[1].tag('TICKET 2') sleep(2) schedule.jobs[0].run() schedule.clear('TICKET 1') self.assertEquals(dt.strftime(dt.now(), '%Y-%m-%d %H:%M:%S'), ticket1.datetime) self.assertEquals(ticket_2_current_time, ticket2.datetime) self.assertEquals(len(schedule.jobs), 2)
def index(request): """ `rank` dict should look like this: ranks = { 'osx11': { 'rank': ('rankosx', 'Гл. Администратор'), 'online': 1024.0, 'rating': (4.8, 10), 'applications_considered': 123, 'additional': [('expert', 'Эксперт'), ('paperwork', 'Бумажная работа')] }, """ ranks = {} for django_user in User.objects.all().exclude(username='******'): username = django_user.username user = MyUser(username) if user.has_access('staff'): continue ranks[username] = {'rank': (str, str), 'online': str, 'rating': str, 'additional': list} ranks[username]['rank'] = (user.get_rank_name(), user.get_rank_title()) ranks[username]['online'] = user.get_online() ranks[username]['rating'] = (user.get_rating(), user.get_vote_count()) ranks[username]['applications_considered'] = user.get_applications_considered() ranks[username]['additional'] = user.get_additional_ranks() ranks = dict(sorted(ranks.items(), key=lambda item: item[1]['rank'][0], reverse=True)) return render(request, 'our_team/our_team.html', {'messages': messages.get_messages(request), 'ranks': ranks})
def test_create_complaint_forbidden_issuer(self): user = MyUser('osx11') user.create(True, False, 'pass', 'fist', 'last') user.manage_access(['staff']) ticket = Tickets(issuer_nickname='osx11', server='server', email='*****@*****.**', ip_address='127.0.0.3', files=None) with self.assertRaises(FieldContainsForbiddenException): ticket.create_complaint(violator_nickname='test', description='desc', evidence=None)
def setUp(self): user = MyUser('test') user.create(True, False, 'pass', 'fist', 'last') user.manage_access(['control']) self.ticket = Tickets( issuer_nickname='test', server='test_server', email='*****@*****.**', ip_address='127.0.0.1', files=None ) self.ticket.create()
def add_comment(request, pk): if not request.POST: return HttpResponseRedirect('/') if not request.recaptcha_is_valid: return HttpResponseRedirect('/tickets/%s/' % pk) form = AddCommentForm(request.POST) if form.is_valid(): answer = request.POST['staff_answer'].replace('\r\n', '<br>') user = get_username( request.user) if request.POST.get('showName') == 'on' else 'Скрыто' will_close = True if request.POST.get('willClose') == 'on' else False files = request.FILES.getlist('dropZone', None) ticket = Tickets.objects.get(secret_key=pk) ticket.add_comment(answer=answer, user=user, will_close=will_close, files=files) emailer = Emailer() emailer.send_email( ticket.email, emailer.get_mail_message_add_comment( 'support.mc-magicstore.ru/tickets/%s' % pk, pk, answer)) if ticket.isClosed: MyUser(request.user.username).add_applications_considered_count() messages.success(request, 'Ответ сохранен. Таймер заявки сброшен на 3 суток.') else: messages.error(request, 'Форма заполнена неверно.') return HttpResponseRedirect('/tickets/%s/' % pk)
def test_resend(self): ticket = Tickets(issuer_nickname='test', server='server', email='*****@*****.**', ip_address='127.0.0.2',) ticket.create() schedule.clear() user = MyUser('authorized_2') user.create(True, False, 'pass', 'fist', 'last') user.manage_access(['control']) current_pinned_admin = ticket.pinned_admin ticket.resend() self.assertNotEquals(current_pinned_admin, ticket.pinned_admin) self.assertTrue(MyUser(ticket.pinned_admin.split(' ')[0]).has_access('control')) self.assertEquals(dt.strftime(dt.now(), '%Y-%m-%d %H:%M:%S'), ticket.datetime) self.assertEquals(len(schedule.jobs), 1) self.assertTrue(ticket.secret_key in schedule.jobs[0].tags)
def setUp(self): self.user = MyUser(self.USERNAME)
class TestClass(TestCase): USERNAME = '******' TRACK_FOR_STAT = False DARK_THEME = False PASSWORD = '******' FIRST_NAME = 'test_user_name' LAST_NAME = 'test_user_surname' def create_user(self): self.user.create(track_for_stat=self.TRACK_FOR_STAT, dark_theme=self.DARK_THEME, password=self.PASSWORD, first_name=self.FIRST_NAME, last_name=self.LAST_NAME) def setUp(self): self.user = MyUser(self.USERNAME) def test_create_repeatedly(self): with self.assertRaises(UserIsAlreadyExistsException): self.create_user() self.create_user() def test_create_normally(self): self.create_user() self.assertEquals(self.user.user.username, self.USERNAME) self.assertEquals(self.user.user.userprofile.track_for_stat, self.TRACK_FOR_STAT) self.assertEquals(self.user.user.first_name, self.FIRST_NAME) self.assertEquals(self.user.user.last_name, self.LAST_NAME) def test_remove_nonexistent(self): with self.assertRaises(UserNotFoundException): self.user.remove() def test_manage_access_nonexistent(self): with self.assertRaises(UserNotFoundException): self.user.manage_access('control') def test_manage_access_normally(self): self.create_user() self.user.manage_access(['control']) self.assertTrue(self.user.has_access('control')) self.user.manage_access(['logs', 'moders']) self.assertTrue(self.user.has_access('logs')) self.assertTrue(self.user.has_access('moders')) def test_manage_rank_nonexistent(self): with self.assertRaises(UserNotFoundException): self.user.manage_rank('rank2') def test_manage_rank_nonexistent_rank(self): self.create_user() with self.assertRaises(RankNotFoundException): self.user.manage_rank('nonexistent_rank') def test_manage_rank_normally(self): self.create_user() rank_data = loads(self.user.user.userprofile.ranks) self.assertEquals(rank_data['rank'], 'rank0') self.user.manage_rank('rank4') rank_data = loads(self.user.user.userprofile.ranks) self.assertEquals(rank_data['rank'], 'rank4') def test_manage_additional_ranks_nonexistent(self): with self.assertRaises(UserNotFoundException): self.user.manage_additional_ranks(['paperwork']) def test_manage_additional_ranks_nonexistent_rank(self): self.create_user() with self.assertRaises(RankNotFoundException): self.user.manage_additional_ranks(['nonexistent_rank']) def test_manage_additional_ranks_normally(self): self.create_user() rank_data = loads(self.user.user.userprofile.ranks) self.assertEquals(len(rank_data['additional']), 0) self.user.manage_additional_ranks(['paperwork', 'expert']) rank_data = loads(self.user.user.userprofile.ranks) self.assertTrue('paperwork' in rank_data['additional']) self.assertTrue('expert' in rank_data['additional']) def test_manage_additional_ranks_save_automatic_assigned_ranks(self): self.create_user() self.user.manage_additional_ranks( ['expert', 'publicaccept', 'online500']) self.user.manage_additional_ranks(['paperwork']) self.assertEquals(self.user.get_additional_ranks_names_only(), ['paperwork', 'online500', 'publicaccept']) def test_toggle_tracking_nonexistent(self): with self.assertRaises(UserNotFoundException): self.user.toggle_tracking() def test_toggle_tracking_normally(self): self.create_user() self.user.toggle_tracking() self.assertEquals(self.user.user.userprofile.track_for_stat, False if self.TRACK_FOR_STAT else True) self.user.toggle_tracking() self.assertEquals(self.user.user.userprofile.track_for_stat, True if self.TRACK_FOR_STAT else False) def test_toggle_dark_theme_nonexistent(self): with self.assertRaises(UserNotFoundException): self.user.toggle_dark_theme() def test_toggle_dark_theme_normally(self): self.create_user() self.user.toggle_dark_theme() self.assertEquals(self.user.user.userprofile.dark_theme, False if self.DARK_THEME else True) self.user.toggle_dark_theme() self.assertEquals(self.user.user.userprofile.dark_theme, True if self.DARK_THEME else False) def test_get_tracked_for_stat(self): self.create_user() self.user.toggle_tracking() authorized_users = get_tracked_for_stat() self.assertEquals( authorized_users, {self.user.username: self.user.user.userprofile.color}) def test_rating_incorrect_string(self): self.create_user() with self.assertRaises(ValueError): self.user.rate('5') def test_rating_incorrect_float(self): self.create_user() with self.assertRaises(ValueError): self.user.rate(5.0) def test_rating_incorrect_more_than_five(self): self.create_user() with self.assertRaises(ValueError): self.user.rate(6) def test_rating_incorrect_less_than_one(self): self.create_user() with self.assertRaises(ValueError): self.user.rate(0) def test_rating_normal(self): self.create_user() self.assertEquals(self.user.get_rating(), 0.0) self.assertEquals(self.user.get_total_vote(), 0) self.assertEquals(self.user.get_vote_count(), 0) self.user.rate(3) self.assertEquals(self.user.get_rating(), 3.0) self.assertEquals(self.user.get_total_vote(), 3) self.assertEquals(self.user.get_vote_count(), 1) self.user.rate(5) self.assertEquals(self.user.get_rating(), 4.0) self.assertEquals(self.user.get_total_vote(), 8) self.assertEquals(self.user.get_vote_count(), 2) self.user.rate(2) self.assertEquals(self.user.get_rating(), 3.3) self.assertEquals(self.user.get_total_vote(), 10) self.assertEquals(self.user.get_vote_count(), 3) def test_add_online_negative(self): self.create_user() with self.assertRaises(ValueError): self.user.add_online(-5) def test_add_online_normal(self): self.create_user() self.assertEquals(self.user.get_online(), 0) self.user.add_online(5) self.assertEquals(self.user.get_online(), 5) self.user.add_online(10) self.assertEquals(self.user.get_online(), 15) def test_add_online_automatic_rank_assign(self): self.create_user() self.user.add_online(502) self.assertEquals(self.user.get_additional_ranks_names_only(), ['online500']) self.user.add_online(502) self.assertEquals(self.user.get_additional_ranks_names_only(), ['online1000']) self.user.manage_additional_ranks(['paperwork', 'expert']) self.user.add_online(1000) self.assertEquals(self.user.get_additional_ranks_names_only(), ['paperwork', 'expert', 'online2000'])
def setUp(self): user = MyUser('test') user.create(True, False, 'pass', 'fist', 'last') user.manage_access(['control'])
def remove_notifications(request): user = MyUser(request.user.username) user.remove_notifications() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def setUp(self): user = MyUser('test') user.create(True, False, 'pass', 'fist', 'last')
def __create_authorized_user(): user = MyUser('authorized_user') user.create(True, False, 'pass', 'first', 'last') user.manage_access(['control']) return user
class TestModels(TestCase): def setUp(self): self.username = '******' self.moderator = MyUser(self.username) self.moderator.create(True, False, 'pass', 'first', 'last') self.osx11 = MyUser('osx11') self.osx11.create(False, False, 'pass', 'Grigory', 'Albertov') self.report = Reports(violator_nickname='test_violator', violator_donate='test_donate', violation='test_violation', comment='test_comment', server='test_server', evidence_text='test_evidence', pinned_admin=self.username, isImportant=True, isWarning=False, files=load_test_files()) @staticmethod def __get_user_notifications(user): return user.notifications.unread()[0] def test_create_new_report(self): self.report.create() self.report.refresh_from_db() report_files = loads(self.report.files)['files'] for file in report_files: self.assertTrue(path.exists(settings.SAVING_FILES_DIR + file)) notification = self.__get_user_notifications(self.osx11.user) self.assertEquals( notification.verb, '%s отправил важный отчет (#%d)' % (self.username, self.report.id)) def test_remove(self): self.report.create() report_id = self.report.id self.report.remove(self.osx11.user) with self.assertRaises(ObjectDoesNotExist): self.report.refresh_from_db() notification = self.__get_user_notifications(self.moderator.user) self.assertEquals(notification.verb, '%s удалил ваш отчет (#%d)' % ('osx11', report_id)) def test_set_non_important(self): self.report.create() self.report.set_non_important(self.osx11.user) self.report.refresh_from_db() self.assertEquals(self.report.isImportant, 0) notification = self.__get_user_notifications(self.moderator.user) self.assertEquals( notification.verb, '%s просмотрел ваш важный отчет (#%d)' % ('osx11', self.report.id)) def test_add_comment(self): self.report.create() self.report.add_comment(load_test_files(), 'test_answer', self.osx11.user) self.report.refresh_from_db() comment_files = loads(self.report.dialogue)['comments'][0]['files'] for file in comment_files: self.assertTrue(path.exists(settings.SAVING_FILES_DIR + file)) notification = self.__get_user_notifications(self.moderator.user) self.assertEquals( notification.verb, '%s добавил комментарий к вашему отчету (#%d)' % ('osx11', self.report.id))
def setUp(self): self.username = '******' self.moderator = MyUser(self.username) self.moderator.create(True, False, 'pass', 'first', 'last') self.moderator.manage_access(['moders']) self.year = dt.now().isocalendar()[0]