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))
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 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 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 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 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 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 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 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_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 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 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 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 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 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 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 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 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]
def setUp(self): user = MyUser('test') user.create(True, False, 'pass', 'fist', 'last') user.manage_access(['control'])
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
def setUp(self): self.user = MyUser(self.USERNAME)
def remove_notifications(request): user = MyUser(request.user.username) user.remove_notifications() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))