async def update_identity(uuid: UUID, body: schemas.IdentityUpdate): identity = await Identity.get(uuid=uuid ).prefetch_related("roles__permissions") if body.is_active is not None: identity.is_active = body.is_active if body.credentials is not None: old_ids = set(await identity.credentials.all().values_list("id", flat=True)) new_ids = set() for identifier_pair in body.credentials: c, _ = await Credential.get_or_create( identifier=identifier_pair.identifier, identifier_type=identifier_pair.identifier_type, identity=identity, ) if identifier_pair.password: pwd = await c.passwords.all().first() if not pwd: pwd = Password.from_raw(c, identifier_pair.password) pwd.set_password(identifier_pair.password) await pwd.save() new_ids.add(c.id) await Credential.filter(id__in=(old_ids - new_ids)).delete() if body.roles is not None: old_roles = set(await identity.roles.all()) new_roles = set(await Role.filter(code__in=[r.code for r in body.roles]).all()) await identity.roles.remove(*(old_roles - new_roles)) await identity.roles.add(*(new_roles - old_roles)) await identity.save() return await schemas.IdentityDetail.from_object(identity)
async def test_pwd(): pwd = Password.from_raw(None, "1234", permanent=True) assert not pwd.is_expired pwd.expires_at = datetime.utcnow() - timedelta(days=1) assert pwd.is_expired assert pwd.validate_password("1234") assert not pwd.validate_password("12345")
async def create_identity(body: schemas.IdentityCreate): roles = await Role.filter(code__in=body.role_codes).all() if not len(roles) == len(body.role_codes): diff = set(body.role_codes) - {r.name for r in roles} raise EvaException(message=f"specified roles {diff} not found") new_identity = Identity(is_active=body.is_active) await new_identity.save() await new_identity.roles.add(*roles) credentials = [] for identifier_pair in body.credentials: c = Credential( identifier=identifier_pair.identifier, identifier_type=identifier_pair.identifier_type, identity=new_identity, ) await c.save() pwd = Password.from_raw(c, identifier_pair.password) await pwd.save() credentials.append(c) await new_identity.fetch_related("roles__permissions") return await schemas.IdentityDetail.from_object(new_identity)