Пример #1
0
def test_send_googl_message():
    with app.app.app_context():
        from app import get_db
        g.db = get_db(filespec)
        success, mes = mail.send_message(
            [("Bill Leddy", '*****@*****.**')],
            body="This is a test",
            subject="Simple Test")
        assert success == True
        assert "sent successfully" in mes
Пример #2
0
def activate():
    """Allow administrator to activate a new user"""

    activate = request.args.get('activate', None)
    if activate:
        user = User(g.db)
        rec = user.select_one(
            where='access_token = "{}"'.format(activate.strip()))
        if rec:
            rec.active = 1
            rec.access_token = None
            rec.access_token_expires = None
            user.save(rec)
            g.db.commit()

            # inform user that their account is now active
            full_name = '{} {}'.format(rec.first_name, rec.last_name).strip()
            to = [(full_name, rec.email)]
            context = {
                'rec': rec,
            }
            subject = 'Account Activated'
            html_template = 'email/activation_complete.html'
            text_template = 'email/activation_complete.txt'
            send_message(to,
                         context=context,
                         subject=subject,
                         html_template=html_template,
                         text_template=text_template)

        else:
            flash("User not found with access_token: {}".format(activate))
            return redirect('/')

    else:
        flash("Activation code not in request args")
        return redirect('/')

    flash("New User Activation Successful")
    return edit(rec.id)
Пример #3
0
def recover_password():
    """Send reset password and send user an email if they forget their password"""

    setExits()
    g.title = "Reset Password"
    rec = None
    temp_pass = None
    email_not_found = False

    if not request.form:
        pass
    else:
        #find the user with that email
        rec = User(g.db).select_one(where='lower(email) = lower("{}")'.format(
            request.form['email'].strip().lower()))
        if rec == None:
            flash(
                "That email address could not be found in the list of users.")
        else:
            # generate a new password that is unique to the system
            temp_pass = get_access_token()
            # save the temporary password
            rec.access_token = temp_pass
            rec.access_token_expires = time() + (3600 * 48)  # 2 days to reset
            User(g.db).save(rec)
            g.db.commit()

            # send an email with instructions
            from shotglass2.takeabeltof.mailer import send_message
            full_name = rec.first_name + " " + rec.last_name
            context = {
                'temp_pass': temp_pass,
                'rec': rec,
                'full_name': full_name
            }
            to_address_list = [
                (full_name, rec.email),
            ]
            result, msg = send_message(
                to_address_list,
                context=context,
                html_template='email/confirm_reset.html',
                text_template='email/confirm_reset.txt',
                subject='Confirm Password Reset')

    # Return a page telling user what we did
    return render_template('recover_password.html',
                           temp_pass=temp_pass,
                           rec=rec)
Пример #4
0
def test_send_message():
    with app.app.app_context():
        from app import get_db
        g.db = get_db(filespec)
        success, mes = mail.send_message([("Bill Leddy", '*****@*****.**')],
                                         body="This is a test",
                                         subject="Simple Test")
        assert success == True
        assert "sent successfully" in mes

        # try sending with the name and addres in the wrong order
        success, mes = mail.send_message(
            [('*****@*****.**', "Bill Leddy")],
            body="This is a test with name and address params reversed",
            subject="Reversed address Test")
        assert success == True
        assert "sent successfully" in mes

        # try address only
        success, mes = mail.send_message(["*****@*****.**"],
                                         body="Address only test test",
                                         subject="Address Test")
        assert success == True
        assert "sent successfully" in mes

        #try sending to a group
        success, mes = mail.send_message([("bill Leddy", '*****@*****.**'),
                                          ('*****@*****.**')],
                                         body="This is a group email",
                                         subject="Group Email")
        assert success == True
        assert "sent successfully" in mes

        success, mes = mail.send_message()
        assert success == False
        assert mes == "Message contained no body content."
Пример #5
0
def contact():
    setExits()
    g.title = 'Contact Us'
    from shotglass2.shotglass import get_site_config
    from shotglass2.takeabeltof.mailer import send_message
    rendered_html = render_markdown_for('contact.md',mod)
    
    show_form = True
    context = {}
    success = True
    bcc=None
    passed_quiz = False
    site_config = get_site_config()
    mes = "No errors yet..."
    if request.form:
        #import pdb;pdb.set_trace()
        quiz_answer = request.form.get('quiz_answer',"A")
        if quiz_answer.upper() == "C":
            passed_quiz = True
        else:
            flash("You did not answer the quiz correctly.")
        if request.form['email'] and request.form['comment'] and passed_quiz:
            context.update({'date':datetime_as_string()})
            for key, value in request.form.items():
                context.update({key:value})
                
            # get best contact email
            to = []
            # See if the contact info is in Prefs
            try:
                from shotglass2.users.views.pref import get_contact_email
                contact_to = get_contact_email()
                if contact_to:
                    to.append(contact_to)
            except Exception as e:
                printException("Need to update home.contact to find contacts in prefs.","error",e)
                
            try:
                if not to:
                    to = [(site_config['CONTACT_NAME'],site_config['CONTACT_EMAIL_ADDR'],),]
                if site_config['CC_ADMIN_ON_CONTACT'] and site_config['ADMIN_EMAILS']:
                    bcc = site_config['ADMIN_EMAILS']
                
            except KeyError as e:
                mes = "Could not get email addresses."
                mes = printException(mes,"error",e)
                if to:
                    #we have at least a to address, so continue
                    pass
                else:
                    success = False
                    
            if success:
                # Ok so far... Try to send
                success, mes = send_message(
                                    to,
                                    subject = "Contact from {}".format(site_config['SITE_NAME']),
                                    html_template = "home/email/contact_email.html",
                                    context = context,
                                    reply_to = request.form['email'],
                                    bcc=bcc,
                                )
        
            show_form = False
        else:
            context = request.form
            flash('You left some stuff out.')
            
    if success:
        return render_template('contact.html',rendered_html=rendered_html, show_form=show_form, context=context,passed_quiz=passed_quiz)
            
    handle_request_error(mes,request,500)
    flash(mes)
    return render_template('500.html'), 500
Пример #6
0
def inform_admin_of_registration(rec):
    site_config = get_site_config()

    to = [(site_config['MAIL_DEFAULT_SENDER'],
           site_config['MAIL_DEFAULT_ADDR'])]

    #Add User List administrators
    reply_to = to.copy()[0]
    user_admin = Pref(g.db).get(
        "New Account Admins",
        user_name=site_config.get("HOST_NAME"),
        default=site_config['MAIL_DEFAULT_ADDR'],
        description=
        "Admin for New User registrations. May use a comma separated list.",
    )
    to.append((user_admin.name, user_admin.value))

    deleteURL = "{}://{}{}?delete={}".format(
        site_config['HOST_PROTOCOL'],
        site_config['HOST_NAME'],
        g.deleteURL,
        rec.access_token,
    )
    editURL = "{}://{}{}{}".format(
        site_config['HOST_PROTOCOL'],
        site_config['HOST_NAME'],
        url_for('.edit'),
        rec.id,
    )
    confirmURL = "{}://{}{}?activate={}".format(
        site_config['HOST_PROTOCOL'],
        site_config['HOST_NAME'],
        url_for('.activate'),
        rec.access_token,
    )

    context = {
        'rec':
        rec,
        'deleteURL':
        deleteURL,
        'editURL':
        editURL,
        'registration_exp':
        datetime.fromtimestamp(
            rec.access_token_expires).strftime('%Y-%m-%d %H:%M:%S'),
        'confirmURL':
        confirmURL,
    }
    subject = 'Unconfirmed Account Request from - {}'.format(
        site_config['SITE_NAME'])
    if site_config.get('AUTOMATICALLY_ACTIVATE_NEW_USERS', False):
        subject = 'New Account Auto Activated - {}'.format(
            site_config['SITE_NAME'])
        del context['confirmURL']

    html_template = 'email/admin_activate_acct.html'
    text_template = None
    send_message(to,
                 context=context,
                 reply_to=reply_to,
                 subject=subject,
                 html_template=html_template,
                 text_template=text_template)
Пример #7
0
def register():
    """Allow people to sign up thier own accounts on the web site"""
    setExits()
    site_config = get_site_config()

    g.title = "Account Registration"
    g.editURL = url_for('.register')
    g.listURL = '/'  # incase user cancels
    user = User(g.db)
    rec = user.new()

    is_admin = False
    user_roles = None
    roles = None
    no_delete = True
    success = True
    help = render_markdown_for("new_account_help.md", mod)
    next = request.form.get('next', request.args.get('next', ''))

    # import pdb;pdb.set_trace()

    if 'confirm' in request.args:
        #Try to find the user record that requested registration
        rec = user.select_one(where='access_token = "{}"'.format(
            request.args.get('confirm', '')).strip())
        if rec and rec.access_token_expires > time():
            if site_config.get('ACTIVATE_USER_ON_CONFIRMATION', False):
                rec.active = 1
                user.save(rec, commit=True)
                # log the user in
                setUserStatus(rec.email, rec.id)

            if rec.active == 1:
                success = "active"
            else:
                success = "waiting"

            #inform the admins
            inform_admin_of_registration(rec)

            return render_template('registration_success.html',
                                   success=success,
                                   next=next)
        else:
            flash("That registration request has expired")
            return redirect('/')

    if request.form:
        #update the record
        user.update(rec, request.form)

        if validForm(rec):
            rec.active = 0  # Self registered accounts are inactive by default
            set_password_from_form(rec)
            set_username_from_form(rec)
            rec.access_token = get_access_token()
            rec.access_token_expires = time() + (3600 * 48)
            if site_config.get('AUTOMATICALLY_ACTIVATE_NEW_USERS', False):
                rec.active = 1
                success = "active"

            try:
                user.save(rec)

                # give user default roles
                for role in site_config.get('DEFAULT_USER_ROLES', ['user']):
                    User(g.db).add_role(rec.id, role)

                g.db.commit()
                # log the user in
                setUserStatus(rec.email, rec.id)

                #inform the admins
                inform_admin_of_registration(rec)

                #Send confirmation email to user if not already active
                full_name = '{} {}'.format(rec.first_name,
                                           rec.last_name).strip()
                to = [(full_name, rec.email)]
                context = {'rec': rec, 'confirmation_code': rec.access_token}
                subject = 'Please confirm your account registration at {}'.format(
                    site_config['SITE_NAME'])
                html_template = 'email/registration_confirm.html'
                text_template = 'email/registration_confirm.txt'
                if rec.active == 1:
                    subject = 'Your account is now active at {}'.format(
                        site_config['SITE_NAME'])
                    html_template = 'email/activation_complete.html'
                    text_template = 'email/activation_complete.txt'

                send_message(to,
                             context=context,
                             subject=subject,
                             html_template=html_template,
                             text_template=text_template)

            except Exception as e:
                g.db.rollback()
                mes = "An error occured while new user was attempting to register"
                printException(mes, "error", e)
                # Send email to the administrator
                to = [(site_config['MAIL_DEFAULT_SENDER'],
                       site_config['MAIL_DEFAULT_ADDR'])]
                context = {'mes': mes, 'rec': rec, 'e': str(e)}
                body = "Signup Error\n{{context.mes}}\n{{context.e}}\nrec:\n{{context.rec}}"
                send_message(to, context=context, body=body, subject=mes)
                success = False

            return render_template(
                'registration_success.html',
                success=success,
                next=next,
            )

    return render_template(
        'user_edit.html',
        rec=rec,
        no_delete=no_delete,
        is_admin=is_admin,
        next=next,
    )
Пример #8
0
def edit(rec_handle=None):
    setExits()
    g.title = "Edit {} Record".format(g.title)
    #import pdb;pdb.set_trace()
    site_config = get_site_config()

    user = User(g.db)
    rec = None
    request_rec_id = cleanRecordID(
        request.form.get('id', request.args.get('id', -1)))
    is_admin = g.admin.has_access(g.user, User)
    no_delete = not is_admin
    new_password = ''
    confirm_password = ''
    user_roles = ['user']  # default

    #limit roles to roles <= current users rank
    curr_user_max_rank = user.max_role_rank(g.user)
    roles = Role(g.db).select(where="rank <= {}".format(curr_user_max_rank))

    include_inactive = True
    next = request.form.get('next', request.args.get('next', ''))

    if not is_admin:
        g.listURL = g.homeURL  # Non admins can't see the list
        include_inactive = False

    if rec_handle != None:
        pass  #rec_handle has to come from admin() at this point
    elif rec_handle == None and g.user != None and request_rec_id == -1:
        rec_handle = g.user
    else:
        rec_handle = request_rec_id
        if rec_handle < 0:
            flash("That is not a valid User ID")
            return redirect(g.listURL)

    if not request.form:
        """ if no form object, send the form page """
        if rec_handle != g.user and not is_admin:
            flash("You do not have access to that area")
            return redirect(g.homeURL)
        elif curr_user_max_rank < user.max_role_rank(rec_handle):
            flash(
                "You don't have sufficiant privelages to edit that user record."
            )
            return redirect(g.homeURL)
        elif rec_handle == 0:
            rec = user.new()
        else:
            rec = user.get(rec_handle, include_inactive=include_inactive)
            if not rec:
                flash("Unable to locate user record")
                return redirect('/')

            user_roles = get_user_role_names(rec)

    else:
        #have the request form
        # import pdb;pdb.set_trace()
        is_new_user = False
        if rec_handle and request.form['id'] != 'None':
            rec = user.get(rec_handle, include_inactive=include_inactive)
            user_roles = get_user_role_names(rec)
        else:
            # its a new unsaved record
            is_new_user = True
            rec = user.new()
            user.update(rec, request.form)

        if validForm(rec):

            #Are we editing the current user's record?
            editingCurrentUser = ''
            if (g.user == rec.username):
                if 'new_username' in request.form:
                    editingCurrentUser = request.form['new_username'].strip()
                else:
                    editingCurrentUser = g.user
            else:
                if (g.user == rec.email):
                    editingCurrentUser = request.form['email'].strip()

            #update the record
            user.update(rec, request.form)

            # ensure these are ints
            if 'may_send_email' in rec._fields:
                rec.may_send_email = cleanRecordID(rec.may_send_email)
            if 'may_send_text' in rec._fields:
                rec.may_send_text = cleanRecordID(rec.may_send_text)

            set_username_from_form(rec)
            set_password_from_form(rec)

            try:
                user.save(rec)

                # update the user roles
                if 'roles_select' in request.form:
                    # import pdb;pdb.set_trace()
                    #delete all the users current roles
                    user.clear_roles(rec.id)
                    for role_name in request.form.getlist('roles_select'):
                        #find the role by name
                        role = Role(g.db).select_one(
                            where='name = "{}"'.format(role_name))
                        if role:
                            user.add_role(rec.id, role.id)

                # if the username or email address are the same as g.user
                # update g.user if it changes
                if (editingCurrentUser != ''):
                    setUserStatus(editingCurrentUser, rec.id)

                g.db.commit()

            except Exception as e:
                g.db.rollback()
                flash(
                    printException(
                        'Error attempting to save ' + g.title + ' record.',
                        "error", e))
                return redirect(g.listURL)

            if is_new_user:
                rec.access_token = get_access_token()
                rec.access_token_expires = time() + (3600 * 48)

                #inform the admins
                inform_admin_of_registration(rec)

                # send an email to welcome the new user
                full_name = '{} {}'.format(rec.first_name,
                                           rec.last_name).strip()

                context = {
                    'rec': rec,
                    'full_name': full_name,
                }
                to_address_list = [(full_name, rec.email)]
                sent, msg = send_message(
                    to_address_list,
                    subject="Welcome to {{ site_config.SITE_NAME}}",
                    context=context,
                    html_template='email/welcome.html',
                    text_template='email/welcome.txt',
                )
                if not sent:
                    flash('The welcome message could not be sent. Error: {}'.
                          format(msg))

            return redirect(g.listURL)

        else:
            # form did not validate, give user the option to keep their old password if there was one
            #need to restore the username
            user.update(rec, request.form)
            if 'new_username' in request.form:
                rec.username = request.form[
                    'new_username']  #preserve user input
            # preserve the selected roles
            #import pdb;pdb.set_trace()
            if 'roles_select' in request.form:
                user_roles = request.form.getlist('roles_select')
            #and password
            new_password = request.form.get('new_password', '')
            confirm_password = request.form.get('confirm_password', '')

    # display form
    return render_template(
        'user_edit.html',
        rec=rec,
        no_delete=no_delete,
        is_admin=is_admin,
        next=next,
        user_roles=user_roles,
        roles=roles,
        new_password=new_password,
        confirm_password=confirm_password,
    )
Пример #9
0
def contact(**kwargs):
    """Send an email to the administator or contact specified.
    
    kwargs:
    
        to_addr: the address to send to
        
        to_contact: Name of contact
        
        subject: The email subject text
        
        custom_message: Message to display at top of contact form. should be html
        
        html_template: The template to use for the contact form
    
    """
    setExits()
    g.title = 'Contact Us'
    from shotglass2.shotglass import get_site_config
    from shotglass2.takeabeltof.mailer import send_message

    #import pdb;pdb.set_trace()

    site_config = get_site_config()
    show_form = True
    context = {}
    success = True
    bcc = None
    passed_quiz = False
    mes = "No errors yet..."
    to = []

    if not kwargs and request.form and 'kwargs' in request.form:
        kwargs = json.loads(request.form.get('kwargs', '{}'))

    subject = kwargs.get('subject',
                         "Contact from {}".format(site_config['SITE_NAME']))
    html_template = kwargs.get('html_template',
                               "home/email/contact_email.html")
    to_addr = kwargs.get('to_addr')
    to_contact = kwargs.get('to_contact', to_addr)
    custom_message = kwargs.get('custom_message')
    if to_addr:
        to.append((to_contact, to_addr))

    if custom_message:
        rendered_html = custom_message
    else:
        rendered_html = render_markdown_for('contact.md', mod)

    if request.form:
        quiz_answer = request.form.get('quiz_answer', "A")
        if quiz_answer.upper() == "C":
            passed_quiz = True
        else:
            flash("You did not answer the quiz correctly.")
        if request.form['email'] and request.form['comment'] and passed_quiz:
            context.update({'date': datetime_as_string()})
            for key, value in request.form.items():
                context.update({key: value})

            # get best contact email
            if not to:
                # See if the contact info is in Prefs
                try:
                    from shotglass2.users.views.pref import get_contact_email
                    contact_to = get_contact_email()
                    # contact_to may be a tuple, a list or None
                    if contact_to:
                        if not isinstance(contact_to, list):
                            contact_to = [contact_to]
                        to.extend(contact_to)

                except Exception as e:
                    printException(
                        "Need to update home.contact to find contacts in prefs.",
                        "error", e)

                try:
                    if not to:
                        to = [
                            (
                                site_config['CONTACT_NAME'],
                                site_config['CONTACT_EMAIL_ADDR'],
                            ),
                        ]
                    if site_config['CC_ADMIN_ON_CONTACT'] and site_config[
                            'ADMIN_EMAILS']:
                        bcc = site_config['ADMIN_EMAILS']

                except KeyError as e:
                    mes = "Could not get email addresses."
                    mes = printException(mes, "error", e)
                    if to:
                        #we have at least a to address, so continue
                        pass
                    else:
                        success = False

            if success:
                # Ok so far... Try to send
                success, mes = send_message(
                    to,
                    subject=subject,
                    html_template=html_template,
                    context=context,
                    reply_to=request.form['email'],
                    bcc=bcc,
                    custom_message=custom_message,
                    kwargs=kwargs,
                )

            show_form = False
        else:
            context = request.form
            flash('You left some stuff out.')

    if success:
        return render_template(
            'contact.html',
            rendered_html=rendered_html,
            show_form=show_form,
            context=context,
            passed_quiz=passed_quiz,
            kwargs=kwargs,
        )

    handle_request_error(mes, request)
    flash(mes)
    return render_template('500.html'), 500