def google_logged_in(blueprint, token): if not token: flash("Failed to log in with {name}".format(name=blueprint.name)) return # figure out who the user is resp = blueprint.session.get("/plus/v1/people/me") # app.logger.debug(resp.json()) # TODO Extract the position of the account email if resp.ok: email = resp.json()['emails'][0]['value'] avatar = resp.json()['image']['url'] existing_user = user_datastore.find_user(email=email) if not existing_user: # create a user existing_user = user_datastore.create_user(username=email, email=email, password=str( uuid.uuid4())) existing_user.has_auto_generated_password = True existing_user.avatar = avatar user_datastore.commit() login_user(existing_user) flash("Successfully signed in with Google", 'success') else: msg = "Failed to fetch user info from {name}".format( name=blueprint.name) flash(msg, category="error")
def get_or_create_user(email, password, role, **kwargs): u = user_datastore.get_user(email) if not u: u = user_datastore.create_user(email=email, password=encrypt_password(password), **kwargs) user_datastore.add_role_to_user(u, role) db.session.commit() return u
def post(self): parser = reqparse.RequestParser() parser.add_argument('email') parser.add_argument('password') args = parser.parse_args() return user_datastore.create_user(email=args["email"], password=hash_password(args["password"]))
def register(): error = None form = MyRegisterForm() if form.validate_on_submit(): username = form.username.data if User.query.filter_by(username=username).first() is not None: error = 'This username is already registered.' elif form.password.data != form.password2.data: error = 'Entered passwords do not match' else: user_datastore.create_user(username=username, email=form.email.data, password=hash_password(form.password.data)) db.session.commit() user = User.query.filter_by(username=username).first() login_user(user, remember=True) return redirect('index') return render_template('signup.html', error=error, form=form)
def register(): data, errors = register_schema.load(request.get_json()) if errors: return jsonify({'errors': errors}), 422 _user = User.findFirst( or_(User.username == data.username, User.email == data.email)) if _user is not None: return jsonify({ 'errors': 'That email address or username is already in the database.' }), 400 else: password_encryped = encrypt_password(data.password) user_datastore.create_user(username=data.username, email=data.email, password=password_encryped) db.session.commit() token = generate_confirmation_token(data.email) confirmation_url = request.url_root[:-1] + url_for('confirmation', token=token) send_confirmation_email(data.email, confirmation_url) return jsonify({'data': 'success'}), 201
def create(self, user_data): deserialized_data = self.user_serializer.load(user_data) with db_wrapper.database.atomic(): role = self.role_manager.find(deserialized_data['role_id']) user = self.manager.get_last_record() fs_uniquifier = 1 if user is None else user.id + 1 deserialized_data.update({ 'created_by': current_user.id, 'roles': [role], 'fs_uniquifier': fs_uniquifier }) user = user_datastore.create_user(**deserialized_data) return user
def create_user(): content = request.get_json(silent=True) validate(instance=content, schema=user_schema) user = user_datastore.create_user( username=content["name"], email=content["email"], password=utils.hash_password(content["password"]), roles=(["admin"] if content["role"] == "admin" else []), access_stations_all=( content['access']['stations']['unlimited'] == True), access_variables_all=( content['access']['variables']['unlimited'] == True), access_variables_standard=( content['access']['variables']['standard'] == True)) # Variable and station access config. user.access_stations_all = ( content['access']['stations']['unlimited'] == True) user.access_variables_all = ( content['access']['variables']['unlimited'] == True) user.access_variables_standard = ( content['access']['variables']['standard'] == True) if content['access']['variables']['unlimited'] == False and content[ 'access']['variables']['standard'] == False: user.access_variable_specific = list( map(lambda x: AccessVariable(variable_id=int(x)), content['access']['variables']['specific'])) else: user.access_variable_specific = [] if content['access']['stations']['unlimited'] == False: user.access_stations_specific = list( map(lambda x: AccessStation(station_id=x), content['access']['stations']['specific'])) else: user.access_stations_specific = [] db.commit() return jsonify({"status": "success"})
def facebook_logged_in(blueprint, token): if not token: flash("Failed to log in with {name}".format(name=blueprint.name)) return # figure out who the user is resp = blueprint.session.get("/me?fields=id,name,email,picture") avatar = resp.json()['picture']['data']['url'] app.logger.debug(resp.json()) if resp.ok: email = resp.json()['email'] existing_user = user_datastore.find_user(email=email) if not existing_user: # create a user existing_user = user_datastore.create_user(username=email, email=email, password=str(uuid.uuid4())) existing_user.has_auto_generated_password = True existing_user.avatar = avatar user_datastore.commit() login_user(existing_user) flash("Successfully signed in with Facebook", 'success') else: msg = "Failed to fetch user info from {name}".format(name=blueprint.name) flash(msg, category="error")
def register(provider_id=None): if current_user.is_authenticated: return redirect(request.referrer or '/') form = RegisterForm() if form.validate_on_submit(): user = user_datastore.create_user(email=form.email.data, password=encrypt_password(form.password.data)) user_datastore.commit() if login_user(user): user_datastore.commit() flash('Account created successfully', 'info') return redirect(url_for('users.profile')) return render_template('thanks.html', user=user) login_failed = int(request.args.get('login_failed', 0)) return render_template('users/register.html', form=form, login_failed=login_failed )
def register(): if request.method == 'POST': try: # Get sent data data, message, status, response_code = request.form.to_dict( ), '', 0, 202 # no data sent if not data: return make_response( jsonify({ 'message': 'Data is missing', 'status': -1 })), response_code fullname, phone_number, id_number = data['official_names'], data[ 'phone_number'], data['id_number'] residency, gender = data.get( 'residency', 'Nairobi'), data.get('gender', '') or '' role, relative, caregiver = data['role'], data.get( 'relative', ''), data.get('caregiver', '') # Ensure the key details are not missing if not role: return make_response( jsonify({ 'message': 'Role is missing', 'status': 1 })), response_code if not fullname: return make_response( jsonify({ 'message': 'Official names are missing', 'status': 1 })), response_code if not phone_number: return make_response( jsonify({ 'message': 'Phone number is missing', 'status': 1 })), response_code if not id_number: return make_response( jsonify({ 'message': "ID number is missing", 'status': 1 })), response_code # Confirm role given is valid if user_datastore.find_role(role=role) is None: return make_response( jsonify({ 'message': 'Non-existent role', 'status': -3 })), 401 if role == 'patient': if not relative: return jsonify({ 'message': 'At least 1 relative required', 'status': 1 }), response_code if not User.query.filter(User.user_id == relative).first(): return jsonify( {'message': 'Relative provided not registered'}), response_code if not caregiver: return jsonify({ 'message': 'At least 1 caregiver required', 'status': 1 }), response_code if not User.query.filter(User.user_id == caregiver).first(): return jsonify( {'message': 'Caregiver provided not registered'}), response_code # Check format of phone number message, status = validate_phone_number(phone_number) if status: return make_response(jsonify({ 'message': message, 'status': 7 })), 202 parts = [x.strip() for x in message.split('.')] phone_number = parts[1].split(':')[-1].strip() # check if user is already registered if User.query.filter_by(phoneNumber=phone_number).first(): return make_response( jsonify({ 'message': 'Phone Number already registered', 'status': 5 })), 202 # receive profile picture message, status = upload_file(request.files, fullname, file_type='image', tag="profile_picture") if status or type(message) == str: return jsonify({'message': message, "status": -4}), 401 else: profile_picture = message['http_url'] if role == 'caregiver' or role == 'admin': # receive ID picture message, status = upload_file(request.files, fullname, file_type='image', tag="identification_picture") if status or type(message) == str: return jsonify({'message': message, "status": -4}), 401 else: identification_picture = message['http_url'] else: identification_picture = '' # Create user with given role user_id = User.generate_user_id(role) try: user_datastore.create_user( user_id=user_id, fullname=fullname, phoneNumber=phone_number, profile_picture=profile_picture, identification_number=id_number, roles=[role], identification_picture=identification_picture, gender=gender, residence=residency, ) if role == 'patient': db.session.add( PatientRelative(relative=relative, patient=user_id, tag='primary')) db.session.add( PatientCaregiver(caregiver=caregiver, patient=user_id, tag='primary')) db.session.commit() except Exception as err: print(err) db.session.rollback() system_logging(msg=err, exception=True) return make_response( jsonify({ 'message': "Error saving user", 'status': 9 })), 202 user = User.query.filter(User.phoneNumber == phone_number).first() user.launch_task('send_account_confirmation_sms', 'Sending account confirmation OTP SMS', phone_number) return make_response( jsonify({ 'message': 'Successful user addition', 'status': status })), 200 except Exception as err: print(err) system_logging(err, exception=True) message = "Error during user registration" return make_response(jsonify({ 'message': message, 'status': -2 })), 401
def create_test_data(): role_user = user_datastore.create_role(**USER_ROLE._asdict()) role_gs_admin = user_datastore.create_role(**SERVER_ADMIN_ROLE._asdict()) role_aga_admin = user_datastore.create_role(**RATINGS_ADMIN_ROLE._asdict()) u = user_datastore.create_user(email='*****@*****.**', password=encrypt_password('usgo'), id=1) user_datastore.add_role_to_user(u, role_aga_admin) kgs_admin = user_datastore.create_user(email='*****@*****.**', password=encrypt_password('kgs'), id=2) user_datastore.add_role_to_user(kgs_admin, role_gs_admin) u = user_datastore.create_user(email='*****@*****.**', aga_id=10, password=encrypt_password('foo'), id=3) db.session.add( Player(id=1, name="FooPlayerKGS", server_id=1, user_id=3, token="secret_foo_KGS")) db.session.add( Player(id=4, name="FooPlayerIGS", server_id=2, user_id=3, token="secret_foo_IGS")) user_datastore.add_role_to_user(u, role_user) u = user_datastore.create_user(email='*****@*****.**', aga_id=20, password=encrypt_password('bar'), id=4) db.session.add( Player(id=2, name="BarPlayerKGS", server_id=1, user_id=4, token="secret_bar_KGS")) db.session.add( Player(id=5, name="BarPlayerIGS", server_id=2, user_id=4, token="secret_bar_IGS")) user_datastore.add_role_to_user(u, role_user) u = user_datastore.create_user(email='*****@*****.**', aga_id=30, password=encrypt_password('baz'), id=5) db.session.add( Player(id=3, name="BazPlayerKGS", server_id=1, user_id=5, token="secret_baz_KGS")) db.session.add( Player(id=6, name="BazPlayerIGS", server_id=2, user_id=5, token="secret_baz_IGS")) user_datastore.add_role_to_user(u, role_user) gs = GoServer(id=1, name='KGS', url='http://gokgs.com', token='secret_kgs') gs.admins.append(kgs_admin) db.session.add(gs) db.session.add( GoServer(id=2, name='IGS', url='http://pandanet.com', token='secret_igs')) basedir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(basedir, 'tests/testsgf.sgf')) as sgf_file: sgf_data = "\n".join(sgf_file.readlines()).encode() db.session.add( Game(server_id=1, white_id=1, black_id=2, rated=True, result="B+0.5", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)))) db.session.add( Game(server_id=1, white_id=1, black_id=2, rated=True, result="W+39.5", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)))) db.session.add( Game(server_id=2, white_id=5, black_id=4, rated=True, result="W+Resign", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)))) db.session.add( Game(server_id=2, white_id=5, black_id=4, rated=True, result="W+Resign", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)))) db.session.add( Game(server_id=2, white_id=6, black_id=5, rated=True, result="W+Resign", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)))) db.session.add( Game(server_id=1, white_id=1, black_id=2, rated=True, result="B+0.5", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)))) db.session.add( Game(server_id=1, white_id=3, black_id=2, rated=True, result="W+39.5", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)))) db.session.add( Game(server_id=2, white_id=5, black_id=6, rated=True, result="W+Resign", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)))) db.session.commit() try: # needed to reset the postgresql autoincrement counter db.engine.execute( "SELECT setval('myuser_id_seq', (SELECT MAX(id) FROM myuser))") db.engine.execute( "SELECT setval('player_id_seq', (SELECT MAX(id) FROM player))") except: pass
def create_test_data(): role_user = user_datastore.create_role(**USER_ROLE._asdict()) role_gs_admin = user_datastore.create_role(**SERVER_ADMIN_ROLE._asdict()) role_aga_admin = user_datastore.create_role(**RATINGS_ADMIN_ROLE._asdict()) u = user_datastore.create_user(email="*****@*****.**", password=encrypt_password("usgo"), id=1) user_datastore.add_role_to_user(u, role_aga_admin) kgs_admin = user_datastore.create_user(email="*****@*****.**", password=encrypt_password("kgs"), id=2) user_datastore.add_role_to_user(kgs_admin, role_gs_admin) u = user_datastore.create_user(email="*****@*****.**", aga_id=10, password=encrypt_password("foo"), id=3) db.session.add(Player(id=1, name="FooPlayerKGS", server_id=1, user_id=3, token="secret_foo_KGS")) db.session.add(Player(id=4, name="FooPlayerIGS", server_id=2, user_id=3, token="secret_foo_IGS")) user_datastore.add_role_to_user(u, role_user) u = user_datastore.create_user(email="*****@*****.**", aga_id=20, password=encrypt_password("bar"), id=4) db.session.add(Player(id=2, name="BarPlayerKGS", server_id=1, user_id=4, token="secret_bar_KGS")) db.session.add(Player(id=5, name="BarPlayerIGS", server_id=2, user_id=4, token="secret_bar_IGS")) user_datastore.add_role_to_user(u, role_user) u = user_datastore.create_user(email="*****@*****.**", aga_id=30, password=encrypt_password("baz"), id=5) db.session.add(Player(id=3, name="BazPlayerKGS", server_id=1, user_id=5, token="secret_baz_KGS")) db.session.add(Player(id=6, name="BazPlayerIGS", server_id=2, user_id=5, token="secret_baz_IGS")) user_datastore.add_role_to_user(u, role_user) gs = GoServer(id=1, name="KGS", url="http://gokgs.com", token="secret_kgs") gs.admins.append(kgs_admin) db.session.add(gs) db.session.add(GoServer(id=2, name="IGS", url="http://pandanet.com", token="secret_igs")) basedir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(basedir, "tests/testsgf.sgf")) as sgf_file: sgf_data = "\n".join(sgf_file.readlines()).encode() db.session.add( Game( server_id=1, white_id=1, black_id=2, rated=True, result="B+0.5", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)), ) ) db.session.add( Game( server_id=1, white_id=1, black_id=2, rated=True, result="W+39.5", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)), ) ) db.session.add( Game( server_id=2, white_id=5, black_id=4, rated=True, result="W+Resign", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)), ) ) db.session.add( Game( server_id=2, white_id=5, black_id=4, rated=True, result="W+Resign", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)), ) ) db.session.add( Game( server_id=2, white_id=6, black_id=5, rated=True, result="W+Resign", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)), ) ) db.session.add( Game( server_id=1, white_id=1, black_id=2, rated=True, result="B+0.5", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)), ) ) db.session.add( Game( server_id=1, white_id=3, black_id=2, rated=True, result="W+39.5", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)), ) ) db.session.add( Game( server_id=2, white_id=5, black_id=6, rated=True, result="W+Resign", game_record=sgf_data, date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0, 1000000)), ) ) db.session.commit() try: # needed to reset the postgresql autoincrement counter db.engine.execute("SELECT setval('myuser_id_seq', (SELECT MAX(id) FROM myuser))") db.engine.execute("SELECT setval('player_id_seq', (SELECT MAX(id) FROM player))") except: pass