Exemple #1
0
def test_getDatetimeFromString():
    site_config = get_site_config()

    assert dates.getDatetimeFromString("12/14/12") == dates.make_tz_aware(
        datetime(2012, 12, 14), site_config["TIME_ZONE"])
    assert dates.getDatetimeFromString("2012-12-14") == dates.make_tz_aware(
        datetime(2012, 12, 14), site_config["TIME_ZONE"])
    assert dates.getDatetimeFromString("12/14/2012") == dates.make_tz_aware(
        datetime(2012, 12, 14), site_config["TIME_ZONE"])
    assert dates.getDatetimeFromString("2/8/19") == dates.make_tz_aware(
        datetime(2019, 2, 8), site_config["TIME_ZONE"])
    assert dates.getDatetimeFromString("2/8/51") == dates.make_tz_aware(
        datetime(1951, 2, 8), site_config["TIME_ZONE"])

    #test what happens when you pass in a date time
    assert dates.getDatetimeFromString(datetime(2019, 2,
                                                8)) == dates.make_tz_aware(
                                                    datetime(2019, 2, 8),
                                                    site_config["TIME_ZONE"])
    assert dates.getDatetimeFromString(
        datetime(2019, 2, 8, 6, 33,
                 00)) == dates.make_tz_aware(datetime(2019, 2, 8, 6, 33, 00),
                                             site_config["TIME_ZONE"])
    # Pass in a date
    assert dates.getDatetimeFromString(date(2019, 2,
                                            8)) == dates.make_tz_aware(
                                                datetime(2019, 2, 8),
                                                site_config["TIME_ZONE"])
Exemple #2
0
    def __init__(self, local_path='', resource_path=''):
        from app import app
        site_config = get_site_config()

        if not resource_path:
            resource_path = site_config.get('DOWNLOAD_FOLDER',
                                            'resource/static')
        self.resource_path = Path(
            app.root_path, site_config.get('DOWNLOAD_FOLDER',
                                           'resource/static'))
        self.local_path = Path(
            local_path
        )  # directory below resource_path to separate files from others
        self.filename = None
        self.success = True
        self.error_text = ''
        self.saved_file_path = Path()
        default_extensions = {
            'txt',
            'pdf',
            'png',
            'jpg',
            'jpeg',
            'gif',
        }
        self.allowed_extensions = site_config.get("ALLOWED_EXTENSIONS",
                                                  default_extensions)
Exemple #3
0
def docs(filename=None):
    #setExits()
    g.title = "Docs"
    from shotglass2.shotglass import get_site_config
    site_config = get_site_config()
    
    #import pdb;pdb.set_trace()
    
    file_exists = False
    if not filename:
        filename = "README.md"
    else:
        filename = filename.strip('/')
        
    # first try to get it as a (possibly) valid path
    temp_path = os.path.join(os.path.dirname(os.path.abspath(__name__)),filename)
    if not os.path.isfile(temp_path):
        # try the default doc dir
        temp_path = os.path.join(os.path.dirname(os.path.abspath(__name__)),'docs',filename)
        
    if not os.path.isfile(temp_path) and 'DOC_DIRECTORY_LIST' in site_config:
        for path in site_config['DOC_DIRECTORY_LIST']:
            temp_path = os.path.join(os.path.dirname(os.path.abspath(__name__)),path.strip('/'),filename)
            if os.path.isfile(temp_path):
                break
            
    filename = temp_path
    file_exists = os.path.isfile(filename)
            
    if file_exists:
        rendered_html = render_markdown_for(filename,mod)
        return render_template('markdown.html',rendered_html=rendered_html)
    else:
        #file not found
        return abort(404)
Exemple #4
0
def send_static_file(filename, **kwargs):
    """Send the file if it exists, else try to send it from the static directory"""
    from shotglass2.shotglass import get_site_config

    path_list = kwargs.get('path_list', ['static', 'shotglass2/static'])

    path = None

    explain = get_site_config().get('EXPLAIN_TEMPLATE_LOADING', False)

    if explain:
        print("\nSearching for {}".format(filename))

    for temp_path in path_list:
        file_loc = os.path.join(os.path.dirname(os.path.abspath(__name__)),
                                temp_path, filename)
        if os.path.isfile(file_loc):
            path = temp_path
            if explain:
                print("{} was found at {}".format(
                    filename,
                    os.path.join(os.path.dirname(os.path.abspath(__name__)),
                                 temp_path)))
            break
        else:
            if explain:
                print("{} was not found at {}".format(
                    filename,
                    os.path.join(os.path.dirname(os.path.abspath(__name__)),
                                 temp_path)))

    if path:
        return send_from_directory(path, filename, as_attachment=False)

    return abort(404)
Exemple #5
0
def test_nowString():
    # This is really an alias to datetime_as_string
    site_config = get_site_config()

    site_config['TIME_ZONE'] = 'US/Pacific'

    now = dates.nowString()
    assert now == dates.datetime_as_string(datetime.now())
Exemple #6
0
 def alert_admin(self,message):
     """Send an email to the admin address if an error is encountered or
     if you just fell like talking...
 
     """
     from shotglass2.takeabeltof.mailer import email_admin
     from shotglass2.shotglass import get_site_config
 
     email_admin("Error in database access for {}".format(get_site_config()['HOST_NAME']),message)
Exemple #7
0
def start_app():
    shotglass.start_logging(app)
    get_db()  # ensure that the database file exists
    # shotglass.start_backup_thread(os.path.join(app.root_path,app.config['DATABASE_PATH']))
    # use os.path.normpath to resolve true path to data file when using '../' shorthand
    shotglass.start_backup_thread(
        os.path.normpath(
            os.path.join(app.root_path,
                         shotglass.get_site_config()['DATABASE_PATH'])))
Exemple #8
0
def get_contact_email():
    """Return a tuple of the contact name and email address 
    or a list of tuples 
    or None"""
    from shotglass2.shotglass import get_site_config

    site_config = get_site_config()

    to = None
    to_name = None
    to_addr = None

    rec = Pref(g.db).get("Contact Name",
                         user_name=site_config.get("HOST_NAME"),
                         default=site_config.get(
                             "CONTACT_NAME",
                             site_config.get("MAIL_DEFAULT_SENDER",
                                             "Site Contact")))
    if rec:
        to_name = rec.value

    if site_config['TESTING']:
        rec = Pref(g.db).select_one(
            where="name='Contact Email Address' and user_name='test'")
    else:
        rec = Pref(g.db).get("Contact Email Address",
                             user_name=site_config.get("HOST_NAME"),
                             default=site_config.get(
                                 "CONTACT_EMAIL_ADDR",
                                 site_config.get(
                                     "MAIL_DEFAULT_ADDR", "info@{}".format(
                                         site_config.get(
                                             "HOST_NAME", "example.com")))))
    if rec:
        to_addr = rec.value
        # split the addresses into a list if there are commas
        temp_addr_list = to_addr.split(',')
        if len(temp_addr_list) > 1:
            to = []
            for index, val in enumerate(temp_addr_list):
                if index == 0:
                    to.append((
                        to_name,
                        val,
                    ))
                else:
                    to.append((
                        None,
                        val,
                    ))
        else:
            to = (
                to_name,
                to_addr,
            )

    return to
Exemple #9
0
def test_make_tz_aware():
    # make_tz_aware(the_datetime,time_zone=None)
    site_config = get_site_config()

    zone = site_config["TIME_ZONE"]
    aware = dates.make_tz_aware(datetime.now(), zone)
    now = dates.local_datetime_now()
    assert aware.tzinfo.zone == zone
    aware = dates.make_tz_aware(datetime.now())
    assert aware.tzinfo.zone == site_config["TIME_ZONE"]
Exemple #10
0
def get_time_zone_setting():
    """Return the TIME_ZONE config setting if it exists else None"""
    try:
        from shotglass2.shotglass import get_site_config

        time_zone = get_site_config()['TIME_ZONE']
    except:
        time_zone = None

    return time_zone
Exemple #11
0
    def __init__(self, address_list=[], **kwargs):
        # import pdb;pdb.set_trace()
        self._to = []
        # some old code will set address_to to None
        if address_list == None:
            address_list = []

        self.add_address(address_list)

        self.site_config = get_site_config()
        self.admin_name = self.site_config['MAIL_DEFAULT_SENDER']
        self.admin_addr = self.site_config['MAIL_DEFAULT_ADDR']
        self.kwargs = kwargs  # templates may need values here...
        self.body = kwargs.get('body', None)
        self.body_is_html = kwargs.get('body_is_html', None)
        self.text_template = kwargs.get('text_template', None)
        self.html_template = kwargs.get('html_template', None)
        self.subject_prefix = kwargs.get(
            'subject_prefix', self.site_config.get("MAIL_SUBJECT_PREFIX", ''))
        contact_address = get_contact_email()
        sender_name = self.admin_name
        sender_addr = self.admin_addr
        if contact_address:
            if isinstance(contact_address, list):
                # if there are multiple addresses in the contact list, just use the first for the sender
                contact_address = contact_address[0]  # returns a tuple
            sender_name = contact_address[0]
            sender_addr = contact_address[1]

        self.from_address = kwargs.get('from_address', sender_addr)
        self.from_sender = kwargs.get('from_sender', sender_name)
        self.reply_to = kwargs.get('reply_to', self.from_address)
        self._cc = kwargs.get('cc', [])
        self._bcc = kwargs.get('bcc', [])

        # import pdb;pdb.set_trace()
        try:
            if self.site_config['BCC_ADMINS_ON_ALL_EMAIL']:
                admins = self.site_config['ADMIN_EMAILS']
                if self._bcc is None:
                    self._bcc = []
                if not isinstance(admins, list):
                    admins = [admins]
                self._bcc.extend(admins)
        except KeyError:
            pass
        self._attachments = []
        self.subject = kwargs.get('subject', '').strip()
        # appends all attachments regardless of keyword used
        self.add_attachment(kwargs.get('attachments', None))
        self.add_attachment(kwargs.get('attachment', None))

        self.success = False
        self.result_text = 'initialized'
Exemple #12
0
def _before():
    # Force all connections to be secure
    if app.config['REQUIRE_SSL'] and not request.is_secure:
        return redirect(request.url.replace("http://", "https://"))

    #ensure that nothing is served from the instance directory
    if 'instance' in request.url:
        return abort(404)

    #import pdb;pdb.set_trace()

    session.permanent = True

    shotglass.get_site_config(app)
    shotglass.set_template_dirs(app)

    get_db()

    # Is the user signed in?
    g.user = None
    if 'user' in session:
        g.user = session['user']

    #g.menu_items = shotglass.get_menu_items()
    g.menu_items = [
        {
            'title': 'Home',
            'url': '/'
        },
        # {'title':'RSVP','url':url_for('www.rsvp')},
        # {'title':'Where to Stay','url':url_for('www.render_for', filename='where_to_stay')},
        # {'title':'Things to Do','url':url_for('www.render_for', filename='things_to_do')},
        # {'title':'Shopping','url':url_for('www.render_for', filename='shopping')},
        # {'title':'The Menu','url':url_for('www.render_for', filename='menu')},
        # {'title':'Churches','url':url_for('www.render_for',filename='churches')},
        # {'title':'Questions','url':url_for('www.contact')},
    ]

    g.admin = Admin(g.db)  # This is where user access rules are stored
    shotglass.user_setup(
    )  # g.admin now holds access rules Users, Prefs and Roles
Exemple #13
0
def edit_from_list(id=None, item_id=None):
    """Handle creation of transaction from the Item record form"""
    setExits()
    #import pdb;pdb.set_trace()

    item_id = cleanRecordID(item_id)
    item_rec = None
    rec = None
    warehouses = Warehouse(g.db).select()
    trx_types = get_site_config().get('trx_types', [
        'Add',
        'Remove',
    ])
    transaction = Transaction(g.db)
    trx_id = cleanRecordID(id)
    if trx_id > 0:
        rec = transaction.get(trx_id)

    if rec:
        item_id = rec.item_id
    else:
        rec = transaction.new()
        rec.created = local_datetime_now()
        if 'last_trx' in session:
            transaction.update(rec, session['last_trx'])

    # Handle Response?
    if request.form:
        #import pdb;pdb.set_trace()
        error_list = []
        transaction.update(rec, request.form)
        if save_record(rec, error_list):
            return "success"  # the success function looks for this...
        else:
            pass

    if item_id > 0:
        item_rec = Item(g.db).get(item_id)

    if not item_rec:
        flash("This is not a valid item id")
        return "failure: This is not a valid item id."
    else:
        rec.item_id = item_id

    return render_template('trx_edit_from_list.html',
                           rec=rec,
                           current_item=item_rec,
                           warehouses=warehouses,
                           trx_types=trx_types)
Exemple #14
0
 def __init__(self, **kwargs):
     site_config = get_site_config()
     super().__init__(self)
     self.add('version', '2.0')
     self.add('calscale', 'GREGORIAN')
     self.add('prodid',
              kwargs.get('prodid', site_config['HOST_NAME'].lower()))
     calendar_name = kwargs.get('calendar_name', None)
     if not calendar_name:
         self.add('x-priamry-calendar', 'TRUE')
     else:
         # give the calendar a name
         self.add('x-wr-calname', calendar_name)
         self.add('name', calendar_name)
Exemple #15
0
    def _text_to_numeric(self,field_name,value,column_type):
        """Attempt to coerce values for numeric fields to numbers if needed.
        
        Params:
        
            field_name: the name of the field being updated
            
            value: the value to convert
            
            column_type: the text name of the field type e.g. INTEGER, REAL, etc.
            
        Return the number or the original value if not successful
        
        Alerts admin on failure
        
        """
        
        from shotglass2.shotglass import get_site_config

        value = value.strip()
        column_type = column_type.upper()
        
        if type(value) != str:
            #safety valve
            return value
            
        if value == '':
           value = None
        elif value.isdigit():
           # convert to int
           value = int(value)
        else:
           # may be a float
           try:
               value = float(value)
               if column_type in self.integer_types:
                   value = int(value)
           except Exception as e:
                mes ="""A problem occurred while attempting to save the record for table {}. 
                It looks like a non-numeric value ('{}') was entered in the field '{}'.
                
                The information in the record may not be what you expect...

                """.format(self.table_name.title(),value,field_name)
                if not get_site_config()['TESTING']:
                    flash(mes)
                self.alert_admin(printException(mes,err=e))
               
        return value
Exemple #16
0
def test_local_datetime_now():
    site_config = get_site_config()
    #site_config['TIME_ZONE'] = 'US/Pacific'
    now = datetime.now()
    local_now = dates.local_datetime_now()
    assert now.day == local_now.day
    assert now.hour == local_now.hour
    assert now.month == local_now.month
    assert local_now.tzinfo is not None
    assert local_now.tzinfo.zone == site_config["TIME_ZONE"]

    # spcecify a time zone
    zone = "US/Eastern"
    east_now = dates.local_datetime_now(zone)
    assert east_now.tzinfo is not None
    assert east_now.tzinfo.zone == zone
Exemple #17
0
def printException(mes="An Unknown Error Occurred", level="error", err=None):
    """Generate an error message, write it to the log and return the resulting
    text.
    
    mes: Some message text specific to the supposed cause of the error.
    
    level: Any of 'error', 'info', 'debug'
    
    When logging or in debug mode attempts to generate a description of the error
    location.
    
    """
    from shotglass2.shotglass import get_site_config
    from app import app

    site_config = get_site_config()
    level = level.lower()

    exc_type, exc_obj, tb = sys.exc_info()
    debugMes = None
    if tb is not None:
        f = tb.tb_frame
        lineno = tb.tb_lineno
        filename = f.f_code.co_filename
        linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        try:
            debugMes = 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(
                filename, lineno, line.strip(), exc_obj)
        except ValueError:
            debugMes = "Could not get error location info."

    if level == "error" or site_config["DEBUG"]:
        if debugMes:
            app.logger.error(nowString() + " - " + debugMes)
        elif err:
            app.logger.error(nowString() + " - Error: " + str(err))

    if mes:
        app.logger.error(nowString() + " - " + mes)

    if site_config["DEBUG"]:
        if debugMes:
            mes = mes + " -- " + debugMes
        return mes
    else:
        return mes
Exemple #18
0
def handle_request_error(error=None, request=None):
    """Usually used to handle a basic request error such as a db error"""
    from shotglass2.takeabeltof.mailer import alert_admin
    from shotglass2.shotglass import get_site_config
    site_config = get_site_config()
    #import pdb; pdb.set_trace()
    mes = "An unknown error occured"
    level = "error"
    request_url = "No URL supplied"
    if request and hasattr(request, 'url'):
        request_url = request.url

    try:
        if error:
            if hasattr(error, 'code'):
                mes = 'The following error was reported from {}. Request status: {} '.format(
                    site_config['SITE_NAME'], error.code)
                if request:
                    mes += ' - Request URL: {}'.format(request_url)

                level = 'info' if error.code == 404 else "error"
                if (error.code == 404 and
                        site_config['REPORT_404_ERRORS']) or error.code != 404:
                    if request and 'apple-touch-icon' not in request_url and 'favicon' not in request_url:
                        alert_admin(
                            "Request error [{}] at {}".format(
                                error.code, site_config['HOST_NAME']), mes)
                        printException(mes, level=level, err=error)
            else:
                temp_mes = str(error)
                mes = printException(
                    "The following error occured: {} during request for {}".
                    format(temp_mes, request_url),
                    level=level,
                    err=error)
                alert_admin(
                    "System error from {}".format(site_config['SITE_NAME']),
                    mes)
        else:
            mes = "Error message not provided"

    except Exception as e:
        alert_admin(
            printException("An error was encountered in handle_request_error.",
                           err=e))

    return mes  # just to make it testable
Exemple #19
0
    def is_admin(self, user):
        """Return True if user (name or id) is an admin"""
        from shotglass2.shotglass import get_site_config

        rec = self.get(user)
        if not rec:
            return False
        admin_roles = get_site_config().get('ADMIN_ROLES', [
            'super',
            'admin',
        ])
        user_roles = self.get_roles(rec.id)
        if user_roles:
            for role in user_roles:
                if role.name in admin_roles:
                    return True
        return False
Exemple #20
0
def getPasswordHash(pw, theSalt=None, timesAround='05',encoding='utf-8'):
    """Return a string hash of the password or None"""
    from shotglass2.shotglass import get_site_config
    
    if type(pw) is str:
        pw = pw.strip()
        if pw == "":
            return None
            
        if not theSalt:
            theSalt = getPasswordSalt()
        codeWord = str(pw) + theSalt
        
        for i in range(int(timesAround) * 1000):
            codeWord = hmac.new(bytearray(get_site_config()['SECRET_KEY'].encode(encoding)), str(codeWord).encode(encoding), hashlib.sha256).hexdigest() 
        return theSalt +'.'+timesAround+'.'+codeWord
    return None
Exemple #21
0
    def get_credentials(self):
        """
        
        Load the API credentials and return the service discovery object instance
        
        Args: None
        
        Returns: googleapiclient.discovery instance
            
        Raises:
            MailSettingsError
        """

        site_config = get_site_config()

        # TOKEN_FILE_PATH = site_config.get('MAIL_TOKEN_PATH','')
        creds = None
        # the file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first time
        # set_trace()
        try:
            with open(self.token_file_path, "rb") as token:
                creds = pickle.load(token)
        except FileNotFoundError:
            raise MailSettingsError("Gmail API token file not found.")
        # if there are no (valid) credentials availablle stop here.
        if not creds:
            raise MailSettingsError("Gmail API credentials are missing.")

        if site_config.get('TESTING', False):
            return creds

        if creds.expired:  # and creds.refresh_token:
            creds.refresh(Request())
            # save the credentials for the next run
            with open(self.token_file_path, "wb") as token:
                pickle.dump(creds, token)
        try:
            return build('gmail', 'v1', credentials=creds)
        except Exception as e:
            raise MailSettingsError(
                "Gmail API could not build a connection. Err: {}".format(
                    str(e)))
Exemple #22
0
def get_db(filespec=None):
    """Return a connection to the database.
    If the db path does not exist, create it and initialize the db"""

    if not filespec:
        filespec = shotglass.get_site_config()['DATABASE_PATH']

    # This is probobly a good place to change the
    # filespec if you want to use a different database
    # for the current request.

    # test the path, if not found, create it
    initialize = shotglass.make_db_path(filespec)

    g.db = Database(filespec).connect()
    if initialize:
        initalize_all_tables(g.db)

    return g.db
Exemple #23
0
def get_db(filespec=None):
    """Return a connection to the database.

    If the db path does not exist, create it and initialize the db"""

    if not filespec:
        filespec = shotglass.get_site_config()['DATABASE_PATH']

    # This is probobly a good place to change the
    # filespec if you want to use a different database
    # for the current request.

    # test the path, if not found, try to create it
    if shotglass.make_db_path(filespec):
        g.db = Database(filespec).connect()
        initalize_all_tables(g.db)

        return g.db
    else:
        # was unable to create a path to the database
        raise IOError(
            "Unable to create path to () in app.get_db".format(filespec))
Exemple #24
0
def email_admin(subject=None, message=None):
    """
        Shortcut method to send a quick email to the admin
    """
    try:
        site_config = get_site_config()
        if not subject:
            subject = "An alert was sent from {}".format(
                site_config['SITE_NAME'])

        if not message:
            message = "An alert was sent from {} with no message...".format(
                site_config['SITE_NAME'])

        return send_message(
            None,
            subject=subject,
            body=message,
        )
    except Exception as e:
        mes = "Not able to send message to admin."
        printException(mes, err=e)
        return (False, mes)
Exemple #25
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
Exemple #26
0
import sys
sys.path.append('')  ##get import to look in the working dir

import datetime
from .rfeed.rfeed import *

has_local_date = False
author_name = "Unknown Jerome"
site_link = "http://www.example.com/rss"

## I Expect to use this from within a shotglass site
try:
    from shotglass2.shotglass import get_site_config
    from shotglass2.takeabeltof.date_utils import local_datetime_now
    has_local_date = True
    site_config = get_site_config()
    author_name = site_config['SITE_NAME']
    site_link = 'http://' + site_config['HOST_NAME']
except ImportError:
    print('no shotglass package')


class FeedMe():
    """Setup the channel parmeters for the news feed prior to adding items
        params:
            title | <str>: Title for the feed
            
            link | <str>: a link to the host ('http://example.com/'). Defaults to the 
            site_settings 'HOST_NAME' if available.
            
            description | <str>: (optional) description of the feed
Exemple #27
0
def _before():
    # Force all connections to be secure
    if app.config['REQUIRE_SSL'] and not request.is_secure:
        return redirect(request.url.replace("http://", "https://"))

    #ensure that nothing is served from the instance directory
    if 'instance' in request.url:
        return abort(404)

    # import pdb;pdb.set_trace()
    # print(app.url_map)
    session.permanent = True

    shotglass.get_site_config(app)
    shotglass.set_template_dirs(app)

    get_db()

    # Is the user signed in?
    g.user = None
    if 'user' in session:
        g.user = session['user']

    # g.menu_items should be a list of dicts
    #  with keys of 'title' & 'url' used to construct
    #  the non-table based items in the main menu
    g.menu_items = [
        {
            'title': 'Home',
            'url': url_for('www.home')
        },
        {
            'title': 'About',
            'url': url_for('www.about')
        },
        {
            'title': 'Contact Us',
            'url': url_for('www.contact')
        },
    ]

    # g.admin items are added to the navigation menu by default
    g.admin = Admin(g.db)  # This is where user access rules are stored

    # # Add a module to the menu
    g.admin.register(
        Event,
        url_for('event.display'),
        display_name='Events',
        top_level=True,
        minimum_rank_required=500,
    )
    g.admin.register(
        Location,
        url_for('location.display'),
        display_name='Locations',
        top_level=True,
        minimum_rank_required=500,
    )

    # This one will set up the view log item
    g.admin.register(
        User,
        url_for('tools.view_log'),
        display_name='View Log',
        top_level=True,
        minimum_rank_required=500,
    )

    shotglass.user_setup(
    )  # g.admin now holds access rules Users, Prefs and Roles
Exemple #28
0
def inject_site_config():
    # Add 'site_config' dict to template context
    return {'site_config': shotglass.get_site_config()}
Exemple #29
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)
Exemple #30
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,
    )