Example #1
0
    def send_verification_email(self, trans, email, username):
        """
        Send the verification email containing the activation link to the user's email.
        """
        if username is None:
            username = trans.user.username
        activation_link = self.prepare_activation_link(trans, escape(email))

        host = trans.request.host.split(':')[0]
        if host in ['localhost', '127.0.0.1', '0.0.0.0']:
            host = socket.getfqdn()
        body = ("Hello %s,\n\n"
                "In order to complete the activation process for %s begun on %s at %s, please click on the following link to verify your account:\n\n"
                "%s \n\n"
                "By clicking on the above link and opening a Galaxy account you are also confirming that you have read and agreed to Galaxy's Terms and Conditions for use of this service (%s). This includes a quota limit of one account per user. Attempts to subvert this limit by creating multiple accounts or through any other method may result in termination of all associated accounts and data.\n\n"
                "Please contact us if you need help with your account at: %s. You can also browse resources available at: %s. \n\n"
                "More about the Galaxy Project can be found at galaxyproject.org\n\n"
                "Your Galaxy Team" % (escape(username), escape(email),
                                      datetime.utcnow().strftime("%D"),
                                      trans.request.host, activation_link,
                                      trans.app.config.terms_url,
                                      trans.app.config.error_email_to,
                                      trans.app.config.instance_resource_url))
        to = email
        frm = trans.app.config.email_from or 'galaxy-no-reply@' + host
        subject = 'Galaxy Account Activation'
        try:
            util.send_mail(frm, to, subject, body, trans.app.config)
            return True
        except Exception:
            log.exception('Unable to send the activation email.')
            return False
Example #2
0
 def execute(cls, app, sa_session, action, job, replacement_dict):
     if action.action_arguments and 'host' in action.action_arguments:
         host = action.action_arguments['host']
     else:
         host = 'usegalaxy.org'
     frm = 'galaxy-noreply@%s' % host
     to = job.user.email
     subject = "Galaxy workflow step notification '%s'" % (job.history.name)
     outdata = ', '.join(ds.dataset.display_name() for ds in job.output_datasets)
     body = "Your Galaxy job generating dataset '%s' is complete as of %s." % (outdata, datetime.datetime.now().strftime( "%I:%M" ))
     try:
         send_mail( frm, to, subject, body, app.config )
     except Exception, e:
         log.error("EmailAction PJA Failed, exception: %s" % e)
Example #3
0
 def execute(cls, app, sa_session, action, job, replacement_dict):
     frm = app.config.email_from
     if frm is None:
         if action.action_arguments and 'host' in action.action_arguments:
             host = action.action_arguments['host']
         else:
             host = socket.getfqdn()
         frm = 'galaxy-no-reply@%s' % host
     to = job.user.email
     subject = "Galaxy workflow step notification '%s'" % (job.history.name)
     outdata = ', '.join(ds.dataset.display_name()
                         for ds in job.output_datasets)
     body = "Your Galaxy job generating dataset '%s' is complete as of %s." % (
         outdata, datetime.datetime.now().strftime("%I:%M"))
     try:
         send_mail(frm, to, subject, body, app.config)
     except Exception as e:
         log.error("EmailAction PJA Failed, exception: %s" % e)
Example #4
0
 def execute(cls, app, sa_session, action, job, replacement_dict):
     try:
         frm = app.config.email_from
         history_id_encoded = app.security.encode_id(job.history_id)
         link = app.config.galaxy_infrastructure_url + "/histories/view?id=" + history_id_encoded
         if frm is None:
             if action.action_arguments and 'host' in action.action_arguments:
                 host = action.action_arguments['host']
             else:
                 host = socket.getfqdn()
             frm = 'galaxy-no-reply@%s' % host
         to = job.user.email
         subject = "Galaxy job completion notification from history '%s'" % (job.history.name)
         outdata = ',\n'.join(ds.dataset.display_name() for ds in job.output_datasets)
         body = "Your Galaxy job generating dataset(s):\n\n{}\n\nis complete as of {}. Click the link below to access your data: \n{}".format(outdata, datetime.datetime.now().strftime("%I:%M"), link)
         send_mail(frm, to, subject, body, app.config)
     except Exception as e:
         log.error("EmailAction PJA Failed, exception: %s", unicodify(e))
Example #5
0
 def execute(cls, app, sa_session, action, job, replacement_dict, final_job_state=None):
     try:
         frm = app.config.email_from
         history_id_encoded = app.security.encode_id(job.history_id)
         link = f"{app.config.galaxy_infrastructure_url}/histories/view?id={history_id_encoded}"
         if frm is None:
             if action.action_arguments and 'host' in action.action_arguments:
                 host = action.action_arguments['host']
             else:
                 host = socket.getfqdn()
             frm = f'galaxy-no-reply@{host}'
         to = job.user.email
         subject = f"Galaxy job completion notification from history '{job.history.name}'"
         outdata = ',\n'.join(ds.dataset.display_name() for ds in job.output_datasets)
         body = f"Your Galaxy job generating dataset(s):\n\n{outdata}\n\nis complete as of {datetime.datetime.now().strftime('%I:%M')}. Click the link below to access your data: \n{link}"
         send_mail(frm, to, subject, body, app.config)
     except Exception as e:
         log.error("EmailAction PJA Failed, exception: %s", unicodify(e))
Example #6
0
 def send_activation_email(self, trans, email, username):
     """
     Send the verification email containing the activation link to the user's email.
     """
     activation_token = self.__get_activation_token(trans, escape(email))
     activation_link = url_for(controller='user',
                               action='activate',
                               activation_token=activation_token,
                               email=escape(email),
                               qualified=True)
     host = self.__get_host(trans)
     custom_message = ''
     if self.app.config.custom_activation_email_message:
         custom_message = f"{self.app.config.custom_activation_email_message}\n\n"
     body = (
         "Hello %s,\n\n"
         "In order to complete the activation process for %s begun on %s at %s, please click "
         "on the following link to verify your account:\n\n"
         "%s \n\n"
         "By clicking on the above link and opening a Galaxy account you are also confirming "
         "that you have read and agreed to Galaxy's Terms and Conditions for use of this "
         "service (%s). This includes a quota limit of one account per user. Attempts to "
         "subvert this limit by creating multiple accounts or through any other method may "
         "result in termination of all associated accounts and data.\n\n"
         "Please contact us if you need help with your account at: %s. You can also browse "
         "resources available"
         " at: %s. \n\n"
         "More about the Galaxy Project can be found at galaxyproject.org\n\n"
         "%s"
         "Your Galaxy Team" %
         (escape(username), escape(email), datetime.utcnow().strftime("%D"),
          trans.request.host, activation_link, self.app.config.terms_url,
          self.app.config.error_email_to,
          self.app.config.instance_resource_url, custom_message))
     to = email
     frm = self.app.config.email_from or f"galaxy-no-reply@{host}"
     subject = 'Galaxy Account Activation'
     try:
         util.send_mail(frm, to, subject, body, self.app.config)
         return True
     except Exception:
         log.debug(body)
         log.exception('Unable to send the activation email.')
         return False
Example #7
0
 def __register(self, trans, email=None, username=None, password=None, subscribe_checked=False, **kwd):
     """Registers a new user."""
     email = util.restore_text(email)
     username = util.restore_text(username)
     status = None
     message = None
     is_admin = trans.user_is_admin
     user = self.user_manager.create(email=email, username=username, password=password)
     if subscribe_checked:
         # subscribe user to email list
         if trans.app.config.smtp_server is None:
             status = "error"
             message = f"Now logged in as {user.email}. However, subscribing to the mailing list has failed because mail is not configured for this Galaxy instance. <br>Please contact your local Galaxy administrator."
         else:
             body = 'Join Mailing list.\n'
             to = trans.app.config.mailing_join_addr
             frm = email
             subject = 'Join Mailing List'
             try:
                 util.send_mail(frm, to, subject, body, trans.app.config)
             except Exception:
                 log.exception('Subscribing to the mailing list has failed.')
                 status = "warning"
                 message = f"Now logged in as {user.email}. However, subscribing to the mailing list has failed."
     if status != "error":
         if not is_admin:
             # The handle_user_login() method has a call to the history_set_default_permissions() method
             # (needed when logging in with a history), user needs to have default permissions set before logging in
             trans.handle_user_login(user)
             trans.log_event("User created a new account")
             trans.log_event("User logged in")
         if trans.app.config.user_activation_on:
             is_activation_sent = self.user_manager.send_activation_email(trans, email, username)
             if is_activation_sent:
                 message = f"Now logged in as {escape(user.email)}.<br>Verification email has been sent to your email address. Please verify it by clicking the activation link in the email.<br>Please check your spam/trash folder in case you cannot find the message.<br><a target=\"_top\" href=\"{url_for('/')}\">Return to the home page.</a>"
             else:
                 status = "error"
                 message = 'Unable to send activation email, please contact your local Galaxy administrator.'
                 if trans.app.config.error_email_to is not None:
                     message += f' Contact: {trans.app.config.error_email_to}'
     else:
         # User activation is OFF, proceed without sending the activation email.
         message = f"Now logged in as {escape(user.email)}.<br><a target=\"_top\" href=\"{url_for('/')}\">Return to the home page.</a>"
     return message, status, user, status is None
Example #8
0
 def reset_password(self, trans, email=None, **kwd):
     """Reset the user's password. Send an email with token that allows a password change."""
     if trans.app.config.smtp_server is None:
         return trans.show_error_message("Mail is not configured for this Galaxy instance "
                                         "and password reset information cannot be sent. "
                                         "Please contact your local Galaxy administrator.")
     message = None
     status = 'done'
     if kwd.get('reset_password_button', False):
         message = validate_email(trans, email, check_dup=False)
         if not message:
             # Default to a non-userinfo-leaking response message
             message = ("Your reset request for %s has been received.  "
                        "Please check your email account for more instructions.  "
                        "If you do not receive an email shortly, please contact an administrator." % (escape(email)))
             reset_user = trans.sa_session.query(trans.app.model.User).filter(trans.app.model.User.table.c.email == email).first()
             if not reset_user:
                 # Perform a case-insensitive check only if the user wasn't found
                 reset_user = trans.sa_session.query(trans.app.model.User).filter(func.lower(trans.app.model.User.table.c.email) == func.lower(email)).first()
             if reset_user:
                 prt = trans.app.model.PasswordResetToken(reset_user)
                 trans.sa_session.add(prt)
                 trans.sa_session.flush()
                 host = trans.request.host.split(':')[0]
                 if host in ['localhost', '127.0.0.1', '0.0.0.0']:
                     host = socket.getfqdn()
                 reset_url = url_for(controller='user',
                                     action="change_password",
                                     token=prt.token, qualified=True)
                 body = PASSWORD_RESET_TEMPLATE % (host, prt.expiration_time.strftime(trans.app.config.pretty_datetime_format),
                                                   reset_url)
                 frm = trans.app.config.email_from or f"galaxy-no-reply@{host}"
                 subject = 'Galaxy Password Reset'
                 try:
                     util.send_mail(frm, email, subject, body, trans.app.config)
                     trans.sa_session.add(reset_user)
                     trans.sa_session.flush()
                     trans.log_event(f"User reset password: {email}")
                 except Exception:
                     log.exception('Unable to reset password.')
     return trans.fill_template('/webapps/tool_shed/user/reset_password.mako',
                                message=message,
                                status=status)
Example #9
0
 def execute(cls, app, sa_session, action, job, replacement_dict):
     frm = app.config.email_from
     if frm is None:
         if action.action_arguments and "host" in action.action_arguments:
             host = action.action_arguments["host"]
         else:
             host = socket.getfqdn()
         frm = "galaxy-no-reply@%s" % host
     to = job.user.email
     subject = "Galaxy workflow step notification '%s'" % (job.history.name)
     outdata = ", ".join(ds.dataset.display_name() for ds in job.output_datasets)
     body = "Your Galaxy job generating dataset '%s' is complete as of %s." % (
         outdata,
         datetime.datetime.now().strftime("%I:%M"),
     )
     try:
         send_mail(frm, to, subject, body, app.config)
     except Exception, e:
         log.error("EmailAction PJA Failed, exception: %s" % e)
Example #10
0
    def _send_report(self, user, email=None, message=None, **kwd):
        smtp_server = self.app.config.smtp_server
        assert smtp_server, ValueError("Mail is not configured for this Galaxy instance")
        to = self.app.config.error_email_to
        assert to, ValueError("Error reporting has been disabled for this Galaxy instance")

        frm = self.app.config.email_from
        error_msg = validate_email_str(email)
        if not error_msg and self._can_access_dataset(user):
            to += f", {email.strip()}"
        subject = f"Galaxy tool error report from {email}"
        try:
            subject = "{} ({})".format(
                subject, self.app.toolbox.get_tool(self.job.tool_id, self.job.tool_version).old_id)
        except Exception:
            pass

        return util.send_mail(frm, to, subject, self.report, self.app.config, html=self.html_report)
Example #11
0
    def _send_report( self, user, email=None, message=None, **kwd ):
        smtp_server = self.app.config.smtp_server
        assert smtp_server, ValueError( "Mail is not configured for this galaxy instance" )
        to_address = self.app.config.error_email_to
        assert to_address, ValueError( "Error reporting has been disabled for this galaxy instance" )

        frm = to_address
        # Check email a bit
        email = email or ''
        email = email.strip()
        parts = email.split()
        if len( parts ) == 1 and len( email ) > 0 and self._can_access_dataset( user ):
            to = to_address + ", " + email
        else:
            to = to_address
        subject = "Galaxy tool error report from %s" % email
        # Send it
        return util.send_mail( frm, to, subject, self.report, self.app.config )
Example #12
0
    def _send_report(self, user, email=None, message=None, **kwd):
        smtp_server = self.app.config.smtp_server
        assert smtp_server, ValueError("Mail is not configured for this Galaxy instance")
        to_address = self.app.config.error_email_to
        assert to_address, ValueError("Error reporting has been disabled for this Galaxy instance")

        frm = to_address
        # Check email a bit
        email = email or ''
        email = email.strip()
        parts = email.split()
        if len(parts) == 1 and len(email) > 0 and self._can_access_dataset(user):
            to = to_address + ", " + email
        else:
            to = to_address
        subject = "Galaxy tool error report from %s" % email
        try:
            subject = "%s (%s)" % (subject, self.app.toolbox.get_tool(self.job.tool_id, self.job.tool_version).old_id)
        except Exception:
            pass

        # Send it
        return util.send_mail(frm, to, subject, self.report, self.app.config, html=self.html_report)
def handle_email_alerts(app, host, repository, content_alert_str='', new_repo_alert=False, admin_only=False):
    """
    There are 2 complementary features that enable a tool shed user to receive email notification:
    1. Within User Preferences, they can elect to receive email when the first (or first valid)
       change set is produced for a new repository.
    2. When viewing or managing a repository, they can check the box labeled "Receive email alerts"
       which caused them to receive email alerts when updates to the repository occur.  This same feature
       is available on a per-repository basis on the repository grid within the tool shed.

    There are currently 4 scenarios for sending email notification when a change is made to a repository:
    1. An admin user elects to receive email when the first change set is produced for a new repository
       from User Preferences.  The change set does not have to include any valid content.  This allows for
       the capture of inappropriate content being uploaded to new repositories.
    2. A regular user elects to receive email when the first valid change set is produced for a new repository
       from User Preferences.  This differs from 1 above in that the user will not receive email until a
       change set tha tincludes valid content is produced.
    3. An admin user checks the "Receive email alerts" check box on the manage repository page.  Since the
       user is an admin user, the email will include information about both HTML and image content that was
       included in the change set.
    4. A regular user checks the "Receive email alerts" check box on the manage repository page.  Since the
       user is not an admin user, the email will not include any information about both HTML and image content
       that was included in the change set.
    """
    sa_session = app.model.context.current
    repo = hg_util.get_repo_for_repository(app, repository=repository, repo_path=None, create=False)
    sharable_link = repository_util.generate_sharable_link_for_repository_in_tool_shed(repository, changeset_revision=None)
    smtp_server = app.config.smtp_server
    if smtp_server and (new_repo_alert or repository.email_alerts):
        # Send email alert to users that want them.
        if app.config.email_from is not None:
            email_from = app.config.email_from
        elif host.split(':')[0] in ['localhost', '127.0.0.1', '0.0.0.0']:
            email_from = 'galaxy-no-reply@' + socket.getfqdn()
        else:
            email_from = 'galaxy-no-reply@' + host.split(':')[0]
        tip_changeset = repo.changelog.tip()
        ctx = repo.changectx(tip_changeset)
        try:
            username = ctx.user().split()[0]
        except Exception:
            username = ctx.user()
        # We'll use 2 template bodies because we only want to send content
        # alerts to tool shed admin users.
        if new_repo_alert:
            template = new_repo_email_alert_template
        else:
            template = email_alert_template
        display_date = hg_util.get_readable_ctx_date(ctx)
        admin_body = string.Template(template).safe_substitute(host=host,
                                                               sharable_link=sharable_link,
                                                               repository_name=repository.name,
                                                               revision='%s:%s' % (str(ctx.rev()), ctx),
                                                               display_date=display_date,
                                                               description=ctx.description(),
                                                               username=username,
                                                               content_alert_str=content_alert_str)
        body = string.Template(template).safe_substitute(host=host,
                                                         sharable_link=sharable_link,
                                                         repository_name=repository.name,
                                                         revision='%s:%s' % (str(ctx.rev()), ctx),
                                                         display_date=display_date,
                                                         description=ctx.description(),
                                                         username=username,
                                                         content_alert_str='')
        admin_users = app.config.get("admin_users", "").split(",")
        frm = email_from
        if new_repo_alert:
            subject = "Galaxy tool shed alert for new repository named %s" % str(repository.name)
            subject = subject[:80]
            email_alerts = []
            for user in sa_session.query(app.model.User) \
                                  .filter(and_(app.model.User.table.c.deleted == false(),
                                               app.model.User.table.c.new_repo_alert == true())):
                if admin_only:
                    if user.email in admin_users:
                        email_alerts.append(user.email)
                else:
                    email_alerts.append(user.email)
        else:
            subject = "Galaxy tool shed update alert for repository named %s" % str(repository.name)
            email_alerts = json.loads(repository.email_alerts)
        for email in email_alerts:
            to = email.strip()
            # Send it
            try:
                if to in admin_users:
                    util.send_mail(frm, to, subject, admin_body, app.config)
                else:
                    util.send_mail(frm, to, subject, body, app.config)
            except Exception:
                log.exception("An error occurred sending a tool shed repository update alert by email.")
Example #14
0
def handle_email_alerts(app,
                        host,
                        repository,
                        content_alert_str='',
                        new_repo_alert=False,
                        admin_only=False):
    """
    There are 2 complementary features that enable a tool shed user to receive email notification:
    1. Within User Preferences, they can elect to receive email when the first (or first valid)
       change set is produced for a new repository.
    2. When viewing or managing a repository, they can check the box labeled "Receive email alerts"
       which caused them to receive email alerts when updates to the repository occur.  This same feature
       is available on a per-repository basis on the repository grid within the tool shed.

    There are currently 4 scenarios for sending email notification when a change is made to a repository:
    1. An admin user elects to receive email when the first change set is produced for a new repository
       from User Preferences.  The change set does not have to include any valid content.  This allows for
       the capture of inappropriate content being uploaded to new repositories.
    2. A regular user elects to receive email when the first valid change set is produced for a new repository
       from User Preferences.  This differs from 1 above in that the user will not receive email until a
       change set tha tincludes valid content is produced.
    3. An admin user checks the "Receive email alerts" check box on the manage repository page.  Since the
       user is an admin user, the email will include information about both HTML and image content that was
       included in the change set.
    4. A regular user checks the "Receive email alerts" check box on the manage repository page.  Since the
       user is not an admin user, the email will not include any information about both HTML and image content
       that was included in the change set.
    """
    sa_session = app.model.context.current
    repo = hg_util.get_repo_for_repository(app,
                                           repository=repository,
                                           repo_path=None,
                                           create=False)
    sharable_link = tool_shed.util.repository_util.generate_sharable_link_for_repository_in_tool_shed(
        repository, changeset_revision=None)
    smtp_server = app.config.smtp_server
    if smtp_server and (new_repo_alert or repository.email_alerts):
        # Send email alert to users that want them.
        if app.config.email_from is not None:
            email_from = app.config.email_from
        elif host.split(':')[0] in ['localhost', '127.0.0.1', '0.0.0.0']:
            email_from = 'galaxy-no-reply@' + socket.getfqdn()
        else:
            email_from = 'galaxy-no-reply@' + host.split(':')[0]
        tip_changeset = repo.changelog.tip()
        ctx = repo.changectx(tip_changeset)
        try:
            username = ctx.user().split()[0]
        except:
            username = ctx.user()
        # We'll use 2 template bodies because we only want to send content
        # alerts to tool shed admin users.
        if new_repo_alert:
            template = new_repo_email_alert_template
        else:
            template = email_alert_template
        display_date = hg_util.get_readable_ctx_date(ctx)
        admin_body = string.Template(template).safe_substitute(
            host=host,
            sharable_link=sharable_link,
            repository_name=repository.name,
            revision='%s:%s' % (str(ctx.rev()), ctx),
            display_date=display_date,
            description=ctx.description(),
            username=username,
            content_alert_str=content_alert_str)
        body = string.Template(template).safe_substitute(
            host=host,
            sharable_link=sharable_link,
            repository_name=repository.name,
            revision='%s:%s' % (str(ctx.rev()), ctx),
            display_date=display_date,
            description=ctx.description(),
            username=username,
            content_alert_str='')
        admin_users = app.config.get("admin_users", "").split(",")
        frm = email_from
        if new_repo_alert:
            subject = "Galaxy tool shed alert for new repository named %s" % str(
                repository.name)
            subject = subject[:80]
            email_alerts = []
            for user in sa_session.query( app.model.User ) \
                                  .filter( and_( app.model.User.table.c.deleted == false(),
                                                 app.model.User.table.c.new_repo_alert == true() ) ):
                if admin_only:
                    if user.email in admin_users:
                        email_alerts.append(user.email)
                else:
                    email_alerts.append(user.email)
        else:
            subject = "Galaxy tool shed update alert for repository named %s" % str(
                repository.name)
            email_alerts = json.loads(repository.email_alerts)
        for email in email_alerts:
            to = email.strip()
            # Send it
            try:
                if to in admin_users:
                    util.send_mail(frm, to, subject, admin_body, app.config)
                else:
                    util.send_mail(frm, to, subject, body, app.config)
            except Exception:
                log.exception(
                    "An error occurred sending a tool shed repository update alert by email."
                )