def createUser(): data = request.get_json(force=True) userName = unicodedata.normalize('NFKD', data['userName']).encode( 'ascii', 'ignore') userPassword = unicodedata.normalize('NFKD', data['userPassword']).encode( 'ascii', 'ignore') userEmail = unicodedata.normalize('NFKD', data['userEmail']).encode( 'ascii', 'ignore') try: if User.query.filter(User.email == userEmail).first() is None: user_datastore.create_user(first_name=userName, email=userEmail, password=userPassword) db.session.commit() return jsonify(success=True, data={ 'msg': 'Success!! created User!', }) else: return Response(json.dumps("User email is taken!")) except IntegrityError, e: db.session.rollback() return Response(e)
def create_test_models(): user_datastore.create_user(email='test', password=encrypt_password('test')) user_datastore.create_user(email='test2', password=encrypt_password('test2')) stuff = SomeStuff(data1=2, data2='toto', user_id=1) db.session.add(stuff) stuff = SomeStuff(data1=5, data2='titi', user_id=1) db.session.add(stuff) db.session.commit()
def _create_admin(self, survey, email, password): admin_role = self.get_user_role('admin') user = user_datastore.create_user(email=email, password=encrypt_password(password), survey_id=survey.id) user_datastore.add_role_to_user(user, admin_role) return user
def user_registration_confirm(token=None): req = UserCreateRequest.from_token(db.session, token) if not req: flash('User registration request not found.', 'danger') return redirect('/') user = User.from_email(db.session, req.email) if user: flash('User already exists.', 'danger') return redirect('/') now = datetime.datetime.now() if now > req.expiry: flash('User registration expired.', 'danger') return redirect('/') user = user_datastore.create_user(email=req.email, password=req.password, first_name=req.first_name, last_name=req.last_name) user.mobile_number = req.mobile_number user.address = req.address user.photo = req.photo user.photo_type = req.photo_type user.confirmed_at = now db.session.delete(req) db.session.commit() flash('User registered.', 'success') return redirect('/')
def createuser(): """Create an user""" username = click.prompt("Username", type=str) email = click.prompt("Email", type=str) password = click.prompt("Password", type=str, hide_input=True, confirmation_prompt=True) while True: role = click.prompt("Role [admin/user]", type=str) if role == "admin" or role == "user": break if click.confirm("Do you want to continue ?"): role = Role.query.filter(Role.name == role).first() if not role: raise click.UsageError("Roles not present in database") u = user_datastore.create_user(name=username, email=email, password=encrypt_password(password), roles=[role]) db.session.commit() if FSConfirmable.requires_confirmation(u): FSConfirmable.send_confirmation_instructions(u) print("Look at your emails for validation instructions.")
def add_user(db, email, first_name, last_name, password): """ adds a user """ user = user_datastore.create_user(email=email, first_name=first_name, last_name=last_name, password_hash=pwd_context.encrypt(password))#, roles=['user']) user_datastore.commit() return user
def seed_users(db): print("++ Seeding users") role_usr = Role() role_usr.name = "user" role_usr.description = "Simple user" role_adm = Role() role_adm.name = "admin" role_adm.description = "Admin user" db.session.add(role_usr) db.session.add(role_adm) user_datastore.create_user( email="*****@*****.**", password="******", name="toto", timezone="UTC", roles=[role_adm] ) db.session.commit() return
def add_user(email, password): with app.app_context(): user = User.from_email(db.session, email) if user: #logger.error("user already exists") #return user.password = encrypt_password(password) else: user = user_datastore.create_user( email=email, password=encrypt_password(password)) db.session.commit()
def create_admin(self, survey, email, password): admin_role = self.get_user_role('admin') user = user_datastore.create_user(email=email, password=encrypt_password(password), survey_id=survey.id) user_datastore.add_role_to_user(user, admin_role) try: db.session.commit() return user except IntegrityError: db.session.rollback()
def create_employees(N): if not Employee.query.first(): sls = Servicelocation.query.all() rs = Role.query.all() user_datastore.create_user(firstname='Admin', lastname='Admin', username='******', password=utils.encrypt_password('PASSWORD'), nightshift=True, active=True, employedsince=datetime.datetime(2001, 1, 1), servicelocationid=random.choice(sls).id, weeklyhours=25, vacationdays=100) for _ in range(N): sl = random.choice(sls) r = random.choice(rs) fn, ln, un, pw, ns, a, es, wh, vd = stringgenerator( 4), stringgenerator(5), stringgenerator( 3), 'PASSWORD', boolgenerator(), True, datetime.datetime( 2001, 1, 1), random.randint(30, 40), 25 u = user_datastore.create_user(firstname=fn, lastname=ln, username=un, password=utils.encrypt_password(pw), nightshift=ns, active=a, employedsince=es, servicelocationid=sl.id, weeklyhours=wh, vacationdays=vd) user_datastore.add_role_to_user(u, r) db.session.commit()
def create_participant(self, survey, email, password, uuid): participant_role = self.get_user_role('participant') user = user_datastore.create_user(email=email, password=encrypt_password(password), survey_id=survey.id, participant_uuid=uuid) user_datastore.add_role_to_user(user, participant_role) try: db.session.commit() return user except IntegrityError: db.session.rollback() return False
def createUser(): data = request.get_json(force=True) userName = unicodedata.normalize('NFKD', data['userName']).encode('ascii','ignore') userPassword = unicodedata.normalize('NFKD', data['userPassword']).encode('ascii','ignore') userEmail= unicodedata.normalize('NFKD', data['userEmail']).encode('ascii','ignore') try: if User.query.filter(User.email == userEmail).first() is None: user_datastore.create_user(first_name=userName,email=userEmail, password= userPassword) db.session.commit() return jsonify( success = True, data = { 'msg': 'Success!! created User!', } ) else: return Response(json.dumps("User email is taken!")) except IntegrityError, e: db.session.rollback() return Response(e)
def test_user_slugs(client, session): """Mass test user slugs""" role = Role.query.filter(Role.name == "user").first() ids = [] for count in range(50): suffix = "".join(random.choices(string.ascii_letters + string.digits, k=20)) username = f"test_slug_{count}_{suffix}" u = user_datastore.create_user( name=username, email=f"test_slug_{count}@localhost", password=hash_password(f"slug_{count}"), roles=[role] ) session.commit() assert u.id >= 0 ids.append(u.id) # Check for i in ids: user = User.query.filter(User.id == i).first() assert user.slug != "" assert user.slug is not None assert len(user.slug) >= 15
def create_researcher(self, survey, email, password, token): existing = ResearcherInviteToken.query.filter_by( token=token).one_or_none() if existing and validate_registration_token( token=token, salt=current_app.config['SECURITY_PASSWORD_SALT'], expiration=current_app.config['SIGNUP_EXPIRATION']): existing.usages += 1 researcher_role = self.get_user_role('researcher') user = user_datastore.create_user( email=email, password=encrypt_password(password), survey_id=survey.id) user_datastore.add_role_to_user(user, researcher_role) try: db.session.commit() return user except IntegrityError: db.session.rollback() return False
def create(): """ Create a user. """ current_app.config["SERVER_NAME"] = current_app.config[ "REEL2BITS_HOSTNAME"] username = click.prompt("Username", type=str) email = click.prompt("Email", type=str) password = click.prompt("Password", type=str, hide_input=True, confirmation_prompt=True) while True: role = click.prompt("Role [admin/user]", type=str) if role == "admin" or role == "user": break if click.confirm("Do you want to continue ?"): role = Role.query.filter(Role.name == role).first() if not role: raise click.UsageError("Roles not present in database") u = user_datastore.create_user(name=username, email=email, password=hash_password(password), roles=[role]) actor = create_actor(u) actor.user = u actor.user_id = u.id db.session.add(actor) db.session.commit() if FSConfirmable.requires_confirmation(u): with current_app.app_context(): FSConfirmable.send_confirmation_instructions(u) print("Look at your emails for validation instructions.")
def check_bronze_auth(flash_it=False): logger.info('current_user: {0}'.format(current_user)) if not hasattr(current_user, 'bronze_data') or not current_user.bronze_data: if bronze.authorized: userinfo = bronze_blueprint.session.get('UserInfo') if userinfo.ok: userinfo = userinfo.json() email = userinfo['email'] user = user_datastore.get_user(email) if not user: logger.info( 'user does not exist with email "{0}"'.format(email)) user = user_datastore.create_user(email=email) user_datastore.add_role_to_user(user, 'bronze') user_datastore.activate_user(user) if not add_update_bronze_data(user): if flash_it: flash('Unable to update user KYC data', 'danger') return False login_user(user, remember=True) db.session.commit() else: if flash_it: flash('Unable to update user email', 'danger') return False else: if flash_it: flash('Not logged in to Bronze', 'danger') return False else: if not add_update_bronze_data(current_user): if flash_it: flash('Unable to update user KYC data', 'danger') return False return True
def accounts(): """ Register an account The method is available to apps with a token obtained via the client credentials grant. It creates a user and account records, as well as an access token for the app that initiated the request. The method returns the access token, which the app should save for later. --- tags: - Accounts definitions: Token: type: object properties: access_token: type: string token_type: type: string scope: type: string created_at: type: integer responses: 200: description: Returns Token schema: $ref: '#/definitions/Token' """ if not current_app.config["REGISTRATION_ENABLED"]: abort(403) errors = {} # Get the bearer token bearer = None if "Authorization" in request.headers: b = request.headers.get("Authorization") b = b.strip().split(" ") if len(b) == 2: bearer = b[1] else: errors["bearer"] = ["API Bearer Authorization format issue"] else: current_app.logger.info( "/api/v1/accounts: no Authorization bearer given") if not request.json: abort(400) if "nickname" not in request.json: errors["nickname"] = ["nickname is missing"] if "email" not in request.json: errors["email"] = ["email is missing"] if "fullname" not in request.json: errors["fullname"] = ["fullname is missing"] if "password" not in request.json: errors["password"] = ["password is missing"] if "confirm" not in request.json: errors["confirm"] = ["password confirm is missing"] if "agreement" not in request.json: errors["agreement"] = ["agreement is missing"] if len(errors) > 0: return jsonify({"error": str(errors)}), 400 if forbidden_username(request.json["nickname"]): return jsonify( {"error": str({"nickname": ["this username cannot be used"]})}), 400 if request.json["password"] != request.json["confirm"]: return jsonify( {"error": str({"confirm": ["passwords doesn't match"]})}), 400 if "agreement" not in request.json: return jsonify({ "error": str({"agreement": ["you need to accept the terms and conditions"]}) }), 400 # Check if user already exists by local user username user = User.query.filter(User.name == request.json["username"]).first() if user: return jsonify({"error": str({"ap_id": ["has already been taken"]})}), 400 # Check if user already exists by old local user (Actors) user = Actor.query.filter( Actor.preferred_username == request.json["username"]).first() if user: return jsonify({"error": str({"ap_id": ["has already been taken"]})}), 400 # Check if user already exists by email user = User.query.filter(User.email == request.json["email"]).first() if user: return jsonify({"error": str({"email": ["has already been taken"]})}), 400 # Check username is valid # /^[a-zA-Z\d]+$/ if not username_is_legal.match(request.json["username"]): return jsonify({ "error": str({"ap_id": ["should contains only letters and numbers"]}) }), 400 # Proceed to register the user role = Role.query.filter(Role.name == "user").first() if not role: return jsonify({"error": "server error"}), 500 u = user_datastore.create_user( name=request.json["username"], email=request.json["email"], display_name=request.json["fullname"], password=hash_password(request.json["password"]), roles=[role], ) actor = create_actor(u) actor.user = u actor.user_id = u.id if "bio" in request.json: actor.summary = request.json["bio"] db.session.add(actor) db.session.commit() if FSConfirmable.requires_confirmation(u): FSConfirmable.send_confirmation_instructions(u) # get the matching item from the given bearer bearer_item = OAuth2Token.query.filter( OAuth2Token.access_token == bearer).first() if not bearer_item: abort(400) client_item = OAuth2Client.query.filter( OAuth2Client.client_id == bearer_item.client_id).first() if not client_item: abort(400) # https://github.com/lepture/authlib/blob/master/authlib/oauth2/rfc6749/grants/base.py#L51 token = authorization.generate_token(client_item.client_id, "client_credentials", user=u, scope=client_item.scope, expires_in=None) tok = OAuth2Token() tok.user_id = u.id tok.client_id = client_item.client_id # the frontend should request an app every time it doesn't have one in local storage # and this app should allow delivering a somewhat non usuable Token # token which gets sent to this endpoint and gets used to get back the right client_id # to associate in the database... tok.token_type = token["token_type"] tok.access_token = token["access_token"] tok.refresh_token = None tok.scope = token["scope"] tok.revoked = False tok.expires_in = token["expires_in"] db.session.add(tok) db.session.commit() return jsonify({**token, "created_at": tok.issued_at}), 200
def setUp(self): db.create_all() user = user_datastore.create_user(email="*****@*****.**", first_name="first", last_name="last", password_hash=pwd_context.encrypt("password")) user_datastore.commit()
def testUserExists(self): user = user_datastore.create_user(email="*****@*****.**", first_name="first", last_name="last", password_hash="password_hash") user_datastore.commit() self.assertTrue(helpers.user_exists("*****@*****.**")) self.assertFalse(helpers.user_exists("*****@*****.**"))