Exemplo n.º 1
0
def send_invitation(invitation, template_name='im/invitation.txt'):
    """
    Send invitation email.
    """
    subject = _(astakos_messages.INVITATION_EMAIL_SUBJECT)
    index_url = reverse('index', urlconf="synnefo.webproject.urls")
    url = '%s?code=%d' % (join_urls(settings.BASE_HOST, index_url,
                                    invitation.code))
    message = render_to_string(
        template_name, {
            'invitation': invitation,
            'url': url,
            'baseurl': settings.BASE_URL,
            'support': settings.CONTACT_EMAIL
        })
    sender = settings.SERVER_EMAIL
    send_mail(subject,
              message,
              sender, [invitation.username],
              connection=get_connection())
    msg = 'Sent invitation %s'
    logger.log(settings.LOGGING_LEVEL, msg, invitation)
    inviter_invitations = invitation.inviter.invitations
    invitation.inviter.invitations = max(0, inviter_invitations - 1)
    invitation.inviter.save()
Exemplo n.º 2
0
def _send_admin_notification(
    template_name,
    context=None,
    user=None,
    msg="",
    subject='alpha2 testing notification',
):
    """
    Send notification email to settings.HELPDESK + settings.MANAGERS +
    settings.ADMINS.
    """
    if context is None:
        context = {}
    if not 'user' in context:
        context['user'] = user

    message = render_to_string(template_name, context)
    sender = settings.SERVER_EMAIL
    recipient_list = [
        e[1] for e in settings.HELPDESK + settings.MANAGERS + settings.ADMINS
    ]
    send_mail(subject,
              message,
              sender,
              recipient_list,
              connection=get_connection())
    if user:
        msg = 'Sent admin notification (%s) for user %s' % (msg,
                                                            user.log_display)
    else:
        msg = 'Sent admin notification (%s)' % msg

    logger.log(settings.LOGGING_LEVEL, msg)
Exemplo n.º 3
0
def send_plain(user,
               sender=settings.SERVER_EMAIL,
               subject=_(astakos_messages.PLAIN_EMAIL_SUBJECT),
               template_name='im/plain_email.txt',
               text=None):
    """Send mail to user with fully customizable sender, subject and body.

    If the function is provided with a `template name`, then it will be used
    for rendering the mail. Any additional text should be provided in the
    `text` parameter and it will be included in the main body of the mail.

    If the function is not provided with a `template name`, then it will use
    the string provided in the `text` parameter as the mail body.
    """
    if not template_name:
        message = text
    else:
        message = render_to_string(
            template_name, {
                'user': user,
                'text': text,
                'baseurl': settings.BASE_URL,
                'support': settings.CONTACT_EMAIL
            })

    send_mail(subject,
              message,
              sender, [user.email],
              connection=get_connection())
    logger.info("Sent plain email to user: %s", user.log_display)
Exemplo n.º 4
0
Arquivo: im.py Projeto: grnet/synnefo
def api_access_config(request, template_name='im/api_access_config.html',
                      content_type='text/plain', extra_context=None,
                      filename='.kamakirc'):

    if settings.KAMAKI_CONFIG_CLOUD_NAME:
        cloud_name = settings.KAMAKI_CONFIG_CLOUD_NAME
    else:
        cloud_name = branding_settings.SERVICE_NAME.replace(' ', '_').lower()

    url = get_public_endpoint(settings.astakos_services, 'identity')

    context = {
        'user': request.user,
        'services': Component.catalog(),
        'token_url': url,
        'cloud_name': cloud_name
    }

    extra_context = extra_context or {}
    context.update(extra_context)
    content = branding.render_to_string(template_name, context,
                                        RequestContext(request))
    response = HttpResponse(content_type=content_type)
    response.status_code = 200
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename
    response.content = content
    return response
Exemplo n.º 5
0
def _send_admin_notification(template_name,
                             context=None,
                             user=None,
                             msg="",
                             subject='alpha2 testing notification',):
    """
    Send notification email to settings.HELPDESK + settings.MANAGERS +
    settings.ADMINS.
    """
    if context is None:
        context = {}
    if not 'user' in context:
        context['user'] = user

    message = render_to_string(template_name, context)
    sender = settings.SERVER_EMAIL
    recipient_list = [e[1] for e in settings.HELPDESK +
                      settings.MANAGERS + settings.ADMINS]
    send_mail(subject, message, sender, recipient_list,
              connection=get_connection())
    if user:
        msg = 'Sent admin notification (%s) for user %s' % (msg,
                                                            user.log_display)
    else:
        msg = 'Sent admin notification (%s)' % msg

    logger.log(settings.LOGGING_LEVEL, msg)
Exemplo n.º 6
0
 def save(self,
          domain_override=None,
          email_template_name='registration/password_reset_email.html',
          use_https=False,
          token_generator=default_token_generator,
          request=None):
     """
     Generates a one-use only link for resetting password and sends to the user.
     """
     for user in self.users_cache:
         url = user.astakosuser.get_password_reset_url(token_generator)
         url = join_urls(settings.BASE_HOST, url)
         c = {
             'email': user.email,
             'url': url,
             'site_name': settings.SITENAME,
             'user': user,
             'baseurl': settings.BASE_URL,
             'support': settings.CONTACT_EMAIL
         }
         message = render_to_string(email_template_name, c)
         from_email = settings.SERVER_EMAIL
         send_mail(_(astakos_messages.PASSWORD_RESET_EMAIL_SUBJECT),
                   message,
                   from_email, [user.email],
                   connection=get_connection())
Exemplo n.º 7
0
def send_plain(user, sender=settings.SERVER_EMAIL,
               subject=_(astakos_messages.PLAIN_EMAIL_SUBJECT),
               template_name='im/plain_email.txt', text=None):
    """Send mail to user with fully customizable sender, subject and body.

    If the function is provided with a `template name`, then it will be used
    for rendering the mail. Any additional text should be provided in the
    `text` parameter and it will be included in the main body of the mail.

    If the function is not provided with a `template name`, then it will use
    the string provided in the `text` parameter as the mail body.
    """
    if not template_name:
        message = text
    else:
        message = render_to_string(template_name, {
                                   'user': user,
                                   'text': text,
                                   'baseurl': settings.BASE_URL,
                                   'site_name': settings.SITENAME,
                                   'support': settings.CONTACT_EMAIL})

    send_mail(subject, message, sender, [user.email],
              connection=get_connection())
    logger.info("Sent plain email to user: %s", user.log_display)
Exemplo n.º 8
0
 def save(self, domain_override=None,
          email_template_name='registration/password_reset_email.html',
          use_https=False, token_generator=default_token_generator,
          request=None, **kwargs):
     """
     Generates a one-use only link for resetting password
     and sends to the user.
     """
     for user in self.users_cache:
         url = user.astakosuser.get_password_reset_url(token_generator)
         url = join_urls(settings.BASE_HOST, url)
         c = {
             'email': user.email,
             'url': url,
             'site_name': settings.SITENAME,
             'user': user,
             'baseurl': settings.BASE_URL,
             'support': settings.CONTACT_EMAIL
         }
         message = render_to_string(email_template_name, c)
         from_email = settings.SERVER_EMAIL
         send_mail(_(astakos_messages.PASSWORD_RESET_EMAIL_SUBJECT),
                   message,
                   from_email,
                   [user.email],
                   connection=get_connection())
Exemplo n.º 9
0
def api_access_config(request,
                      template_name='im/api_access_config.html',
                      content_type='text/plain',
                      extra_context=None,
                      filename='.kamakirc'):

    if settings.KAMAKI_CONFIG_CLOUD_NAME:
        cloud_name = settings.KAMAKI_CONFIG_CLOUD_NAME
    else:
        cloud_name = branding_settings.SERVICE_NAME.replace(' ', '_').lower()

    url = get_public_endpoint(settings.astakos_services, 'identity')

    context = {
        'user': request.user,
        'services': Component.catalog(),
        'token_url': url,
        'cloud_name': cloud_name
    }

    extra_context = extra_context or {}
    context.update(extra_context)
    content = branding.render_to_string(template_name, context,
                                        RequestContext(request))
    response = HttpResponse(content_type=content_type)
    response.status_code = 200
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename
    response.content = content
    return response
Exemplo n.º 10
0
def send_change_email_to_old(email_change,
        email_template_name='registration/email_change_email_old_email.txt'):

    message = render_to_string(email_template_name, {'ec': email_change})
    from_email = settings.SERVER_EMAIL

    send_mail(_(astakos_messages.EMAIL_CHANGE_OLD_EMAIL_SUBJECT), message,
        from_email, [email_change.user.email], connection=get_connection())
Exemplo n.º 11
0
 def __init__(self, sender, recipients, subject,
              message=None, template=None, dictionary=None):
     if not message and not template:
         raise IOError('message and template cannot be both None.')
     dictionary = dictionary or {}
     self.sender = sender
     self.recipients = recipients
     self.subject = subject
     self.message = message or render_to_string(template, dictionary)
Exemplo n.º 12
0
 def render(self, *args, **kwargs):
     conf = settings.RECAPTCHA_OPTIONS
     recaptcha_conf = ('<script type="text/javascript">' "var RecaptchaOptions = %s" "</script>") % json.dumps(conf)
     custom_widget_html = render_to_string("im/captcha.html", {"conf": "Bob"})
     return mark_safe(
         recaptcha_conf
         + custom_widget_html
         + captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY, use_ssl=settings.RECAPTCHA_USE_SSL)
     )
Exemplo n.º 13
0
def confirm_link(context,
                 title,
                 prompt='',
                 url=None,
                 urlarg=None,
                 extracontent='',
                 confirm_prompt=None,
                 inline=True,
                 cls='',
                 template="im/table_rich_link_column.html"):

    urlargs = None
    if urlarg:
        if isinstance(urlarg, basestring) and "," in urlarg:
            args = urlarg.split(",")
            for index, arg in enumerate(args):
                if context.get(arg, None) is not None:
                    args[index] = context.get(arg)
            urlargs = args
        else:
            urlargs = (urlarg, )

    if CONFIRM_LINK_PROMPT_MAP.get(prompt, None):
        prompt = mark_safe(CONFIRM_LINK_PROMPT_MAP.get(prompt))

    if url:
        url = reverse(url, args=urlargs)
    else:
        url = None

    title = _(title)
    tpl_context = RequestContext(context.get('request'))
    tpl_context.update({
        'col': {
            'method': 'POST',
            'cancel_prompt': 'CANCEL',
            'confirm_prompt': confirm_prompt or title
        },
        'inline':
        inline,
        'url':
        url,
        'action':
        title,
        'cls':
        cls,
        'prompt':
        prompt,
        'extra_form_content':
        EXTRA_CONTENT_MAP.get(extracontent, ''),
        'confirm':
        True
    })

    content = render_to_string(template, tpl_context)
    return content
Exemplo n.º 14
0
 def __init__(
     self, sender, recipients, subject,
     message=None, template=None, dictionary=None):
     if not message and not template:
         raise IOError('message and template cannot be both None.')
     dictionary = dictionary or {}
     self.sender = sender
     self.recipients = recipients
     self.subject = subject
     self.message = message or render_to_string(template, dictionary)
Exemplo n.º 15
0
 def render(self, *args, **kwargs):
     conf = settings.RECAPTCHA_OPTIONS
     recaptcha_conf = ('<script type="text/javascript">'
                       'var RecaptchaOptions = %s'
                       '</script>') % json.dumps(conf)
     custom_widget_html = render_to_string("im/captcha.html",
                                           {'conf': 'Bob'})
     return mark_safe(
         recaptcha_conf + custom_widget_html +
         captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY,
                             use_ssl=settings.RECAPTCHA_USE_SSL))
Exemplo n.º 16
0
def send_change_email_to_old(
        email_change,
        email_template_name='registration/email_change_email_old_email.txt'):

    message = render_to_string(email_template_name, {'ec': email_change})
    from_email = settings.SERVER_EMAIL

    send_mail(_(astakos_messages.EMAIL_CHANGE_OLD_EMAIL_SUBJECT),
              message,
              from_email, [email_change.user.email],
              connection=get_connection())
Exemplo n.º 17
0
def send_feedback(msg, data, user, email_template_name='im/feedback_mail.txt'):
    subject = _(astakos_messages.FEEDBACK_EMAIL_SUBJECT)
    from_email = settings.SERVER_EMAIL
    recipient_list = [e[1] for e in settings.HELPDESK]
    content = render_to_string(email_template_name, {
        'message': msg,
        'data': data,
        'user': user})
    send_mail(subject, content, from_email, recipient_list,
              connection=get_connection())
    msg = 'Sent feedback from %s'
    logger.log(settings.LOGGING_LEVEL, msg, user.log_display)
Exemplo n.º 18
0
def send_change_email(
    ec, request, email_template_name='registration/email_change_email.txt'):
    url = ec.get_url()
    url = request.build_absolute_uri(url)
    c = {'url': url, 'site_name': settings.SITENAME, 'support': settings.CONTACT_EMAIL,
         'ec': ec}
    message = render_to_string(email_template_name, c)
    from_email = settings.SERVER_EMAIL
    send_mail(_(astakos_messages.EMAIL_CHANGE_EMAIL_SUBJECT), message,
              from_email,
              [ec.new_email_address], connection=get_connection())
    msg = 'Sent change email for %s' % ec.user.log_display
    logger.log(settings.LOGGING_LEVEL, msg)
Exemplo n.º 19
0
def send_change_email_to_new(
    ec, email_template_name=('registration/email_change_email_new_email.txt')):
    url = ec.get_url()
    url = urlparse.urljoin(settings.BASE_URL, url)
    c = {'url': url, 'support': settings.CONTACT_EMAIL, 'ec': ec}
    message = render_to_string(email_template_name, c)
    from_email = settings.SERVER_EMAIL
    send_mail(_(astakos_messages.EMAIL_CHANGE_NEW_EMAIL_SUBJECT),
              message,
              from_email, [ec.new_email_address],
              connection=get_connection())
    msg = 'Sent change email for %s'
    logger.log(settings.LOGGING_LEVEL, msg, ec.user.log_display)
Exemplo n.º 20
0
def confirm_link(context, title, prompt='', url=None, urlarg=None,
                 extracontent='',
                 confirm_prompt=None,
                 inline=True,
                 cls='',
                 template="im/table_rich_link_column.html"):

    urlargs = None
    if urlarg:
        if isinstance(urlarg, basestring) and "," in urlarg:
            args = urlarg.split(",")
            for index, arg in enumerate(args):
                property = None
                if "." in arg:
                    arg, property = arg.split(".")
                if context.get(arg, None) is not None:
                    val = context.get(arg)
                    if property:
                        val = getattr(val, property)
                    args[index] = val
            urlargs = args
        else:
            urlargs = (urlarg,)

    if CONFIRM_LINK_PROMPT_MAP.get(prompt, None):
        prompt = mark_safe(CONFIRM_LINK_PROMPT_MAP.get(prompt))

    if url:
        url = reverse(url, args=urlargs)
    else:
        url = None

    title = _(title)
    tpl_context = RequestContext(context.get('request'))
    tpl_context.update({
        'col': {
            'method': 'POST',
            'cancel_prompt': 'CANCEL',
            'confirm_prompt': confirm_prompt or title
        },
        'inline': inline,
        'url': url,
        'action': title,
        'cls': cls,
        'prompt': prompt,
        'extra_form_content': EXTRA_CONTENT_MAP.get(extracontent, ''),
        'confirm': True
    })

    content = render_to_string(template, tpl_context)
    return content
Exemplo n.º 21
0
def send_change_email_to_new(ec, email_template_name=(
                      'registration/email_change_email_new_email.txt')):
    url = ec.get_url()
    url = urlparse.urljoin(settings.BASE_URL, url)
    c = {'url': url,
         'support': settings.CONTACT_EMAIL,
         'ec': ec}
    message = render_to_string(email_template_name, c)
    from_email = settings.SERVER_EMAIL
    send_mail(_(astakos_messages.EMAIL_CHANGE_NEW_EMAIL_SUBJECT), message,
              from_email,
              [ec.new_email_address], connection=get_connection())
    msg = 'Sent change email for %s'
    logger.log(settings.LOGGING_LEVEL, msg, ec.user.log_display)
Exemplo n.º 22
0
    def test_send_plain_email(self):
        """Test if send_plain_email function works as intended."""
        def verify_sent_email(email_dict, mail):
            """Helper function to verify that an email was sent properly."""
            sender = email_dict.get('sender', astakos_settings.SERVER_EMAIL)
            subject = email_dict.get('subject',
                                     _(astakos_messages.PLAIN_EMAIL_SUBJECT))
            self.assertEqual(sender, mail.from_email)
            self.assertEqual(subject, mail.subject)
            self.assertEqual(email_dict['text'], mail.body)

        # Common variables
        template_name = 'im/plain_email.txt'
        text = u"Δεσποινίς, που είναι η μπάλα; Ümlaut.)?"
        expected_text = render_to_string(
            template_name, {
                'user': self.user1,
                'text': text,
                'baseurl': astakos_settings.BASE_URL,
                'support': astakos_settings.CONTACT_EMAIL
            })

        # Test 1 - Check if a simple test mail is sent properly.
        send_plain(self.user1, text=text)
        self.assertEqual(len(mail.outbox), 1)
        body = mail.outbox[0].body
        self.assertEqual(expected_text, body)

        # Test 2 - Check if the email template can get overriden.
        email_dict = {
            'template_name': None,
            'text': expected_text,
        }

        send_plain(self.user1, **email_dict)
        self.assertEqual(len(mail.outbox), 2)
        verify_sent_email(email_dict, mail.outbox[1])

        # Test 3 - Check if the email subject can get overriden.
        email_dict.update({'subject': u"Το θέμα μας είναι: Ümlaut."})
        send_plain(self.user1, **email_dict)
        self.assertEqual(len(mail.outbox), 3)
        verify_sent_email(email_dict, mail.outbox[2])

        # Test 4 - Check if the email sender can get overriden.
        email_dict.update({'sender': "*****@*****.**"})
        send_plain(self.user1, **email_dict)
        self.assertEqual(len(mail.outbox), 4)
        verify_sent_email(email_dict, mail.outbox[3])
Exemplo n.º 23
0
def confirm_link(
    context,
    title,
    prompt="",
    url=None,
    urlarg=None,
    extracontent="",
    confirm_prompt=None,
    inline=True,
    cls="",
    template="im/table_rich_link_column.html",
):

    urlargs = None
    if urlarg:
        if isinstance(urlarg, basestring) and "," in urlarg:
            args = urlarg.split(",")
            for index, arg in enumerate(args):
                if context.get(arg, None) is not None:
                    args[index] = context.get(arg)
            urlargs = args
        else:
            urlargs = (urlarg,)

    if CONFIRM_LINK_PROMPT_MAP.get(prompt, None):
        prompt = mark_safe(CONFIRM_LINK_PROMPT_MAP.get(prompt))

    if url:
        url = reverse(url, args=urlargs)
    else:
        url = None

    title = _(title)
    tpl_context = RequestContext(context.get("request"))
    tpl_context.update(
        {
            "col": {"method": "POST", "cancel_prompt": "CANCEL", "confirm_prompt": confirm_prompt or title},
            "inline": inline,
            "url": url,
            "action": title,
            "cls": cls,
            "prompt": prompt,
            "extra_form_content": EXTRA_CONTENT_MAP.get(extracontent, ""),
            "confirm": True,
        }
    )

    content = render_to_string(template, tpl_context)
    return content
Exemplo n.º 24
0
    def test_send_plain_email(self):
        """Test if send_plain_email function works as intended."""
        def verify_sent_email(email_dict, mail):
            """Helper function to verify that an email was sent properly."""
            sender = email_dict.get('sender', astakos_settings.SERVER_EMAIL)
            subject = email_dict.get('subject',
                                     _(astakos_messages.PLAIN_EMAIL_SUBJECT))
            self.assertEqual(sender, mail.from_email)
            self.assertEqual(subject, mail.subject)
            self.assertEqual(email_dict['text'], mail.body)

        # Common variables
        template_name = 'im/plain_email.txt'
        text = u"Δεσποινίς, που είναι η μπάλα; Ümlaut.)?"
        expected_text = render_to_string(template_name, {
            'user': self.user1,
            'text': text,
            'baseurl': astakos_settings.BASE_URL,
            'site_name': astakos_settings.SITENAME,
            'support': astakos_settings.CONTACT_EMAIL})

        # Test 1 - Check if a simple test mail is sent properly.
        send_plain(self.user1, text=text)
        self.assertEqual(len(mail.outbox), 1)
        body = mail.outbox[0].body
        self.assertEqual(expected_text, body)

        # Test 2 - Check if the email template can get overriden.
        email_dict = {
            'template_name': None,
            'text': expected_text,
        }

        send_plain(self.user1, **email_dict)
        self.assertEqual(len(mail.outbox), 2)
        verify_sent_email(email_dict, mail.outbox[1])

        # Test 3 - Check if the email subject can get overriden.
        email_dict.update({'subject': u"Το θέμα μας είναι: Ümlaut."})
        send_plain(self.user1, **email_dict)
        self.assertEqual(len(mail.outbox), 3)
        verify_sent_email(email_dict, mail.outbox[2])

        # Test 4 - Check if the email sender can get overriden.
        email_dict.update({'sender': "*****@*****.**"})
        send_plain(self.user1, **email_dict)
        self.assertEqual(len(mail.outbox), 4)
        verify_sent_email(email_dict, mail.outbox[3])
Exemplo n.º 25
0
def send_feedback(msg, data, user, email_template_name='im/feedback_mail.txt'):
    subject = _(astakos_messages.FEEDBACK_EMAIL_SUBJECT)
    from_email = settings.SERVER_EMAIL
    recipient_list = [e[1] for e in settings.HELPDESK]
    content = render_to_string(email_template_name, {
        'message': msg,
        'data': data,
        'user': user
    })
    send_mail(subject,
              content,
              from_email,
              recipient_list,
              connection=get_connection())
    msg = 'Sent feedback from %s'
    logger.log(settings.LOGGING_LEVEL, msg, user.log_display)
Exemplo n.º 26
0
def send_account_pending_moderation_notification(
        user,
        template_name='im/account_pending_moderation_notification.txt'):
    """
    Notify 'ACCOUNT_PENDING_MODERATION_RECIPIENTS' that a new user has verified
    his email address and moderation step is required to activate his account.
    """
    subject = (_(astakos_messages.ACCOUNT_CREATION_SUBJECT) %
               {'user': user.email})
    message = render_to_string(template_name, {'user': user})
    sender = settings.SERVER_EMAIL
    recipient_list = [e[1] for e in
                      settings.ACCOUNT_PENDING_MODERATION_RECIPIENTS]
    send_mail(subject, message, sender, recipient_list,
              connection=get_connection())
    msg = 'Sent admin notification (account creation) for user %s'
    logger.log(settings.LOGGING_LEVEL, msg, user.log_display)
Exemplo n.º 27
0
def send_verification(user, template_name='im/activation_email.txt'):
    """
    Send email to user to verify his/her email and activate his/her account.
    """
    index_url = reverse('index', urlconf="synnefo.webproject.urls")
    url = join_urls(settings.BASE_HOST,
                    user.get_activation_url(nxt=index_url))
    message = render_to_string(template_name, {
                               'user': user,
                               'url': url,
                               'baseurl': settings.BASE_URL,
                               'support': settings.CONTACT_EMAIL})
    sender = settings.SERVER_EMAIL
    send_mail(_(astakos_messages.VERIFICATION_EMAIL_SUBJECT), message, sender,
              [user.email],
              connection=get_connection())
    logger.info("Sent user verification email: %s", user.log_display)
Exemplo n.º 28
0
def send_account_activated_notification(
        user, template_name='im/account_activated_notification.txt'):
    """
    Send email to ACCOUNT_ACTIVATED_RECIPIENTS list to notify that a new
    account has been accepted and activated.
    """
    message = render_to_string(template_name, {'user': user})
    sender = settings.SERVER_EMAIL
    recipient_list = [e[1] for e in settings.ACCOUNT_ACTIVATED_RECIPIENTS]
    send_mail(_(astakos_messages.HELPDESK_NOTIFICATION_EMAIL_SUBJECT) %
              {'user': user.email},
              message,
              sender,
              recipient_list,
              connection=get_connection())
    msg = 'Sent helpdesk admin notification for %s'
    logger.log(settings.LOGGING_LEVEL, msg, user.email)
Exemplo n.º 29
0
def send_greeting(user, email_template_name='im/welcome_email.txt'):
    """
    Send welcome email to an accepted/activated user.

    Raises SMTPException, socket.error
    """
    subject = _(astakos_messages.GREETING_EMAIL_SUBJECT)
    index_url = reverse('index', urlconf="synnefo.webproject.urls")
    message = render_to_string(email_template_name, {
                               'user': user,
                               'url': join_urls(settings.BASE_HOST, index_url),
                               'baseurl': settings.BASE_URL,
                               'support': settings.CONTACT_EMAIL})
    sender = settings.SERVER_EMAIL
    send_mail(subject, message, sender, [user.email],
              connection=get_connection())
    msg = 'Sent greeting %s'
    logger.log(settings.LOGGING_LEVEL, msg, user.log_display)
Exemplo n.º 30
0
def send_account_activated_notification(
        user,
        template_name='im/account_activated_notification.txt'):
    """
    Send email to ACCOUNT_ACTIVATED_RECIPIENTS list to notify that a new
    account has been accepted and activated.
    """
    message = render_to_string(
        template_name,
        {'user': user}
    )
    sender = settings.SERVER_EMAIL
    recipient_list = [e[1] for e in
                      settings.ACCOUNT_ACTIVATED_RECIPIENTS]
    send_mail(_(astakos_messages.HELPDESK_NOTIFICATION_EMAIL_SUBJECT) %
              {'user': user.email},
              message, sender, recipient_list, connection=get_connection())
    msg = 'Sent helpdesk admin notification for %s'
    logger.log(settings.LOGGING_LEVEL, msg, user.email)
Exemplo n.º 31
0
def send_verification(user, template_name='im/activation_email.txt'):
    """
    Send email to user to verify his/her email and activate his/her account.
    """
    index_url = reverse('index', urlconf="synnefo.webproject.urls")
    url = join_urls(settings.BASE_HOST, user.get_activation_url(nxt=index_url))
    message = render_to_string(
        template_name, {
            'user': user,
            'url': url,
            'baseurl': settings.BASE_URL,
            'support': settings.CONTACT_EMAIL
        })
    sender = settings.SERVER_EMAIL
    send_mail(_(astakos_messages.VERIFICATION_EMAIL_SUBJECT),
              message,
              sender, [user.email],
              connection=get_connection())
    logger.info("Sent user verification email: %s", user.log_display)
Exemplo n.º 32
0
def send_change_email(
        ec,
        request,
        email_template_name='registration/email_change_email.txt'):
    url = ec.get_url()
    url = request.build_absolute_uri(url)
    c = {
        'url': url,
        'site_name': settings.SITENAME,
        'support': settings.CONTACT_EMAIL,
        'ec': ec
    }
    message = render_to_string(email_template_name, c)
    from_email = settings.SERVER_EMAIL
    send_mail(_(astakos_messages.EMAIL_CHANGE_EMAIL_SUBJECT),
              message,
              from_email, [ec.new_email_address],
              connection=get_connection())
    msg = 'Sent change email for %s'
    logger.log(settings.LOGGING_LEVEL, msg, ec.user.log_display)
Exemplo n.º 33
0
def send_account_pending_moderation_notification(
        user, template_name='im/account_pending_moderation_notification.txt'):
    """
    Notify 'ACCOUNT_PENDING_MODERATION_RECIPIENTS' that a new user has verified
    his email address and moderation step is required to activate his account.
    """
    subject = (_(astakos_messages.ACCOUNT_CREATION_SUBJECT) % {
        'user': user.email
    })
    message = render_to_string(template_name, {'user': user})
    sender = settings.SERVER_EMAIL
    recipient_list = [
        e[1] for e in settings.ACCOUNT_PENDING_MODERATION_RECIPIENTS
    ]
    send_mail(subject,
              message,
              sender,
              recipient_list,
              connection=get_connection())
    msg = 'Sent admin notification (account creation) for user %s'
    logger.log(settings.LOGGING_LEVEL, msg, user.log_display)
Exemplo n.º 34
0
def send_invitation(invitation, template_name='im/invitation.txt'):
    """
    Send invitation email.
    """
    subject = _(astakos_messages.INVITATION_EMAIL_SUBJECT)
    index_url = reverse('index', urlconf="synnefo.webproject.urls")
    url = '%s?code=%d' % (join_urls(settings.BASE_HOST, index_url,
                                    invitation.code))
    message = render_to_string(template_name, {
                               'invitation': invitation,
                               'url': url,
                               'baseurl': settings.BASE_URL,
                               'support': settings.CONTACT_EMAIL})
    sender = settings.SERVER_EMAIL
    send_mail(subject, message, sender, [invitation.username],
              connection=get_connection())
    msg = 'Sent invitation %s'
    logger.log(settings.LOGGING_LEVEL, msg, invitation)
    inviter_invitations = invitation.inviter.invitations
    invitation.inviter.invitations = max(0, inviter_invitations - 1)
    invitation.inviter.save()
Exemplo n.º 35
0
def send_greeting(user, email_template_name='im/welcome_email.txt'):
    """
    Send welcome email to an accepted/activated user.

    Raises SMTPException, socket.error
    """
    subject = _(astakos_messages.GREETING_EMAIL_SUBJECT)
    index_url = reverse('index', urlconf="synnefo.webproject.urls")
    message = render_to_string(
        email_template_name, {
            'user': user,
            'url': join_urls(settings.BASE_HOST, index_url),
            'baseurl': settings.BASE_URL,
            'support': settings.CONTACT_EMAIL
        })
    sender = settings.SERVER_EMAIL
    send_mail(subject,
              message,
              sender, [user.email],
              connection=get_connection())
    msg = 'Sent greeting %s'
    logger.log(settings.LOGGING_LEVEL, msg, user.log_display)
Exemplo n.º 36
0
                      request.user_uniq, request.path)
        return func(request, *args, **kwargs)

    return wrapper


# View functions ###

default_dict = {
    'ADMIN_MEDIA_URL': admin_settings.ADMIN_MEDIA_URL,
    'UI_MEDIA_URL': UI_MEDIA_URL,
    'mail': {
        'sender': astakos_settings.SERVER_EMAIL,
        'subject': sample_subject,
        'body': render_to_string('im/plain_email.txt', {
            'baseurl': astakos_settings.BASE_URL,
            'support': astakos_settings.CONTACT_EMAIL}).replace('\n\n\n', '\n'),
        'legend': {
            'Full name': "{{ full_name }}",
            'First name': "{{ first_name }}",
            'Last name': "{{ last_name }}",
            'Email': "{{ email }}",
        }
    },
    'views': admin_settings.ADMIN_VIEWS,
    'ADMIN_OR_SIGN': admin_settings.ADMIN_OR_SIGN,
}


@admin_user_required
def logout(request):
Exemplo n.º 37
0
def machines_connect(request):
    ip_address = request.GET.get("ip_address", "")
    hostname = request.GET.get("hostname", "")
    operating_system = metadata_os = request.GET.get("os", "")
    server_id = request.GET.get("srv", 0)
    host_os = request.GET.get("host_os", "Linux").lower()
    username = request.GET.get("username", None)
    domain = request.GET.get("domain", DOMAIN_TPL % int(server_id))
    ports = json.loads(request.GET.get("ports", "{}"))

    # guess host os
    if host_os != "windows":
        host_os = "linux"

    # guess username
    if not username:
        username = "******"

        if metadata_os.lower() in ["ubuntu", "kubuntu", "fedora"]:
            username = "******"

        if metadata_os.lower() == "windows":
            username = "******"

    ssh_forward = ports.get("22", None)
    rdp_forward = ports.get("3389", None)

    # operating system provides ssh access
    ssh = False
    if operating_system != "windows":
        operating_system = "linux"
        ssh = True

    # rdp param is set, the user requested rdp file
    # check if we are on windows
    if operating_system == "windows" and request.GET.get("rdp", False):
        port = "3389"
        if rdp_forward:
            hostname = rdp_forward.get("host", hostname)
            ip_address = rdp_forward.get("host", ip_address)
            port = str(rdp_forward.get("port", "3389"))

        extra_rdp_content = ""
        # UI sent domain info (from vm metadata) use this
        # otherwise use our default snf-<vm_id> domain
        EXTRA_RDP_CONTENT = getattr(settings, "UI_EXTRA_RDP_CONTENT", "")
        if callable(EXTRA_RDP_CONTENT):
            extra_rdp_content = EXTRA_RDP_CONTENT(server_id, ip_address, hostname, username)
        else:
            if EXTRA_RDP_CONTENT:
                extra_rdp_content = EXTRA_RDP_CONTENT % {
                    "server_id": server_id,
                    "ip_address": ip_address,
                    "hostname": hostname,
                    "user": username,
                    "port": port,
                }

        rdp_context = {
            "username": username,
            "domain": domain,
            "ip_address": ip_address,
            "hostname": hostname,
            "port": request.GET.get("port", port),
            "extra_content": extra_rdp_content,
        }

        rdp_file_data = render_to_string("synnefo-windows.rdp", rdp_context)
        response = HttpResponse(rdp_file_data, mimetype="application/x-rdp")

        # proper filename, use server id and ip address
        filename = "%d-%s.rdp" % (int(server_id), hostname)
        response["Content-Disposition"] = "attachment; filename=%s" % filename
    else:
        message_key = "ssh_message"
        ip_address = ip_address
        hostname = hostname
        port = ""
        if ssh_forward:
            message_key = "ssh_message_port"
            hostname = ssh_forward.get("host", hostname)
            ip_address = ssh_forward.get("host", ip_address)
            port = str(ssh_forward.get("port", "22"))

        ssh_message = CONNECT_PROMPT_MESSAGES["linux"].get(message_key)
        if host_os == "windows":
            ssh_message = CONNECT_PROMPT_MESSAGES["windows"].get(message_key)
        if callable(ssh_message):
            link_title = ssh_message(server_id, ip_address, hostname, username)
        else:
            link_title = ssh_message % {
                "server_id": server_id,
                "ip_address": ip_address,
                "hostname": hostname,
                "user": username,
                "port": port,
            }
        if operating_system != "windows":
            link_url = None

        else:
            link_title = _("Remote desktop to %s") % ip_address
            if rdp_forward:
                hostname = rdp_forward.get("host", hostname)
                ip_address = rdp_forward.get("host", ip_address)
                port = str(rdp_forward.get("port", "3389"))
                link_title = _("Remote desktop to %s (port %s)") % (ip_address, port)
            link_url = "%s?ip_address=%s&os=%s&rdp=1&srv=%d&username=%s&domain=%s" "&hostname=%s&port=%s" % (
                reverse("ui_machines_connect"),
                ip_address,
                operating_system,
                int(server_id),
                username,
                domain,
                hostname,
                port,
            )

        # try to find a specific message
        try:
            connect_message = CONNECT_PROMPT_MESSAGES[host_os][operating_system][0]
            subinfo = CONNECT_PROMPT_MESSAGES[host_os][operating_system][1]
        except KeyError:
            connect_message = _("You are trying to connect from a %s " "machine to a %s machine") % (
                host_os,
                operating_system,
            )
            subinfo = ""

        response_object = {
            "ip": ip_address,
            "os": operating_system,
            "ssh": ssh,
            "info": unicode(connect_message),
            "subinfo": unicode(subinfo),
            "link": {"title": unicode(link_title), "url": link_url},
        }
        response = HttpResponse(json.dumps(response_object), mimetype="application/json")  # no windows, no rdp

    return response
Exemplo n.º 38
0
def machines_connect(request):
    ip_address = request.GET.get('ip_address', '')
    hostname = request.GET.get('hostname', '')
    operating_system = metadata_os = request.GET.get('os', '')
    server_id = request.GET.get('srv', 0)
    host_os = request.GET.get('host_os', 'Linux').lower()
    username = request.GET.get('username', None)
    domain = request.GET.get("domain", DOMAIN_TPL % int(server_id))
    ports = json.loads(request.GET.get('ports', '{}'))

    # guess host os
    if host_os != "windows":
        host_os = 'linux'

    # guess username
    if not username:
        username = "******"

        if metadata_os.lower() in ['ubuntu', 'kubuntu', 'fedora']:
            username = "******"

        if metadata_os.lower() == "windows":
            username = "******"

    ssh_forward = ports.get("22", None)
    rdp_forward = ports.get("3389", None)

    # operating system provides ssh access
    ssh = False
    if operating_system != "windows":
        operating_system = "linux"
        ssh = True

    # rdp param is set, the user requested rdp file
    # check if we are on windows
    if operating_system == 'windows' and request.GET.get("rdp", False):
        port = '3389'
        if rdp_forward:
            hostname = rdp_forward.get('host', hostname)
            ip_address = rdp_forward.get('host', ip_address)
            port = str(rdp_forward.get('port', '3389'))

        extra_rdp_content = ''
        # UI sent domain info (from vm metadata) use this
        # otherwise use our default snf-<vm_id> domain
        EXTRA_RDP_CONTENT = getattr(settings, 'UI_EXTRA_RDP_CONTENT', '')
        if callable(EXTRA_RDP_CONTENT):
            extra_rdp_content = EXTRA_RDP_CONTENT(server_id, ip_address,
                                                  hostname, username)
        else:
            if EXTRA_RDP_CONTENT:
                extra_rdp_content = EXTRA_RDP_CONTENT % \
                    {
                        'server_id': server_id,
                        'ip_address': ip_address,
                        'hostname': hostname,
                        'user': username,
                        'port': port
                    }

        rdp_context = {
            'username': username,
            'domain': domain,
            'ip_address': ip_address,
            'hostname': hostname,
            'port': request.GET.get('port', port),
            'extra_content': extra_rdp_content
        }

        rdp_file_data = render_to_string("synnefo-windows.rdp", rdp_context)
        response = HttpResponse(rdp_file_data,
                                content_type='application/x-rdp')

        # proper filename, use server id and ip address
        filename = "%d-%s.rdp" % (int(server_id), hostname)
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
    else:
        message_key = "ssh_message"
        ip_address = ip_address
        hostname = hostname
        port = ''
        if ssh_forward:
            message_key = 'ssh_message_port'
            hostname = ssh_forward.get('host', hostname)
            ip_address = ssh_forward.get('host', ip_address)
            port = str(ssh_forward.get('port', '22'))

        ssh_message = CONNECT_PROMPT_MESSAGES['linux'].get(message_key)
        if host_os == 'windows':
            ssh_message = CONNECT_PROMPT_MESSAGES['windows'].get(message_key)
        if callable(ssh_message):
            link_title = ssh_message(server_id, ip_address, hostname, username)
        else:
            link_title = ssh_message % {
                'server_id': server_id,
                'ip_address': ip_address,
                'hostname': hostname,
                'user': username,
                'port': port
            }
        if (operating_system != "windows"):
            link_url = None

        else:
            link_title = _("Remote desktop to %s") % ip_address
            if rdp_forward:
                hostname = rdp_forward.get('host', hostname)
                ip_address = rdp_forward.get('host', ip_address)
                port = str(rdp_forward.get('port', '3389'))
                link_title = _("Remote desktop to %s (port %s)") % (ip_address,
                                                                    port)
            link_url = \
                "%s?ip_address=%s&os=%s&rdp=1&srv=%d&username=%s&domain=%s" \
                "&hostname=%s&port=%s" % (
                    reverse("ui_machines_connect"), ip_address,
                    operating_system, int(server_id), username,
                    domain, hostname, port)

        # try to find a specific message
        try:
            connect_message = \
                CONNECT_PROMPT_MESSAGES[host_os][operating_system][0]
            subinfo = CONNECT_PROMPT_MESSAGES[host_os][operating_system][1]
        except KeyError:
            connect_message = \
                _("You are trying to connect from a %s "
                  "machine to a %s machine") % (host_os, operating_system)
            subinfo = ""

        response_object = {
            'ip': ip_address,
            'os': operating_system,
            'ssh': ssh,
            'info': unicode(connect_message),
            'subinfo': unicode(subinfo),
            'link': {'title': unicode(link_title), 'url': link_url}
        }
        response = \
            HttpResponse(json.dumps(response_object),
                         content_type='application/json')  # no windows, no rdp


    return response
Exemplo n.º 39
0

# View functions ###

default_dict = {
    'ADMIN_MEDIA_URL': admin_settings.ADMIN_MEDIA_URL,
    'UI_MEDIA_URL': UI_MEDIA_URL,
    'mail': {
        'sender':
        astakos_settings.SERVER_EMAIL,
        'subject':
        sample_subject,
        'body':
        render_to_string(
            'im/plain_email.txt', {
                'baseurl': astakos_settings.BASE_URL,
                'support': astakos_settings.CONTACT_EMAIL
            }).replace('\n\n\n', '\n'),
        'legend': {
            'Full name': "{{ full_name }}",
            'First name': "{{ first_name }}",
            'Last name': "{{ last_name }}",
            'Email': "{{ email }}",
        }
    },
    'views': admin_settings.ADMIN_VIEWS,
    'ADMIN_OR_SIGN': admin_settings.ADMIN_OR_SIGN,
}


@admin_user_required