def lost_password(request): """ Presents lost password page - sends password reset link to specified email address. This link is valid only for 10 minutes """ form = forms.LostPasswordForm(request.POST, csrf_context=request) if request.method == 'POST' and form.validate(): user = User.by_email(form.email.data) if user: user.regenerate_security_code() user.security_code_date = datetime.datetime.utcnow() email_vars = { 'user': user, 'request': request, 'email_title': "AppEnlight :: New password request" } UserService.send_email( request, recipients=[user.email], variables=email_vars, template='/email_templates/lost_password.jinja2') msg = 'Password reset email had been sent. ' \ 'Please check your mailbox for further instructions.' request.session.flash(_(msg)) return HTTPFound(location=request.route_url('lost_password')) return {"form": form}
def send_digest(self, **kwargs): """ Build and send daily digest notification kwargs: application: application that the event applies for, user: user that should be notified request: request object since_when: reports are newer than this time value, reports: list of reports to render """ template_vars = self.report_alert_notification_vars(kwargs) title = "AppEnlight :: Daily report digest: %s - %s reports" template_vars["email_title"] = title % ( template_vars["resource_name"], template_vars["confirmed_total"], ) UserService.send_email( kwargs["request"], [self.channel_value], template_vars, "/email_templates/notify_reports.jinja2", immediately=True, silent=True, ) log_msg = "DIGEST : %s via %s :: %s reports" % ( kwargs["user"].user_name, self.channel_visible_value, template_vars["confirmed_total"], ) log.warning(log_msg)
def notify_chart_alert(self, **kwargs): """ Build and send chart alert notification Kwargs: application: application that the event applies for, event: event that is notified, user: user that should be notified request: request object """ template_vars = self.chart_alert_notification_vars(kwargs) title = ('AppEnlight :: ALERT {} value in "{}" chart' ' met alert "{}" criteria'.format( template_vars["alert_action"], template_vars["chart_name"], template_vars["action_name"], )) template_vars["email_title"] = title UserService.send_email( kwargs["request"], [self.channel_value], template_vars, "/email_templates/alert_chart.jinja2", )
def notify_report_alert(self, **kwargs): """ Build and send report alert notification Kwargs: application: application that the event applies for, event: event that is notified, user: user that should be notified request: request object """ template_vars = self.report_alert_notification_vars(kwargs) if kwargs["event"].unified_alert_action() == "OPEN": title = "AppEnlight :: ALERT %s: %s - %s %s" % ( template_vars["alert_action"], template_vars["resource_name"], kwargs["event"].values["reports"], template_vars["report_type"], ) else: title = "AppEnlight :: ALERT %s: %s type: %s" % ( template_vars["alert_action"], template_vars["resource_name"], template_vars["alert_type"].replace("_", " "), ) template_vars["email_title"] = title UserService.send_email( kwargs["request"], [self.channel_value], template_vars, "/email_templates/alert_reports.jinja2", )
def notify_report_alert(self, **kwargs): """ Build and send report alert notification Kwargs: application: application that the event applies for, event: event that is notified, user: user that should be notified request: request object """ template_vars = self.report_alert_notification_vars(kwargs) if kwargs['event'].unified_alert_action() == 'OPEN': title = 'AppEnlight :: ALERT %s: %s - %s %s' % ( template_vars['alert_action'], template_vars['resource_name'], kwargs['event'].values['reports'], template_vars['report_type'], ) else: title = 'AppEnlight :: ALERT %s: %s type: %s' % ( template_vars['alert_action'], template_vars['resource_name'], template_vars['alert_type'].replace('_', ' '), ) template_vars['email_title'] = title UserService.send_email(kwargs['request'], [self.channel_value], template_vars, '/email_templates/alert_reports.jinja2')
def notify_reports(self, **kwargs): """ Notify user of individual reports kwargs: application: application that the event applies for, user: user that should be notified request: request object since_when: reports are newer than this time value, reports: list of reports to render """ template_vars = self.report_alert_notification_vars(kwargs) if template_vars['confirmed_total'] > 1: template_vars["title"] = "AppEnlight :: %s - %s reports" % ( template_vars['resource_name'], template_vars['confirmed_total'], ) else: error_title = truncate( template_vars['reports'][0][1].error or 'slow report', 20) template_vars["title"] = "AppEnlight :: %s - '%s' report" % ( template_vars['resource_name'], error_title) UserService.send_email(kwargs['request'], [self.channel_value], template_vars, '/email_templates/notify_reports.jinja2') log_msg = 'NOTIFY : %s via %s :: %s reports' % ( kwargs['user'].user_name, self.channel_visible_value, template_vars['confirmed_total']) log.warning(log_msg)
def check_user_report_notifications(resource_id): since_when = datetime.utcnow() try: request = get_current_request() application = ApplicationService.by_id(resource_id) if not application: return error_key = REDIS_KEYS["reports_to_notify_per_type_per_app"].format( ReportType.error, resource_id) slow_key = REDIS_KEYS["reports_to_notify_per_type_per_app"].format( ReportType.slow, resource_id) error_group_ids = Datastores.redis.smembers(error_key) slow_group_ids = Datastores.redis.smembers(slow_key) Datastores.redis.delete(error_key) Datastores.redis.delete(slow_key) err_gids = [int(g_id) for g_id in error_group_ids] slow_gids = [int(g_id) for g_id in list(slow_group_ids)] group_ids = err_gids + slow_gids occurence_dict = {} for g_id in group_ids: key = REDIS_KEYS["counters"]["report_group_occurences"].format( g_id) val = Datastores.redis.get(key) Datastores.redis.delete(key) if val: occurence_dict[g_id] = int(val) else: occurence_dict[g_id] = 1 report_groups = ReportGroupService.by_ids(group_ids) report_groups.options(sa.orm.joinedload(ReportGroup.last_report_ref)) ApplicationService.check_for_groups_alert( application, "alert", report_groups=report_groups, occurence_dict=occurence_dict, ) users = set([ p.user for p in ResourceService.users_for_perm(application, "view") ]) report_groups = report_groups.all() for user in users: UserService.report_notify( user, request, application, report_groups=report_groups, occurence_dict=occurence_dict, ) for group in report_groups: # marks report_groups as notified if not group.notified: group.notified = True except Exception as exc: print_traceback(log) raise
def comment_create(request): """ Creates user comments for report group, sends email notifications of said comments """ report_group = request.context.report_group application = request.context.resource form = forms.CommentForm(MultiDict(request.unsafe_json_body), csrf_context=request) if request.method == 'POST' and form.validate(): comment = ReportComment(owner_id=request.user.id, report_time=report_group.first_timestamp) form.populate_obj(comment) report_group.comments.append(comment) perm_list = application.users_for_perm('view') uids_to_notify = [] users_to_notify = [] for perm in perm_list: user = perm.user if ('@{}'.format(user.user_name) in comment.body and user.id not in uids_to_notify): uids_to_notify.append(user.id) users_to_notify.append(user) commenters = ReportGroupService.users_commenting( report_group, exclude_user_id=request.user.id) for user in commenters: if user.id not in uids_to_notify: uids_to_notify.append(user.id) users_to_notify.append(user) for user in users_to_notify: email_vars = {'user': user, 'commenting_user': request.user, 'request': request, 'application': application, 'report_group': report_group, 'comment': comment, 'email_title': "AppEnlight :: New comment"} UserService.send_email( request, recipients=[user.email], variables=email_vars, template='/email_templates/new_comment_report.jinja2') request.session.flash(_('Your comment was created')) return comment.get_dict() else: return form.errors
def assign_users(request): """ Assigns specific report group to user for review - send email notification """ report_group = request.context.report_group application = request.context.resource currently_assigned = [u.user_name for u in report_group.assigned_users] new_assigns = request.unsafe_json_body # first unassign old users for user_name in new_assigns['unassigned']: if user_name in currently_assigned: user = User.by_user_name(user_name) report_group.assigned_users.remove(user) comment = ReportComment(owner_id=request.user.id, report_time=report_group.first_timestamp) comment.body = 'Unassigned group from @%s' % user_name report_group.comments.append(comment) # assign new users for user_name in new_assigns['assigned']: if user_name not in currently_assigned: user = User.by_user_name(user_name) if user in report_group.assigned_users: report_group.assigned_users.remove(user) DBSession.flush() assignment = ReportAssignment( owner_id=user.id, report_time=report_group.first_timestamp, group_id=report_group.id) DBSession.add(assignment) comment = ReportComment(owner_id=request.user.id, report_time=report_group.first_timestamp) comment.body = 'Assigned report_group to @%s' % user_name report_group.comments.append(comment) email_vars = {'user': user, 'request': request, 'application': application, 'report_group': report_group, 'email_title': "AppEnlight :: Assigned Report"} UserService.send_email(request, recipients=[user.email], variables=email_vars, template='/email_templates/assigned_report.jinja2') return True
def notify_uptime_alert(self, **kwargs): """ Build and send uptime alert notification Kwargs: application: application that the event applies for, event: event that is notified, user: user that should be notified request: request object """ template_vars = self.uptime_alert_notification_vars(kwargs) title = 'AppEnlight :: ALERT %s: %s has uptime issues' % ( template_vars['alert_action'], template_vars['resource_name'], ) template_vars['email_title'] = title UserService.send_email(kwargs['request'], [self.channel_value], template_vars, '/email_templates/alert_uptime.jinja2')
def users_list(request): """ Returns users list """ props = ['user_name', 'id', 'first_name', 'last_name', 'email', 'last_login_date', 'status'] users = UserService.all() users_dicts = [] for user in users: u_dict = user.get_dict(include_keys=props) u_dict['gravatar_url'] = user.gravatar_url(s=20) users_dicts.append(u_dict) return users_dicts
def alert_channels_POST(request): """ Creates a new email alert channel for user, sends a validation email """ user = request.user form = forms.EmailChannelCreateForm(MultiDict(request.unsafe_json_body), csrf_context=request) if not form.validate(): return HTTPUnprocessableEntity(body=form.errors_json) email = form.email.data.strip() channel = EmailAlertChannel() channel.channel_name = 'email' channel.channel_value = email security_code = generate_random_string(10) channel.channel_json_conf = {'security_code': security_code} user.alert_channels.append(channel) email_vars = { 'user': user, 'email': email, 'request': request, 'security_code': security_code, 'email_title': "AppEnlight :: " "Please authorize your email" } UserService.send_email(request, recipients=[email], variables=email_vars, template='/email_templates/authorize_email.jinja2') request.session.flash(_('Your alert channel was ' 'added to the system.')) request.session.flash( _('You need to authorize your email channel, a message was ' 'sent containing necessary information.'), 'warning') DBSession.flush() channel.get_dict()
def register(request): """ Render register page with form Also handles oAuth flow for registration """ login_url = request.route_url('ziggurat.routes.sign_in') if request.query_string: query_string = '?%s' % request.query_string else: query_string = '' referrer = '%s%s' % (request.path, query_string) if referrer in [login_url, '/register', '/register?sign_in=1']: referrer = '/' # never use the login form itself as came_from sign_in_form = forms.SignInForm(came_from=request.params.get( 'came_from', referrer), csrf_context=request) # populate form from oAuth session data returned by authomatic social_data = request.session.get('zigg.social_auth') if request.method != 'POST' and social_data: log.debug(social_data) user_name = social_data['user'].get('user_name', '').split('@')[0] form_data = { 'user_name': user_name, 'email': social_data['user'].get('email') } form_data['user_password'] = str(uuid.uuid4()) form = forms.UserRegisterForm(MultiDict(form_data), csrf_context=request) form.user_password.widget.hide_value = False else: form = forms.UserRegisterForm(request.POST, csrf_context=request) if request.method == 'POST' and form.validate(): log.info('registering user') # insert new user here if request.registry.settings['appenlight.disable_registration']: request.session.flash(_('Registration is currently disabled.')) return HTTPFound(location=request.route_url('/')) new_user = User() DBSession.add(new_user) form.populate_obj(new_user) new_user.regenerate_security_code() new_user.status = 1 new_user.set_password(new_user.user_password) new_user.registration_ip = request.environ.get('REMOTE_ADDR') if social_data: handle_social_data(request, new_user, social_data) email_vars = { 'user': new_user, 'request': request, 'email_title': "AppEnlight :: Start information" } UserService.send_email(request, recipients=[new_user.email], variables=email_vars, template='/email_templates/registered.jinja2') request.session.flash(_('You have successfully registered.')) DBSession.flush() headers = security.remember(request, new_user.id) return HTTPFound(location=request.route_url('/'), headers=headers) settings = request.registry.settings social_plugins = {} if settings.get('authomatic.pr.twitter.key', ''): social_plugins['twitter'] = True if settings.get('authomatic.pr.google.key', ''): social_plugins['google'] = True if settings.get('authomatic.pr.github.key', ''): social_plugins['github'] = True if settings.get('authomatic.pr.bitbucket.key', ''): social_plugins['bitbucket'] = True return { "form": form, "sign_in_form": sign_in_form, "social_plugins": social_plugins }