Пример #1
0
def send(email, username, hostname, password):
    print(email)
    message = dedent("""
        Hi {username},

        Your student virtual machine for the Linux SysAdmin Decal is ready. You will need this machine to complete some of your labs. Please note the following login information:

        Host: {username}.decal.xcf.sh
        Username: {username}
        Temporary Password: {password}

        You can login to this machine with `ssh {username}@{hostname}`, after which you’ll be prompted to enter your password. You should see a prompt to change your temporary password after your first login. We recommend selecting a strong password to secure your VM appropriately. 
        
        These VMs were graciously provided for the DeCal by DigitalOcean.

        Let us know if you have any questions or issues,

        Linux SysAdmin DeCal Staff
        """).strip()

    send_mail(
        email,
        '[Linux SysAdmin DeCal] Your Student Virtual Machine Information',
        message.format(username=username, hostname=hostname,
                       password=password),
        cc='*****@*****.**',
        sender='*****@*****.**',
    )
Пример #2
0
def send_created_mail(request):
    body = """Greetings from the Grotto of Hearst Gym,

Your OCF account has been created and is ready for use! Welcome aboard!

Your account name is: {request.user_name}

As a brand-new OCF member, you're welcome to use any and all of our services.
Some key highlights:

    - Access to our swanky computer lab (6A Hearst Gym)
    - 250 pages of free printing per semester
    - Web hosting: https://www.ocf.berkeley.edu/~{request.user_name}/

You can find out the cool things you can do on our wiki:
https://ocf.io/wiki

Keep in mind not to share your shiny new password with anyone, including OCF
staffers. You can always reset it online:

https://ocf.io/password

Finally, we'd like to remind you that the OCF is run completely by student
volunteers (people like you)! If you value the services we provide, check us
out and consider getting involved!

https://hello.ocf.berkeley.edu/

If you have any other questions, feel free to reply to this message!

{signature}""".format(request=request, signature=constants.MAIL_SIGNATURE)

    send_mail(request.email, '[OCF] Your account has been created!', body)
Пример #3
0
def send_created_mail(request):
    body = """Greetings from the Grotto of Hearst Gym,

Your OCF account has been created and is ready for use! Welcome aboard!

Your account name is: {request.user_name}

As a brand-new OCF member, you're welcome to use any and all of our services.
Some key highlights:

    - Access to our swanky computer lab (6A Hearst Gym)
    - 250 pages of free printing per semester
    - Web hosting: https://www.ocf.berkeley.edu/~{request.user_name}/

You can find out the cool things you can do on our wiki:
https://ocf.io/wiki

Keep in mind not to share your shiny new password with anyone, including OCF
staffers. You can always reset it online:

https://ocf.io/password

Finally, we'd like to remind you that the OCF is run completely by student
volunteers (people like you)! If you value the services we provide, check us
out and consider getting involved!

https://hello.ocf.berkeley.edu/

If you have any other questions, feel free to reply to this message!

{signature}""".format(request=request,
                      signature=constants.MAIL_SIGNATURE)

    send_mail(request.email, '[OCF] Your account has been created!', body)
Пример #4
0
def send_created_mail(request):
    body = jinja_mail_env.get_template(
        'account/mail_templates/account-created.jinja', ).render(
            request=request,
            semesterly_quota=SEMESTERLY_QUOTA,
        )
    send_mail(request.email, '[OCF] Your account has been created!', body)
Пример #5
0
def send_created_mail(request):
    body = jinja_mail_env.get_template(
        'account/mail_templates/account-created.jinja',
    ).render(
        request=request,
        semesterly_quota=SEMESTERLY_QUOTA,
    )
    send_mail(request.email, '[OCF] Your account has been created!', body)
Пример #6
0
def send_request_to_officers(request):
    body = JINJA_MAIL_ENV.get_template(
        'lab_reservations/mail_templates/officer_notification.jinja',
    ).render(request=request)
    send_mail(
        '*****@*****.**',
        'New Lab Reservation Request: {}'.format(request.group),
        body,
        sender=request.contact_email,
    )
Пример #7
0
def create_user():
    username = env.host.split('.')[0]

    # Generate a random temporary password to be emailed out to each student
    rand = random.SystemRandom()
    password = ''.join(
        rand.choice(string.ascii_letters + string.digits)
        for _ in range(PW_LENGTH))

    # Create a new user account in the sudo group so they have root access
    run('useradd -m -g sudo -s /bin/bash {}'.format(username))

    # Set their password to the temporary password previously generated
    run("echo '{}:{}' | chpasswd -e".format(username, crypt.crypt(password)))

    # Set password expiration for the user so that they have to change their
    # password immediately upon login
    run('chage -d 0 {}'.format(username))

    # make sure password authentication is on so students can log in
    # it appears it gets turned off now if you supply a root ssh key
    run("sed -i '/^PasswordAuthentication no/d' /etc/ssh/sshd_config && systemctl reload ssh"
        )

    # Send an email out to the user with their new password
    message = dedent("""
        Hello {username},

        We have created a virtual machine for you for the Linux SysAdmin DeCal!

        You should be able to connect to it at {hostname} by running
        'ssh {username}@{hostname}' and entering your temporary
        password {password}.

        You should see a prompt to change your temporary password to something
        more secure after your first login.

        Let us know if you have any questions or issues,

        DeCal Staff
    """).strip()

    send_mail(
        '{}@ocf.berkeley.edu'.format(username),
        '[Linux SysAdmin DeCal] Virtual Machine Information',
        message.format(
            username=username,
            hostname=env.host,
            password=password,
        ),
        cc='*****@*****.**',
        sender='*****@*****.**',
    )
Пример #8
0
    def test_send_mail(self, mock_popen):
        send_mail(
            '*****@*****.**',
            'hello world',
            'this is a body',
            sender='ocflib <*****@*****.**>',
        )

        msg = self.get_message(mock_popen)
        assert msg['Subject'] == 'hello world'
        assert msg['From'] == 'ocflib <*****@*****.**>'
        assert msg['To'] == '*****@*****.**'
        assert msg.get_payload() == 'this is a body'
def main():
    for lab, pairs in pending_labs().items():
        facilitators = db.facilitator_labs(lab)
        emails = [email_for_user(f) for f in facilitators]

        submissions_txt = '\n'.join('{} {}'.format(*p) for p in pairs)
        body = template.format(
            names=', '.join(facilitators),
            lab=lab,
            submissions=submissions_txt,
        )

        send_mail(
            to=', '.join(emails),
            subject='Decal Checkoff Reminder for lab {}'.format(lab),
            body=body,
            sender='*****@*****.**',
        )
Пример #10
0
def send_rejected_mail(request, reason):
    body = """Greetings from the Grotto of Hearst Gym,

Your OCF account, {request.user_name} has been rejected for the following reason:

{reason}

For information about account eligibility, see:

https://wiki.ocf.berkeley.edu/membership/

If you have any other questions or problems, feel free to contact us by
replying to this message.

{signature}""".format(request=request,
                      reason=reason,
                      signature=constants.MAIL_SIGNATURE)

    send_mail(request.email, '[OCF] Your account request has been rejected',
              body)
Пример #11
0
def send_rejected_mail(request, reason):
    body = """Greetings from the Grotto of Hearst Gym,

Your OCF account, {request.user_name} has been rejected for the following reason:

{reason}

For information about account eligibility, see:

https://wiki.ocf.berkeley.edu/membership/

If you have any other questions or problems, feel free to contact us by
replying to this message.

{signature}""".format(request=request,
                      reason=reason,
                      signature=constants.MAIL_SIGNATURE)

    send_mail(
        request.email, '[OCF] Your account request has been rejected', body)
Пример #12
0
 def test_send_mail_errors(self, sender, recipient, mock_popen):
     with pytest.raises(ValueError):
         send_mail(sender, 'subject', 'body', sender=recipient)
     assert not mock_popen.called
Пример #13
0
def send_rejected_mail(request, reason):
    body = jinja_mail_env.get_template(
        'account/mail_templates/account-rejected.jinja', ).render(
            request=request, reason=reason)
    send_mail(request.email, '[OCF] Your account request has been rejected',
              body)
Пример #14
0
def send_rejected_mail(request, reason):
    body = jinja_mail_env.get_template(
        'account/mail_templates/account-rejected.jinja',
    ).render(request=request, reason=reason)
    send_mail(request.email, '[OCF] Your account request has been rejected', body)
Пример #15
0
def send_request_confirmation(request):
    body = JINJA_MAIL_ENV.get_template(
        'lab_reservations/mail_templates/user_notification.jinja',
    ).render(request=request)
    send_mail(request.contact_email, '[OCF] Your reservation request has been submitted!', body)
Пример #16
0
def request_vhost(request):
    user = logged_in_user(request)
    attrs = user_attrs(user)
    error = None

    if has_vhost(user):
        return render(
            request,
            'account/vhost/already_have_vhost.html',
            {
                'title': 'You already have virtual hosting',
                'user': user,
            },
        )

    if request.method == 'POST':
        form = VirtualHostForm(request.POST)

        if form.is_valid():
            requested_subdomain = form.cleaned_data['requested_subdomain']
            requested_why = form.cleaned_data['requested_why']
            comments = form.cleaned_data['comments']
            your_name = form.cleaned_data['your_name']
            your_email = form.cleaned_data['your_email']
            your_position = form.cleaned_data['your_position']

            if not error:
                # send email to hostmaster@ocf and redirect to success page
                ip_addr = get_real_ip(request)

                try:
                    ip_reverse = socket.gethostbyaddr(ip_addr)[0]
                except:
                    ip_reverse = 'unknown'

                subject = 'Virtual Hosting Request: {} ({})'.format(
                    requested_subdomain,
                    user,
                )
                message = dedent('''\
                    Virtual Hosting Request:
                      - OCF Account: {user}
                      - OCF Account Title: {title}
                      - Requested Subdomain: {requested_subdomain}
                      - Current URL: https://www.ocf.berkeley.edu/~{user}/

                    Request Reason:
                    {requested_why}

                    Comments/Special Requests:
                    {comments}

                    Requested by:
                      - Name: {your_name}
                      - Position: {your_position}
                      - Email: {your_email}
                      - IP Address: {ip_addr} ({ip_reverse})
                      - User Agent: {user_agent}

                    --------
                    Request submitted to ocfweb ({hostname}) on {now}.
                    {full_path}''').format(
                    user=user,
                    title=attrs['cn'][0],
                    requested_subdomain=requested_subdomain,
                    requested_why=requested_why,
                    comments=comments,
                    your_name=your_name,
                    your_position=your_position,
                    your_email=your_email,
                    ip_addr=ip_addr,
                    ip_reverse=ip_reverse,
                    user_agent=request.META.get('HTTP_USER_AGENT'),
                    now=datetime.datetime.now().strftime(
                        '%A %B %e, %Y @ %I:%M:%S %p',
                    ),
                    hostname=socket.gethostname(),
                    full_path=request.build_absolute_uri(),
                )

                try:
                    send_mail(
                        '*****@*****.**' if not settings.DEBUG else current_user_formatted_email(),
                        subject,
                        message,
                        sender=your_email,
                    )
                except Exception as ex:
                    # TODO: report via ocflib
                    print(ex)
                    print('Failed to send vhost request email!')
                    error = \
                        'We were unable to submit your virtual hosting ' + \
                        'request. Please try again or email us at ' + \
                        '*****@*****.**'
                else:
                    return redirect(reverse('request_vhost_success'))
    else:
        form = VirtualHostForm(initial={'requested_subdomain': user + '.berkeley.edu'})

    group_url = 'https://www.ocf.berkeley.edu/~{0}/'.format(user)

    return render(
        request,
        'account/vhost/index.html',
        {
            'attrs': attrs,
            'error': error,
            'form': form,
            'group_url': group_url,
            'title': 'Request berkeley.edu virtual hosting',
            'user': user,
        },
    )
Пример #17
0
                                    correct_sentence=sentence,
                                    facilitator=co.facilitator,
                                    feedback=co.feedback)

        to_email = email_for_user(co.username)

        try:
            cursor = db.get_cursor()
            checkoff.insert_into_db(cursor, co)
        except:
            db.db.rollback()
            db.db.close()
            raise
        else:
            db.db.commit()

            # send the email
            send_mail(
                to=to_email,
                subject='[Decal] Feedback on lab {}'.format(co.labid),
                body=full_text,
                cc='*****@*****.**',
                sender='*****@*****.**',
            )

    except Exception as err:
        # Subtract 1 from the rowid to cancel out the first header row. This will print the actual row when looking at the google doc
        print('Error on row {} (facilitator: {})'.format(
            co.rowid - 1, co.facilitator))
        traceback.print_tb(err.__traceback__)
Пример #18
0
def request_vhost(request: HttpRequest) -> HttpResponse:
    user = logged_in_user(request)
    attrs = user_attrs(user)
    is_group = 'callinkOid' in attrs
    error = None

    if has_vhost(user):
        return render(
            request,
            'account/vhost/already_have_vhost.html',
            {
                'title': 'You already have virtual hosting',
                'user': user,
            },
        )
    elif not eligible_for_vhost(user):
        return render(
            request,
            'account/vhost/not_eligible.html',
            {
                'title': 'You are not eligible for virtual hosting',
                'user': user,
            },
        )

    if request.method == 'POST':
        form = VirtualHostForm(is_group, request.POST)

        if form.is_valid():
            requested_subdomain = form.cleaned_data['requested_subdomain']
            university_purpose = form.cleaned_data['university_purpose']
            university_contact = form.cleaned_data['university_contact']
            comments = form.cleaned_data['comments']
            your_name = form.cleaned_data['your_name'] if is_group else attrs[
                'cn'][0]
            your_email = form.cleaned_data['your_email']
            your_position = form.cleaned_data['your_position']

            if not error:
                # send email to hostmaster@ocf and redirect to success page
                ip_addr, _ = get_client_ip(request)

                try:
                    ip_reverse = socket.gethostbyaddr(ip_addr)[0]
                except socket.herror:
                    ip_reverse = 'unknown'

                subject = 'Virtual Hosting Request: {} ({})'.format(
                    requested_subdomain,
                    user,
                )
                message = dedent('''\
                    Virtual Hosting Request:
                      - OCF Account: {user}
                      - OCF Account Title: {title}
                      - Requested Subdomain: {requested_subdomain}
                      - Current URL: https://www.ocf.berkeley.edu/~{user}/

                    University Hostmaster Questions:
                      - Purpose: {university_purpose}
                      - Contact: {university_contact}

                    Comments/Special Requests:
                    {comments}

                    Requested by:
                      - Name: {your_name}
                      - Position: {your_position}
                      - Email: {your_email}
                      - IP Address: {ip_addr} ({ip_reverse})
                      - User Agent: {user_agent}

                    --------
                    Request submitted to ocfweb ({hostname}) on {now}.
                    {full_path}''').format(
                    user=user,
                    title=attrs['cn'][0],
                    requested_subdomain=requested_subdomain,
                    university_purpose=university_purpose,
                    university_contact=university_contact,
                    comments=comments,
                    your_name=your_name,
                    your_position=your_position,
                    your_email=your_email,
                    ip_addr=ip_addr,
                    ip_reverse=ip_reverse,
                    user_agent=request.META.get('HTTP_USER_AGENT'),
                    now=datetime.datetime.now().strftime(
                        '%A %B %e, %Y @ %I:%M:%S %p', ),
                    hostname=socket.gethostname(),
                    full_path=request.build_absolute_uri(),
                )

                try:
                    send_mail(
                        '*****@*****.**' if not settings.DEBUG
                        else current_user_formatted_email(),
                        subject,
                        message,
                        sender=your_email,
                    )
                except Exception as ex:
                    # TODO: report via ocflib
                    print(ex)
                    print('Failed to send vhost request email!')
                    error = \
                        'We were unable to submit your virtual hosting ' + \
                        'request. Please try again or email us at ' + \
                        '*****@*****.**'
                else:
                    return redirect(reverse('request_vhost_success'))
    else:
        # Unsupported left operand type for + ("None") because form might not have been instantiated at this point...
        # but this doesn't matter because of if-else clause
        form = VirtualHostForm(
            is_group, initial={'requested_subdomain':
                               user + '.berkeley.edu'})  # type: ignore

    group_url = f'https://www.ocf.berkeley.edu/~{user}/'

    return render(
        request,
        'account/vhost/index.html',
        {
            'attrs': attrs,
            'error': error,
            'form': form,
            'group_url': group_url,
            'is_group': is_group,
            'title': 'Request virtual hosting',
            'user': user,
        },
    )
Пример #19
0
CCN = '28246'
SUBJECT = '[Linux SysAdmin Decal] Fall 2018 Enrollment Code'
FROM = '*****@*****.**'
CC = '*****@*****.**'
MYSQL_PWD = open('mysqlpwd', 'r').read().strip()

message = dedent('''
Hello {name},

Welcome to the Fall 2018 edition of the Linux Sysadmin DeCal. Please use the code {code} to enroll in CS 198-8, CCN #{ccn}.

Thank you,

DeCal Staff
''').strip()

with get_connection('decal', MYSQL_PWD, 'decal') as c:
    c.execute(
        'SELECT `username`, `enrollment_code` FROM students WHERE semester = 4;'
    )
    for c in c.fetchall():
        username = c['username']
        enrollment_code = c['enrollment_code']
        name = user_attrs(username)['cn'][0]
        email = '{}@ocf.berkeley.edu'.format(username)
        materialized_message = message.format(name=name,
                                              code=enrollment_code,
                                              ccn=CCN)
        print('Sending enrollment email to:', email)
        send_mail(email, SUBJECT, materialized_message, cc=CC, sender=FROM)