def su(request): """ Impersonate another user. This allows an admin to take the identity of any other user. It is meant to be used strictly for debugging. You can return to your regular user simply by logging out. This won't affect the last login time of the actual user. An email should be immediately sent out to the team, notifying of the 'su' action for security reasons. """ # SEC raise exception if user not admin user = user_from_request(request, admin=True) session = request.environ['session'] if isinstance(session, ApiToken): raise ForbiddenError('Cannot do su when authenticated with api token') real_email = user.email params = params_from_request(request) email = params.get('email') if not email: raise RequiredParameterMissingError('email') try: user = User.objects.get(email=email) except (UserNotFoundError, User.DoesNotExist): raise UserUnauthorizedError() reissue_cookie_session(request, real_email, su=user.id) # alert admins subject = "Some admin used su" body = "Admin: %s\nUser: %s\nServer: %s" % (real_email, user.email, config.CORE_URI) send_email(subject, body, config.NOTIFICATION_EMAIL['ops']) return HTTPFound('/')
def notify_user(owner, title, message="", email_notify=True, **kwargs): # Notify connected owner via amqp payload = {'title': title, 'message': message} payload.update(kwargs) if 'command' in kwargs: output = '%s\n' % kwargs['command'] if 'output' in kwargs: output += '%s\n' % kwargs['output'].decode('utf-8', 'ignore') if 'retval' in kwargs: output += 'returned with exit code %s.\n' % kwargs['retval'] payload['output'] = output amqp_publish_user(owner, routing_key='notify', data=payload) body = message + '\n' if message else '' if 'cloud_id' in kwargs: cloud_id = kwargs['cloud_id'] body += "Cloud:\n" try: cloud = Cloud.objects.get(owner=owner, id=cloud_id, deleted=None) cloud_title = cloud.title except DoesNotExist: cloud_title = '' cloud = '' if cloud_title: body += " Name: %s\n" % cloud_title body += " Id: %s\n" % cloud_id if 'machine_id' in kwargs: machine_id = kwargs['machine_id'] body += "Machine:\n" if kwargs.get('machine_name'): name = kwargs['machine_name'] else: try: name = Machine.objects.get(cloud=cloud, machine_id=machine_id).name except DoesNotExist: name = '' if name: body += " Name: %s\n" % name title += " for machine %s" % (name or machine_id) body += " Id: %s\n" % machine_id if 'error' in kwargs: error = kwargs['error'] body += "Result: %s\n" % ('Success' if not error else 'Error') if error and error is not True: body += "Error: %s" % error if 'command' in kwargs: body += "Command: %s\n" % kwargs['command'] if 'retval' in kwargs: body += "Return value: %s\n" % kwargs['retval'] if 'duration' in kwargs: body += "Duration: %.2f secs\n" % kwargs['duration'] if 'output' in kwargs: body += "Output: %s\n" % kwargs['output'].decode('utf-8', 'ignore') if email_notify: from mist.api.helpers import send_email email = owner.email if hasattr(owner, 'email') else owner.get_email() send_email("[%s] %s" % (config.PORTAL_NAME, title), body.encode('utf-8', 'ignore'), email)
def notify_admin(title, message="", team="all"): """ This will only work on a multi-user setup configured to send emails """ try: from mist.api.helpers import send_email send_email( title, message, config.NOTIFICATION_EMAIL.get(team, config.NOTIFICATION_EMAIL)) except ImportError: pass
def send(self, notification): ''' Accepts a notification and sends an email using included data. If SENDGRID_REPORTING_KEY and EMAIL_REPORT_SENDER are available in config, it uses Sendgrid to deliver the email. Otherwise, it uses plain SMTP through send_email() ''' user = notification.user to = notification.email or user.email full_name = user.get_nice_name() first_name = user.first_name or user.get_nice_name() if (hasattr(config, "SENDGRID_REPORTING_KEY") and hasattr(config, "EMAIL_REPORT_SENDER")): from sendgrid.helpers.mail import (Email, Mail, Personalization, Content, Substitution) import sendgrid self.sg_instance = sendgrid.SendGridAPIClient( apikey=config.SENDGRID_REPORTING_KEY) mail = Mail() mail.from_email = Email(config.EMAIL_REPORT_SENDER, "Mist.io Reports") personalization = Personalization() personalization.add_to(Email(to, full_name)) personalization.subject = notification.subject sub1 = Substitution("%name%", first_name) personalization.add_substitution(sub1) if "unsub_link" in notification: sub2 = Substitution("%nsub%", notification.unsub_link) personalization.add_substitution(sub2) mail.add_personalization(personalization) mail.add_content(Content("text/plain", notification.body)) if "html_body" in notification: mail.add_content(Content("text/html", notification.html_body)) mdict = mail.get() try: return self.sg_instance.client.mail.send.post( request_body=mdict) except urllib2.URLError as exc: logging.error(exc) exit() except Exception as exc: logging.error(str(exc.status_code) + ' - ' + exc.reason) logging.error(exc.to_dict) exit() else: send_email(notification.subject, notification.body, [to], sender="config.EMAIL_REPORT_SENDER")
def send(self, users=None): # FIXME Imported here due to circular dependency issues. from mist.api.notifications.models import UserNotificationPolicy if not users: users = self.ntf.owner.members elif not isinstance(users, list): users = [users] for user in users: # Prepare each user's information. Note that users may either be # instances of mist.api.users.models.User or e-mail addresses. if isinstance(user, User): to = user.email full_name = user.get_nice_name() first_name = user.first_name or full_name unsub_link = self.ntf.get_unsub_link(user.id) query_kwargs = {'owner': self.ntf.owner, 'user_id': user.id} else: to = user # Just an e-mail. full_name = first_name = "" unsub_link = self.ntf.get_unsub_link(user_id=None, email=user) query_kwargs = {'owner': self.ntf.owner, 'email': user} # Check the user's notification policy. try: np = UserNotificationPolicy.objects.get(**query_kwargs) if np.has_blocked(self.ntf): continue except UserNotificationPolicy.DoesNotExist: log.debug('No UserNotificationPolicy found for %s', user) if config.SENDGRID_EMAIL_NOTIFICATIONS_KEY: # Initialize SendGrid client. sg = SendGridAPIClient( apikey=config.SENDGRID_EMAIL_NOTIFICATIONS_KEY) mail = Mail() mail.from_email = Email(self.ntf.sender_email, self.ntf.sender_title) # Personalize e-mail. personalization = Personalization() personalization.subject = self.ntf.subject personalization.add_to(Email(to, full_name)) sub = Substitution("%name%", first_name) personalization.add_substitution(sub) if unsub_link: sub = Substitution("%nsub%", unsub_link) personalization.add_substitution(sub) mail.add_personalization(personalization) # Add content. mail.add_content(Content("text/plain", self.ntf.text_body)) if self.ntf.html_body: mail.add_content(Content("text/html", self.ntf.html_body)) # Attempt to send. try: sg.client.mail.send.post(request_body=mail.get()) except urllib2.URLError as exc: log.exception(repr(exc)) except Exception as exc: log.exception(repr(exc)) else: body = self.ntf.text_body.replace("%nsub%", unsub_link) send_email(self.ntf.subject, body, [to], sender=self.ntf.sender_email)