def make_guinea_pig(): """Create an additional dummy user when more than one user is needed. Returns: User: A basic user with a confirmed account but no privileges. """ cavy = User() # Cavy is another name for guinea pig. cavy.email = '*****@*****.**' cavy.name = 'Mister Squeals' cavy.set_password('food') cavy.confirmed = True return cavy
def test_reset_password_wrong_email(self, app, db): """reset_password flashes and error if wrong user's email provided.""" user = make_dummy_user() user.confirmed = True db.session.add(user) db.session.commit() token = user.generate_password_reset_token() user2 = User() user2.name = 'Ford Prefect' user2.set_password('knowwhereyourtowelis') user2.email = '*****@*****.**' user2.confirmed = True db.session.add(user2) db.session.commit() data = dict( email=user2.email, password1='heartofgold', password2='heartofgold') with app.test_client() as tc: rv = tc.post(url_for('auth.reset_password', token=token), data=data, follow_redirects=True) assert 'Error: Given token is invalid' in str(rv.data)
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.')