def test_load_users(self, db): """load_users loads all users in database into select_user.choices.""" user1 = User() user1.name = 'Bob' user1.email = '*****@*****.**' user2 = User() user2.name = 'Eris' user2.email = '*****@*****.**' db.session.add(user1) db.session.add(user2) form = SelectUserForm() form.load_users() print(form.select_user.choices) assert (user1.id, user1.name) in form.select_user.choices assert (user2.id, user2.name) in form.select_user.choices
def post(self): form = self.form openid = self.openid if form.validate(): encpass = enc_login_passwd(form.password.data) U = User(username=form.username.data, password=encpass, language=self.language) user_info = self.get_user_info U.nickname = user_info.get('nickname', U.username) U.email = form.email.data self.db.add(U) self.db.commit() U.init_account(self.db) U.last_login = datetime.datetime.now() openid.user_id = U.id self.db.commit() self.save_session(U.id) self.db.delete(self.K) self.db.commit() return self.redirect_next('/account') self.render()
def post(self): form = self.form openid = self.openid if form.validate(): encpass = enc_login_passwd(form.password.data) U = User( username = form.username.data, password = encpass, language = self.language ) user_info = self.get_user_info U.nickname = user_info.get('nickname', U.username) U.email = form.email.data self.db.add( U ) self.db.commit() U.init_account(self.db) U.last_login = datetime.datetime.now() openid.user_id = U.id self.db.commit() self.save_session(U.id) self.db.delete(self.K) self.db.commit() return self.redirect_next('/account') self.render()
def test_confirm_new_email_works_with_generated_token(self, app): """confirm_new_mail should return True & set email w/ valid token.""" user = User() user.id = 42 user.email = '*****@*****.**' new_email = '*****@*****.**' token = user.generate_new_email_token(new_email) assert user.confirm_new_email(token) assert new_email == user.email
def login(): """Simulate the standard login flow.""" user = User.find_by_email('*****@*****.**') if user is None: user = User('Dave') user.email = '*****@*****.**' user.save() login_user(user) return redirect(url_for('main.home'))
def create_dummy_user( email='*****@*****.**', name='AzureDiamond', password='******'): user = User() user.name = name user.set_password(password) user.email = email return user
def make_dummy_user(): """Create a basic dummy for testing. Returns: User: A basic user with no confirmed account or privileges. """ user = User() user.name = 'AzureDiamond' user.set_password('hunter2') user.email = '*****@*****.**' return user
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 _create_superuser(): from app.auth.models import User from app import db user = User() user.fname = input("Enter First name: ") user.lname = input("Enter Last name: ") user.username = input("Enter Username: "******"Enter Email: ") user.set_password(input("Enter password: "******"SuperUser Created!")
def admin(): logged_user = google_users.get_current_user() form = AdminForm(request.form) if form.validate_on_submit(): user = User() user.email = form.email.data user.name = form.name.data user.password = generate_password_hash(form.password.data) user.put() return redirect(url_for("auth.admin")) users = User.query().order(-User.created_at) return render_template( "auth/admin.html", form=form, users=users, logged_user=logged_user, google_users=google_users )
def admin(): logged_user = google_users.get_current_user() form = AdminForm(request.form) if form.validate_on_submit(): user = User() user.email = form.email.data user.name = form.name.data user.password = generate_password_hash(form.password.data) user.put() return redirect(url_for('auth.admin')) users = User.query().order(-User.created_at) return render_template("auth/admin.html", form=form, users=users, logged_user=logged_user, google_users=google_users)
def signup_user(): try: username = request.form['username'] email = request.form['email'] password = request.form['password'] u = User.query.filter( or_(User.username == username, User.email == email)).first() if u: return jsonify(status='error', info=u'已经存在该用户!') else: u = User() u.username = username u.email = email u.set_password(password) db.session.add(u) db.session.commit() return jsonify(status='success', info=u'恭喜你,注册成功了!') except Exception as e: current_app.logger.error(e) return redirect(url_for('ask.index'))
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 handle_authorize(remote, token, user_info): current_app.logger.info("remote: {}".format(remote)) current_app.logger.info("token: {!r}".format(token)) current_app.logger.info("user_info: {!r}".format(user_info)) if user_info: # Note: Here's where to do team membership or whitelist/blacklist tests user = User.find_by_email(user_info['email']) if user is None: user = User(user_info['preferred_username']) user.email = user_info['email'] # Note: in real life we wouldn't discard the rest user.save() login_user(user) else: # Authorization failed. # In real code, we'd provided feedback (e.g., flash a message) pass return redirect(url_for('main.home'))
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.')