def push(request): """ data pushed by standalone python script (run by munin-limits) """ json_alerts = request.POST.get("alerts") if not json_alerts: return alerts = json.loads(json_alerts) opened_alerts = Alert.objects.filter(checked=False) for a in alerts: alert = Alert(host=a["host"], group=a["group"], category=a["category"], title=a["title"], value=a["value"], label=a["label"], atype=a["type"], arange=a["range"], ipaddr=a.get("ip", ""), extinfo=a["extinfo"]) for oa in opened_alerts: if oa == alert: oa.tick(alert) alert = None break if alert: alert.save() return HttpResponse(200, 'Good!')
def done(self, request, form_list): data = {} for form in form_list: data.update(form.cleaned_data) # Send alert alert = Alert(sent_by = data['sent_by'], title = data['title'], details = data['details'], level = data['level'], ) if data['send_to'] == 'all': alert_userlist(alert, User.objects.all()) if data['send_to'] == 'group': alert_groups(alert, data['sent_to']) if data['send_to'] == 'user': alert.sent_to = data['sent_to'] alert.save() # Display success message and redirect to changelist: return self._model_admin.response_add(request, alert)
def run(self, manual=False): hardcoded_reports = HardcodedReport.objects.filter(report=self) queries = Query.objects.filter(report=self) runs = [] for report in hardcoded_reports: runs.append(report.run(manual=manual)) for query in queries: runs.append(query.run(manual=manual)) if self.alert: for run in runs: for result in run.result_set.all(): for row_map in result.table_rendered().row_maps(): if 'EMPLID' in row_map: # for more complicated Alert handling, we need # to pass in actual unique_fields unique_fields = ["EMPLID"] Alert.create(row_map, self.alert, unique_fields) for rule in self.expired_schedule_rules(): rule.set_next_run() rule.save() failed_runs = [run for run in runs if run.success == False] if len(failed_runs) > 0: self.failure_notification(failed_runs[0]) return runs
def edit_profile(request): profile = request.user.profile if request.POST: form = EditProfileForm(request.POST, profile=profile) form2 = EditUserForm(request.POST, instance=request.user) if form.is_valid() and form2.is_valid(): data = form.save(commit=False) profile.bio = data['bio'] profile.slotName = data['slotName'] profile.eventName = data['eventName'] profile.save() form2.save() alert = Alert(user=request.user, text="Profile updated", color=Alert.getYellow()) alert.saveIP(request) return redirect('/accounts/profile/') form = EditProfileForm( initial={ 'bio': profile.bio, 'slotName': profile.slotName, 'eventName': profile.eventName }) form2 = EditUserForm(instance=request.user) return render(request, 'accounts/edit_profile.html', { "form": form, 'profile': profile, "form2": form2 })
def patch(self, request): from alerts.models import Alert updated = False agent = get_object_or_404(Agent, agent_id=request.data["agent_id"]) if pyver.parse(request.data["version"]) > pyver.parse( agent.version ) or pyver.parse(request.data["version"]) == pyver.parse( settings.LATEST_AGENT_VER ): updated = True agent.version = request.data["version"] agent.last_seen = djangotime.now() agent.save(update_fields=["version", "last_seen"]) # change agent update pending status to completed if agent has just updated if ( updated and agent.pendingactions.filter( # type: ignore action_type="agentupdate", status="pending" ).exists() ): agent.pendingactions.filter( # type: ignore action_type="agentupdate", status="pending" ).update(status="completed") # handles any alerting actions if Alert.objects.filter(agent=agent, resolved=False).exists(): Alert.handle_alert_resolve(agent) # get any pending actions if agent.pendingactions.filter(status="pending").exists(): # type: ignore agent.handle_pending_actions() return Response("ok")
def editField(request, user_slot_id, field): user_slot = User_Slot.objects.get(id=user_slot_id) if user_slot.parentSlot.parentGroup is not None: group = user_slot.parentSlot.parentGroup else: group = user_slot.parentSlot.parentEvent.parentGroup if not group.get_is_organzer(request.user): alert = Alert(user=request.user, text="You must be an organizer to edit extra fields", color=Alert.getRed()) alert.saveIP(request) return redirect('/volunteer/slot/' + str(user_slot.parentSlot.id)) if group.get_is_organzer(request.user): if request.method == 'POST': form = FieldForm(request.POST) if form.is_valid(): newVal = form.save() user_slot.set_extra(field, newVal) user_slot.save() return redirect('/volunteer/slot/' + str(user_slot.parentSlot.id)) else: form = FieldForm(initial={"field": user_slot.get_extra()[field]}) return render( request, 'organizer/editField.html', { 'form': form, 'user_slot': user_slot, 'slotField': field, 'val': user_slot.get_extra()[field] }) return redirect('/volunteer/slot/' + str(user_slot.parentSlot.id))
def done(self, request, form_list): data = {} for form in form_list: data.update(form.cleaned_data) # Send alert alert = Alert( sent_by=data['sent_by'], title=data['title'], details=data['details'], level=data['level'], ) if data['send_to'] == 'all': alert_userlist(alert, User.objects.all()) if data['send_to'] == 'group': alert_groups(alert, data['sent_to']) if data['send_to'] == 'user': alert.sent_to = data['sent_to'] alert.save() # Display success message and redirect to changelist: return self._model_admin.response_add(request, alert)
def edit(request): # Makes sure the user is an organizer is_organizer = False for g in request.user.groups.all(): if g.name == 'Organizer': is_organizer = True if not is_organizer: Alert.not_permitted(request) return redirect('/') # Gets the page type type = request.GET.get('type', 'html') # If the page type is normal, send them to the single slot page for now if type == 'html' or type == 'singleSlot': if request.method == 'POST': form = NewSingleSlotForm(request.POST, user=request.user) if form.is_valid(): slot = form.save(commit=False) slot.save() else: form = NewSingleSlotForm(user=request.user) # Filter this by single slot events in the future return render(request, 'organizer/add_single_slot.html', {'form': form}) elif type == 'event': if request.method == 'POST': form = NewEventForm(request.POST, user=request.user) if form.is_valid(): slot = form.save(commit=False) slot.save() else: form = NewEventForm(user=request.user) return render(request, 'organizer/add_event.html', {'form': form})
def patch(self, request, pk, agentid): from alerts.models import Alert from logs.models import AuditLog agent = get_object_or_404(Agent, agent_id=agentid) task = get_object_or_404(AutomatedTask, pk=pk) serializer = TaskRunnerPatchSerializer( instance=task, data=request.data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save(last_run=djangotime.now()) status = "failing" if task.retcode != 0 else "passing" new_task: AutomatedTask = AutomatedTask.objects.get(pk=task.pk) new_task.status = status new_task.save() if status == "passing": if Alert.objects.filter(assigned_task=new_task, resolved=False).exists(): Alert.handle_alert_resolve(new_task) else: Alert.handle_alert_failure(new_task) AuditLog.objects.create( username=agent.hostname, agent=agent.hostname, object_type="agent", action="task_run", message=f"Scheduled Task {task.name} was run on {agent.hostname}", after_value=AutomatedTask.serialize(new_task), ) return Response("ok")
def editSignOut(request, user_slot_id): user_slot = User_Slot.objects.get(id=user_slot_id) if user_slot.parentSlot.parentEvent is not None: group = user_slot.parentSlot.parentEvent.parentGroup else: group = user_slot.parentSlot.parentGroup if not group.get_is_organzer(request.user): Alert.not_permitted(request) return ('/volunteer/slot/' + str(user_slot.parentSlot.id)) if group.get_is_organzer(request.user): if request.method == 'POST': form = EditTimeForm(request.POST) if form.is_valid(): signout = form.save() user_slot.signout = signout user_slot.save() user_slot.updateDeltaTimes() return redirect('/volunteer/slot/' + str(user_slot.parentSlot.id)) else: form = EditTimeForm() return render(request, 'organizer/editTime.html', { 'form': form, 'user_slot': user_slot, 'type': 'Out' }) return redirect('/volunteer/slot/' + str(user_slot.parentSlot.id))
def logout(self): """ Removes any alerts for the current owner, then refreshes the alert_key. """ Alert.clear(self.owner) del self[:] self.owner = alert_key(self.session)
def test_alert_body_change_to_null(self): u = User(username='******', password='******', email='*****@*****.**') u.save() a = Alert(user=u, body='this is a test message') a.save() a.body = '' self.assertEqual(a.body, '')
def test_alert_read_toggle_false(self): u = User(username='******', password='******', email='*****@*****.**') u.save() a = Alert(user=u, read=True) a.save() a.read = False self.assertEqual(a.read, False)
def volunteer(request, slot_id): # next = request.GET.get('next') slot = Slot.objects.get(id=slot_id) user_slot = User_Slot.objects.filter(parentSlot=slot, volunteer__isnull=True).first() slots_filled_by_this_user = User_Slot.objects.filter( parentSlot=slot, volunteer=request.user).first() if slot.parentEvent is not None: group = slot.parentEvent.parentGroup else: group = slot.parentGroup if slot.maxVolunteers == 0: # and slots_filled_by_this_user is None: user_slot = User_Slot(parentSlot=slot, accepted="Yes") # # elif slots_filled_by_this_user is not None: # alert = Alert(user=request.user, text="Already volunteered", color=Alert.getRed()) # alert.saveIP(request) # return redirect('/volunteer/slot/' + str(slot_id)) elif user_slot is None: alert = Alert(user=request.user, text="Already at Max Volunteers", color=Alert.getRed()) alert.saveIP(request) return redirect('/volunteer/slot/' + str(slot_id)) user_slot.volunteer = request.user user_slot.accepted = "Yes" if slot.get_extra() is not None: ans = {} for i in slot.get_extra(): if i != '': ans[i] = '-' user_slot.extraFields = ans user_slot.save() name = slot.title feed_entry = Feed_Entry(group=group, user=request.user, datetime=get_dt(), description="Volunteered for \"" + name, url="/volunteer/slot/" + str(slot.id), private=slot.private) feed_entry.save() alert = Alert(user=request.user, text="Volunteered for " + slot.title, color=Alert.getGreen()) alert.saveIP(request) return redirect('/volunteer/slot/' + str(slot.id))
def _create_alert(self): """ Generates an Alert based on the Monitor's alert_level. Returns the saved Alert. """ title = self._get_title() alert = Alert(title=title, level=self.alert_level, alarm=self, distillery=self.last_active_distillery, doc_id=self.last_saved_doc) alert.save() return alert
def addSingleSlot(request, group_id): group = Group.objects.get(id=group_id) if not Group.get_is_organzer(group, request.user): alert = Alert(user=request.user, text="Only organizers can add single slots", color=Alert.getRed()) alert.saveIP(request) return redirect('/volunteer/slots') if request.method == 'GET': form = NewSlotForm(user=request.user, parentEvent=None, initial={'private': group.private}) else: form = NewSlotForm(request.POST, user=request.user, parentEvent=None, initial={'private': group.private}) if form.is_valid(): slot = form.save(commit=False) slot.parentGroup = group slot.save() ans = OrderedDict() for i in slot.get_extra(): if i != '' and i != ' ': ans[i] = '-' for x in range(0, slot.maxVolunteers): user_slot = User_Slot(volunteer=None, parentSlot=slot) user_slot.save_extra(ans) user_slot.save() feed_entry = Feed_Entry(group=group, user=request.user, datetime=get_dt(), description="Created single slot \"" + str(slot.title), url="/volunteer/slot/" + str(slot.id), private=False) feed_entry.save() alert = Alert(user=request.user, text="Created slot " + slot.title, color=Alert.getBlue()) alert.saveIP(request) return redirect('/volunteer/slots/' + str(slot.id)) return render(request, 'organizer/add_slot.html', {'form': form})
def addUserManually(request, slot_id): slot = Slot.objects.get(id=slot_id) group = slot.get_group() if not group.get_is_organzer(request.user): Alert.not_permitted(request) return redirect('/volunteer/slot/' + str(slot.id)) if group.get_is_organzer(request.user): return render(request, 'organizer/pick_volunteer.html', { 'slot': slot, 'group': group }) return redirect('/volunteer/slot/' + str(slot.id))
def edit_password(request): user = request.user form = PasswordChangeForm(user=request.user, data=request.POST) if request.POST: if form.is_valid(): form.save() update_session_auth_hash(request, user) alert = Alert(user=request.user, text="Password updated", color=Alert.getYellow()) alert.saveIP(request) return redirect('/accounts/profile') return render(request, 'accounts/edit_password.html', {"form": form})
def signin(request, user_slot_id): next = request.GET.get('next') user_slot = User_Slot.objects.get(id=user_slot_id) group = user_slot.parentSlot.get_group() if (user_slot.volunteer != None and group.get_is_organzer(request.user)): user_slot.signin = get_dt() user_slot.save() alert = Alert(user=request.user, text="Signed in " + user_slot.volunteer.username, color=Alert.getYellow()) alert.saveIP(request) return redirect(next)
def test_alert_group(self): """ Tests the ability of the system to alert a group of users """ # Create groups group = Group.objects.create(name='test1') # Create a load of users for i in range(50): user = User.objects.create(username='******' % (i)) if settings.NONREL: update_user_groups(user, [group]) else: group.user_set.add(user) for i in range(50, 100): user = User.objects.create(username='******' % (i)) alert = Alert( sent_by='Tester', title='Test title', details='No details', level='Notice', ) alert_groups(alert, group) self.assertEquals(len(Alert.objects.all()), 50)
def track_stories_from_session_data(self, user): story_id = self.request.session.get("wants_to_track", None) if story_id is not None: try: story = Story.objects.get(id=story_id) try: Alert.objects.get(story=story, user=user) # inform the user that he is already subscribed # to this story except Alert.DoesNotExist: new_alert = Alert(story=story, user=user) new_alert.save() except Story.DoesNotExist: pass self.request.session["wants_to_track"] = None
def agent_outages_task() -> None: from alerts.models import Alert agents = Agent.objects.only( "pk", "last_seen", "offline_time", "overdue_time", "overdue_email_alert", "overdue_text_alert", "overdue_dashboard_alert", ) for agent in agents: if agent.status == "overdue": Alert.handle_alert_failure(agent)
def update(request, group_id): group = Group.objects.get(id=group_id) owner = group.owner if request.user.is_authenticated(): form = EditGroupForm(request.POST, id=group_id) if form.is_valid(): data = form.save(commit=False) group.name = data['name'] group.tagline = data['tagline'] group.description = data['description'] group.email = data['email'] group.website = data['website'] group.location = data['location'] group.address = data['address'] group.city = data['city'] group.state = data['state'] group.zip_code = data['zip_code'] group.approvalNeeded = data['approvalNeeded'] group.private = data['private'] group.save() alert = Alert(user=request.user, text="Updated group " + group.name, color=Alert.getBlue()) alert.saveIP(request) return redirect("/groups/" + str(group.id)) form = EditGroupForm(id=group_id, initial={ 'name': group.name, 'tagline': group.tagline, 'description': group.description, 'email': group.email, 'website': group.website, 'location': group.location, 'address': group.address, 'city': group.city, 'state': group.state, 'zip_code': group.zip_code, 'approvalNeeded': group.approvalNeeded, 'private': group.private }) return render(request, 'groups/edit_group.html', {'form': form})
def signup(request): # Checks if the user is sending their data (POST) or getting the form (GET) if (request.method == 'POST'): form = SignupForm(request.POST) # Makes sure the user filled out the form correctly as dictated by forms.py if form.is_valid(): user = form.save(commit=False) # Sets the user to deactive until they confirm email user.is_active = False # Saves the user to the server user.save() # Gets the current domain in order to send the email current_site = get_current_site(request) # Sends the user an email based on the email template and the info passed in here message = render_to_string( 'emails/activate_account.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'Activate your Sapphire Account!' to_email = form.cleaned_data.get('email') email = EmailMultiAlternatives(mail_subject, message, to=[to_email]) email.content_subtype = 'html' email.mixed_subtype = 'related' fp = open('static/img/logos.ico/ms-icon-70x70.png', 'rb') logo = MIMEImage(fp.read()) logo.add_header('Content-ID', '<logo>') email.attach(logo) email.send() alert = Alert( user=user, text= "Click on the link sent to your email to confirm your account", color=Alert.getYellow()) alert.saveIP(request) return redirect('/login') #return render(request, 'accounts/please_confirm.html') else: form = SignupForm() return render(request, 'accounts/signup.html', {'form': form})
def setUp(self): self.alert = Alert(level='HIGH', status=0, distillery=self.distillery, doc_id=1, alarm=self.watchdog) logging.disable(logging.ERROR)
def sendEventOpeningNotification(request, event_id): event = Event.objects.get(pk=event_id) group = event.parentGroup if not group.get_is_organzer(request.user): Alert.not_permitted(request) return redirect('/volunteer/event/' + str(event.id)) if request.method == 'POST': # form = SlotOpeningMailListForm(request.POST, all_members=list(chain(group.volunteers, group.organizers))) form = SlotOpeningMailListForm(request.POST, volunteers=group.volunteers, organizers=group.organizers) if form.is_valid(): mail_list = form.cleaned_data.get('organizers').all( ) | form.cleaned_data.get('volunteers').all() current_site = get_current_site(request) for recipient in mail_list: message = render_to_string( 'emails/event_create_alert.html', { 'user': recipient, 'event': event, 'group': group, 'domain': current_site.domain, 'slots': Slot.objects.filter(parentEvent=event), }) mail_subject = 'Sign up for a ' + group.name + ' Activity!' to_email = recipient.email email = EmailMultiAlternatives(mail_subject, message, to=[to_email]) email.content_subtype = 'html' email.mixed_subtype = 'related' fp = open('static/img/logos.ico/ms-icon-70x70.png', 'rb') logo = MIMEImage(fp.read()) logo.add_header('Content-ID', '<logo>') email.attach(logo) email.send() return redirect('/volunteer/event/' + str(event_id)) else: form = SlotOpeningMailListForm(volunteers=group.volunteers, organizers=group.organizers) return render(request, 'organizer/selectEmailRecipients.html', {'form': form})
def handle(self, *args, **options): # csv file csv_path = os.path.abspath(options['csv_file'][0]) csv_delimiter = options['csv_delimiter'] # alert details alert_querystring = options['querystring'] alert_title = options['title'] alert_latest_alert_date = options['latest_alert_date'] if alert_latest_alert_date: alert_latest_alert_date = datetime \ .strptime(options['latest_alert_date'], '%Y-%m-%d') \ .replace(hour=12, minute=0) alert_latest_alert_date = timezone.make_aware( alert_latest_alert_date) alert_frequency = options['frequency'] alert_validated = options['validated'] # build list of alerts self.stdout.write('Building the list of alerts...') alerts = [] with open(csv_path) as csv_file: csvreader = csv.DictReader(csv_file, delimiter=csv_delimiter) if 'email' not in csvreader.fieldnames: raise KeyError('\'email\' column missing') for index, row in enumerate(csvreader): alert = Alert(email=row['email']) if alert_querystring: alert.querystring = alert_querystring if alert_title: alert.title = alert_title if alert_latest_alert_date: alert.latest_alert_date = alert_latest_alert_date if alert_frequency: alert.alert_frequency = alert_frequency if alert_validated: alert.validate() alerts.append(alert) self.stdout.write("Build alert '{}' for {}".format( alert.title, alert.email)) # create all the alerts simultaneously alerts_created = Alert.objects.bulk_create(alerts) # send confirmation email alerts_created_not_validated = [ alert for alert in alerts_created if not alert.validated ] # noqa self.stdout.write('Sending validation emails for {} alerts'.format( len(alerts_created_not_validated))) for alert in alerts_created_not_validated: send_alert_confirmation_email.delay(alert.email, alert.token) self.stdout.write( self.style.SUCCESS('Done! %d alerts created.' % (len(alerts_created))))
def __call__(self, text, level=None, title=None, prefix=None, important=None): """ Adds a new alert to the list, if theres a delay adds it to the database Returns the index at which the alert is at, so you can change it afterwards """ alert = Alert( text=text or '', title=title or '', prefix=prefix or '', level=level or settings.ALERT_DEFAULT_LEVEL, owner=self.owner ) if important is None: important = level in settings.ALERT_IMPORTANT_LEVELS alert.closable = not important self.append(alert) return alert
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['images'] = Image.objects.filter( product=context['product']).order_by('-primary') context['prices'] = Price.objects.filter(listing__product=context['product'])\ .order_by('listing', '-updated_time').distinct('listing') alert = Alert(product=context['product']) context['alert_form'] = AlertForm(instance=alert) return context
def invite(request, action): if request.method == 'POST': if action == 'send': team_select_form = TeamSelectForm(data=request.POST) user_select_form = UserSearchForm(data=request.POST) if team_select_form.is_valid() and user_select_form.is_valid(): team = team_select_form.cleaned_data['team'] user = user_select_form.cleaned_data['user'] if request.user in team.members.all(): if user in team.members.all(): # User already on team pass elif Invite.objects.filter(team=team, user=user).exists(): # Invite already exists pass else: invite = Invite(team=team, user=user); invite.save() alert = Alert( user=user, subject='New Team Invite', body='You have been invited to join team <em>%s</em>.'%(team.name), target=Target.objects.get_or_create(invite=invite)[0]).save() else: # User does not have permission to send invite pass return redirect(reverse('teams:index', kwargs={'team_id':team.id})) elif action == 'accept': return join(request) elif action == 'decline': team_select_form = TeamSelectForm(data=request.POST) if team_select_form.is_valid(): team = team_select_form.cleaned_data['team'] if Invite.objects.filter(team=team, user=request.user).exists(): Invite.objects.filter(team=team, user=request.user).delete() return redirect(reverse('teams:index', kwargs={'team_id':team.id})) elif action == 'cancel': invite_form = InviteForm(data=request.POST) if invite_form.is_valid(): invite = invite_form.cleaned_data['invite'] if request.user in invite.team.members.all(): invite.delete() return redirect(reverse('teams:index', kwargs={'team_id':invite.team.id})) return redirect(reverse('teams:index'))
def leave(request, group_id): group = Group.objects.get(id=group_id) if (group.get_is_organzer(request.user) and group.get_is_owner(request.user) == False): group.organizers.remove(request.user) group.save() if (group.get_is_member(request.user)): group.volunteers.remove(request.user) group.save() if (group.get_is_owner(request.user)): return render(request, "groups/pickNewOwner.html", {"organizers": group.organizers.all()}) alert = Alert(user=request.user, text="Left " + str(group.name), color=Alert.getRed()) alert.saveIP(request) return redirect('/groups/' + str(group_id))
def signout(request, user_slot_id): next = request.GET.get('next') user_slot = User_Slot.objects.get(id=user_slot_id) if (user_slot.parentSlot.parentEvent != None): group = user_slot.parentSlot.parentEvent.parentGroup else: group = user_slot.parentSlot.parentGroup if (user_slot.volunteer != None and group.get_is_organzer(request.user)): user_slot.signout = get_dt() user_slot.save() user_slot.updateDeltaTimes() alert = Alert(user=request.user, text="Signed out " + user_slot.volunteer.username, color=Alert.getYellow()) alert.saveIP(request) return redirect(next)
def add(request): if request.user.is_authenticated(): if request.method == 'GET': form = NewGroupForm(owner=request.user) else: form = NewGroupForm(request.POST, owner=request.user) if form.is_valid(): group = form.save(commit=False) group.save() alert = Alert(user=request.user, text="Created group " + group.name, color=Alert.getBlue()) alert.saveIP(request) return redirect("/groups/" + str(group.id)) return render(request, 'groups/add_group.html', {'form': form}) else: return redirect('login')
def _create_alert(self, level, doc_obj): """ Takes an alert level, a distillery, and a document id. Returns an Alert object. """ data = json_encodeable(doc_obj.data) return Alert(level=level, alarm=self, distillery=doc_obj.distillery, doc_id=doc_obj.doc_id, data=data)
def __init__(self, session, owner): super(Alerts, self).__init__(Alert.get_alerts(owner)) self.session = session self.owner = owner