Ejemplo n.º 1
0
 def test_grant_permission(self, app):
     """grant_permission should set a permission and not unset it."""
     user = User()
     user.permissions = 0
     perm1 = 0b1
     perm2 = 0b10
     perm3 = 0b100
     user.grant_permission(perm1)
     assert user.permissions == 0b1
     user.grant_permission(perm3)
     assert user.permissions == 0b101
     user.grant_permission(perm2)
     assert user.permissions == 0b111
     # Already set permissions should remain unchanged.
     user.grant_permission(perm1)
     assert user.permissions == 0b111
     user.grant_permission(perm2)
     assert user.permissions == 0b111
     user.grant_permission(perm3)
     assert user.permissions == 0b111
Ejemplo n.º 2
0
def resetdb(fast=False):
    """Erase db and/or create a new one with an admin account."""
    from pycountry import countries
    from app.auth import models as auth_models
    from app.seeds import models as seeds_models
    from app.shop import models as shop_models
    from app.shop.models import Country, State
    resp = input(
        'WARNNG: This will erase existing database and create a new one! '
        'Proceed anyway? y/N: '
    )
    if 'y' in resp.lower():
        print('Erasing existing database if present...')
        db.session.rollback()
        db.session.remove()
        if db.engine.dialect.name == 'postgresql':
            db.engine.execute('drop schema if exists public cascade')
            db.engine.execute('create schema public')
        db.drop_all()
        print('Configuring mappers...')
        db.configure_mappers()
        print('Creating new database...')
        db.create_all()
        db.session.commit()
        admin = User()
        db.session.add(admin)
        print('Populating countries table...')
        db.session.add_all(
            sorted(
                Country.generate_from_alpha3s(c.alpha3 for c in countries),
                key=lambda x: x.name
            )
        )
        db.session.flush()
        print('Setting safe to ship countries...')
        stsfile = Path(
            app.config['JSON_FOLDER'], 
            'safe_to_ship_countries.json'
        )
        try:
            with stsfile.open('r', encoding='utf-8') as ifile:
                sts = json.loads(ifile.read())
                for c in sts:
                    if isinstance(c, str):
                        alpha3 = c
                        thresh = None
                    else:
                        alpha3 = c[0]
                        thresh = c[1]
                    country = Country.get(alpha3=alpha3)
                    if thresh:
                        country.at_own_risk_threshold = thresh
                    country.safe_to_ship = True
                db.session.flush()
        except FileNotFoundError:
            db.session.rollback()
            raise FileNotFoundError(
                'Could not find file "{}". This file should be a JSON list '
                'containing alpha3 country codes for countries we can safely '
                'ship to, including ones that become at own risk above a '
                'certain cost total, which should be 2 value lists formatted '
                '["<alpha3", <int or decimal cost above which is at own '
                'risk>], e.g.: [... , "JPN", "NLD", ["NOR", 50], "PRI", '
                '"ESP", ...]'.format(stsfile.absolute())
            )
        print('Setting noship countries...')
        ncfile = Path(app.config['JSON_FOLDER'], 'noship_countries.json')
        try:
            with ncfile.open('r', encoding='utf-8') as ifile:
                a3s = json.loads(ifile.read())
                for alpha3 in a3s:
                    country = Country.get(alpha3=alpha3)
                    country.noship = True
                db.session.flush()
        except FileNotFoundError:
            db.session.rollback()
            raise FileNotFoundError(
                'Could not find file "{}"! This file should be a JSON list '
                'containing alpha3 country codes for countries we cannot '
                'ship to. e.g.: ["BGD", "BRA", "CHN", ... ]'
                .format(ncfile.absolute())
            )
        print('Populating States/Provinces/etc...')
        try:
            sfile = Path(app.config['JSON_FOLDER'], 'states.json')
            with sfile.open('r', encoding='utf-8') as ifile:
                d = json.loads(ifile.read())
                db.session.add_all(
                    State.generate_from_dict(d)
                )
                db.session.flush()
        except FileNotFoundError:
            db.session.rollback()
            raise FileNotFoundError(
                'Could not find file "{}"! If it does not exist, it should '
                'be created and contain a JSON object formatted: { "<country '
                'alpha3 code>": { "<state abbreviation>": "<state name>", '
                '... }, ... } e.g. {"USA": {"AL": "Alabama", "AK": '
                '"Alaska", ... }, "CAN": {"AB": "Alberta", "BC": '
                '"British Columbia", ... }, ... }'.format(sfile.absolute())
            )
        print('Setting California sales tax...')
        rfile = Path(app.config['JSON_FOLDER'], 'rates.json')
        try:
            with rfile.open('r', encoding='utf-8') as ifile:
                rates = json.loads(ifile.read())
            ca = State.get(
                country=Country.get(alpha3='USA'), abbreviation='CA'
            )
            ca.tax = Decimal(str(rates['sales tax']['USA']['CA']))
            db.session.flush()
        except FileNotFoundError:
            raise FileNotFoundError(
                'Could not find file "{}"! It should contain a JSON object '
                'including: { "sales tax": {"USA": {"CA":<tax rate>i, ... }, '
                '... }, ... }'.format(rfile.absolute())
            )
        print('Creating first administrator account...')
        if fast:
            admin.name = 'admin'
            admin.email = 'admin@localhost'
            admin.set_password('sgsadmin')  # Very secure!
        else:
            admin.name = input('Enter name for admin account: ')
            admin.email = input('Enter email address for admin account: ')
            while True:
                pw = getpass('Enter new password: '******'Confirm new password: '******'Passwords do not match! Please try again.')
                else:
                    break
            admin.set_password(pw)
        admin.grant_permission(Permission.MANAGE_SEEDS)
        admin.grant_permission(Permission.MANAGE_USERS)
        admin.confirmed = True
        print('Admin account "{}" created!'.format(admin.name))
        db.session.commit()
        print('Database was successfully created!')
    else:
        print('Aborted.')