diff --git a/services/celest_cloud_auth/CHANGELOG.md b/services/celest_cloud_auth/CHANGELOG.md index 90de2c721..4b449b532 100644 --- a/services/celest_cloud_auth/CHANGELOG.md +++ b/services/celest_cloud_auth/CHANGELOG.md @@ -1,3 +1,7 @@ +## 0.3.2 + +- fix: Properly set/check session duration + ## 0.3.1 - fix: Allow dashes in routes diff --git a/services/celest_cloud_auth/drift_schema/auth_database/drift_schema_v5.json b/services/celest_cloud_auth/drift_schema/auth_database/drift_schema_v5.json new file mode 100644 index 000000000..0d0018320 --- /dev/null +++ b/services/celest_cloud_auth/drift_schema/auth_database/drift_schema_v5.json @@ -0,0 +1 @@ +{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"cloud_auth_users","was_declared_in_moor":true,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]},{"name":"given_name","getter_name":"givenName","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"family_name","getter_name":"familyName","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"time_zone","getter_name":"timeZone","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"language_code","getter_name":"languageCode","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"create_time","getter_name":"createTime","moor_type":"double","nullable":false,"customConstraints":"NOT NULL DEFAULT (unixepoch('now', 'subsec'))","default_dart":"const CustomExpression('unixepoch(\\'now\\', \\'subsec\\')')","default_client_dart":null,"dsl_features":[]},{"name":"update_time","getter_name":"updateTime","moor_type":"double","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":1,"references":[],"type":"table","data":{"name":"cedar_types","was_declared_in_moor":true,"columns":[{"name":"fqn","getter_name":"fqn","moor_type":"string","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[1],"type":"table","data":{"name":"cedar_entities","was_declared_in_moor":true,"columns":[{"name":"entity_type","getter_name":"entityType","moor_type":"string","nullable":false,"customConstraints":"NOT NULL REFERENCES cedar_types(fqn)","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"entity_id","getter_name":"entityId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"attribute_json","getter_name":"attributeJson","moor_type":"string","nullable":false,"customConstraints":"NOT NULL DEFAULT '{}'","default_dart":"const CustomExpression('\\'{}\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const CedarAttributesConverter()","dart_type_name":"Map"}},{"name":"entity_json","getter_name":"entityJson","moor_type":"string","nullable":false,"customConstraints":"NOT NULL GENERATED ALWAYS AS (json_object('type', entity_type, 'id', entity_id)) VIRTUAL","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"],"type_converter":{"dart_expr":"const CedarEntityUidConverter()","dart_type_name":"EntityUid"}}],"is_virtual":false,"without_rowid":true,"constraints":["CONSTRAINT cedar_entities_pk PRIMARY KEY(entity_type, entity_id)ON CONFLICT IGNORE"],"explicit_pk":["entity_type","entity_id"]}},{"id":3,"references":[0,2],"type":"trigger","data":{"on":0,"references_in_body":[0,2],"name":"cloud_auth_users_create_trg","sql":"CREATE TRIGGER IF NOT EXISTS cloud_auth_users_create_trg\nBEFORE INSERT ON cloud_auth_users\nBEGIN\n INSERT INTO cedar_entities(entity_type, entity_id)\n VALUES ('Celest::User', NEW.user_id);\nEND;"}},{"id":4,"references":[2],"type":"table","data":{"name":"cedar_relationships","was_declared_in_moor":true,"columns":[{"name":"entity_type","getter_name":"entityType","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"entity_id","getter_name":"entityId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"entity_json","getter_name":"entityJson","moor_type":"string","nullable":false,"customConstraints":"NOT NULL GENERATED ALWAYS AS (json_object('type', entity_type, 'id', entity_id)) VIRTUAL","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"],"type_converter":{"dart_expr":"const CedarEntityUidConverter()","dart_type_name":"EntityUid"}},{"name":"parent_type","getter_name":"parentType","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"parent_id","getter_name":"parentId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"parent_json","getter_name":"parentJson","moor_type":"string","nullable":false,"customConstraints":"NOT NULL GENERATED ALWAYS AS (json_object('type', parent_type, 'id', parent_id)) VIRTUAL","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"],"type_converter":{"dart_expr":"const CedarEntityUidConverter()","dart_type_name":"EntityUid"}}],"is_virtual":false,"without_rowid":true,"constraints":["CONSTRAINT cedar_relationships_pk PRIMARY KEY(entity_type, entity_id, parent_type, parent_id)ON CONFLICT IGNORE","CONSTRAINT cedar_relationships_fk_entity FOREIGN KEY(entity_type, entity_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE","CONSTRAINT cedar_relationships_fk_parent FOREIGN KEY(parent_type, parent_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE"],"explicit_pk":["entity_type","entity_id","parent_type","parent_id"]}},{"id":5,"references":[0,4,2],"type":"trigger","data":{"on":0,"references_in_body":[0,4,2],"name":"cloud_auth_users_delete_trg","sql":"CREATE TRIGGER IF NOT EXISTS cloud_auth_users_delete_trg\nAFTER DELETE ON cloud_auth_users\nBEGIN\n DELETE FROM cedar_relationships\n WHERE \n (entity_type = 'Celest::User' AND entity_id = OLD.user_id)\n OR (parent_type = 'Celest::User' AND parent_id = OLD.user_id);\n DELETE FROM cedar_entities\n WHERE\n entity_id = OLD.user_id\n AND entity_type = 'Celest::User';\nEND;"}},{"id":6,"references":[0],"type":"table","data":{"name":"cloud_auth_user_emails","was_declared_in_moor":true,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"email","getter_name":"email","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"is_verified","getter_name":"isVerified","moor_type":"bool","nullable":false,"customConstraints":"NOT NULL DEFAULT FALSE","default_dart":"const CustomExpression('FALSE')","default_client_dart":null,"dsl_features":[]},{"name":"is_primary","getter_name":"isPrimary","moor_type":"bool","nullable":false,"customConstraints":"NOT NULL DEFAULT FALSE","default_dart":"const CustomExpression('FALSE')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":true,"constraints":["CONSTRAINT cloud_auth_user_emails_pk PRIMARY KEY(user_id, email)","CONSTRAINT cloud_auth_user_emails_user_fk FOREIGN KEY(user_id)REFERENCES cloud_auth_users(user_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED"],"explicit_pk":["user_id","email"]}},{"id":7,"references":[0],"type":"table","data":{"name":"cloud_auth_user_phone_numbers","was_declared_in_moor":true,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"phone_number","getter_name":"phoneNumber","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"is_verified","getter_name":"isVerified","moor_type":"bool","nullable":false,"customConstraints":"NOT NULL DEFAULT FALSE","default_dart":"const CustomExpression('FALSE')","default_client_dart":null,"dsl_features":[]},{"name":"is_primary","getter_name":"isPrimary","moor_type":"bool","nullable":false,"customConstraints":"NOT NULL DEFAULT FALSE","default_dart":"const CustomExpression('FALSE')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":true,"constraints":["CONSTRAINT cloud_auth_user_phone_numbers_pk PRIMARY KEY(user_id, phone_number)","CONSTRAINT cloud_auth_user_phone_numbers_user_fk FOREIGN KEY(user_id)REFERENCES cloud_auth_users(user_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED"],"explicit_pk":["user_id","phone_number"]}},{"id":8,"references":[],"type":"table","data":{"name":"cloud_auth_projects","was_declared_in_moor":true,"columns":[{"name":"project_id","getter_name":"projectId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]},{"name":"version","getter_name":"version","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"resolved_ast","getter_name":"resolvedAst","moor_type":"blob","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const ResolvedProjectConverter()","dart_type_name":"ResolvedProject"}},{"name":"etag","getter_name":"etag","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":9,"references":[8],"type":"table","data":{"name":"cloud_auth_apis","was_declared_in_moor":true,"columns":[{"name":"api_id","getter_name":"apiId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]},{"name":"project_id","getter_name":"projectId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"resolved_ast","getter_name":"resolvedAst","moor_type":"blob","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const ResolvedApiConverter()","dart_type_name":"ResolvedApi"}},{"name":"etag","getter_name":"etag","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":["CONSTRAINT cloud_auth_apis_project_fk FOREIGN KEY(project_id)REFERENCES cloud_auth_projects(project_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED"]}},{"id":10,"references":[9],"type":"index","data":{"on":9,"name":"cloud_auth_apis_project_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_apis_project_idx ON cloud_auth_apis(project_id);","unique":false,"columns":[]}},{"id":11,"references":[9,2],"type":"trigger","data":{"on":9,"references_in_body":[9,2],"name":"cloud_auth_apis_create_trg","sql":"CREATE TRIGGER IF NOT EXISTS cloud_auth_apis_create_trg\nBEFORE INSERT ON cloud_auth_apis\nBEGIN\n INSERT INTO cedar_entities(entity_type, entity_id)\n VALUES ('Celest::Api', NEW.api_id);\nEND;"}},{"id":12,"references":[9,4,2],"type":"trigger","data":{"on":9,"references_in_body":[9,4,2],"name":"cloud_auth_apis_delete_trg","sql":"CREATE TRIGGER IF NOT EXISTS cloud_auth_apis_delete_trg\nAFTER DELETE ON cloud_auth_apis\nBEGIN\n DELETE FROM cedar_relationships\n WHERE \n entity_type = 'Celest::Api'\n AND entity_id = OLD.api_id;\n DELETE FROM cedar_relationships\n WHERE \n parent_type = 'Celest::Api'\n AND parent_id = OLD.api_id;\n DELETE FROM cedar_entities\n WHERE\n entity_type = 'Celest::Api'\n AND entity_id = OLD.api_id;\nEND;"}},{"id":13,"references":[9],"type":"table","data":{"name":"cloud_auth_functions","was_declared_in_moor":true,"columns":[{"name":"function_id","getter_name":"functionId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]},{"name":"api_id","getter_name":"apiId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"resolved_ast","getter_name":"resolvedAst","moor_type":"blob","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const ResolvedFunctionConverter()","dart_type_name":"ResolvedCloudFunction"}},{"name":"etag","getter_name":"etag","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":["CONSTRAINT cloud_auth_functions_api_fk FOREIGN KEY(api_id)REFERENCES cloud_auth_apis(api_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED"]}},{"id":14,"references":[13],"type":"index","data":{"on":13,"name":"cloud_auth_functions_api_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_functions_api_idx ON cloud_auth_functions(api_id);","unique":false,"columns":[]}},{"id":15,"references":[13,2,4],"type":"trigger","data":{"on":13,"references_in_body":[13,2,4],"name":"cloud_auth_functions_create_trg","sql":"CREATE TRIGGER IF NOT EXISTS cloud_auth_functions_create_trg\nBEFORE INSERT ON cloud_auth_functions\nBEGIN\n INSERT INTO cedar_entities(entity_type, entity_id)\n VALUES ('Celest::Function', NEW.function_id);\n INSERT INTO cedar_relationships(entity_type, entity_id, parent_type, parent_id)\n VALUES ('Celest::Function', NEW.function_id, 'Celest::Api', NEW.api_id);\nEND;"}},{"id":16,"references":[13,4,2],"type":"trigger","data":{"on":13,"references_in_body":[13,4,2],"name":"cloud_auth_functions_delete_trg","sql":"CREATE TRIGGER IF NOT EXISTS cloud_auth_functions_delete_trg\nAFTER DELETE ON cloud_auth_functions\nBEGIN\n DELETE FROM cedar_relationships\n WHERE \n entity_type = 'Celest::Function'\n AND entity_id = OLD.function_id;\n DELETE FROM cedar_relationships\n WHERE \n parent_type = 'Celest::Function'\n AND parent_id = OLD.function_id;\n DELETE FROM cedar_entities\n WHERE\n entity_type = 'Celest::Function'\n AND entity_id = OLD.function_id;\nEND;"}},{"id":17,"references":[],"type":"table","data":{"name":"cloud_auth_meta","was_declared_in_moor":true,"columns":[{"name":"schema_version","getter_name":"schemaVersion","moor_type":"int","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":18,"references":[],"type":"table","data":{"name":"cloud_auth_crypto_keys","was_declared_in_moor":true,"columns":[{"name":"crypto_key_id","getter_name":"cryptoKeyId","moor_type":"blob","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]},{"name":"key_purpose","getter_name":"keyPurpose","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"key_algorithm","getter_name":"keyAlgorithm","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"key_material","getter_name":"keyMaterial","moor_type":"blob","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"external_crypto_key_id","getter_name":"externalCryptoKeyId","moor_type":"string","nullable":true,"customConstraints":"UNIQUE","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]}],"is_virtual":false,"without_rowid":false,"constraints":["CHECK(key_material IS NOT NULL OR external_crypto_key_id IS NOT NULL)"]}},{"id":19,"references":[18],"type":"index","data":{"on":18,"name":"cloud_auth_crypto_keys_external_crypto_key_id_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_crypto_keys_external_crypto_key_id_idx ON cloud_auth_crypto_keys(external_crypto_key_id);","unique":false,"columns":[]}},{"id":20,"references":[0,18],"type":"table","data":{"name":"cloud_auth_sessions","was_declared_in_moor":true,"columns":[{"name":"rowid","getter_name":"rowid","moor_type":"int","nullable":false,"customConstraints":"PRIMARY KEY AUTOINCREMENT","default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"session_id","getter_name":"sessionId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL UNIQUE","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"crypto_key_id","getter_name":"cryptoKeyId","moor_type":"blob","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"user_id","getter_name":"userId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"client_info","getter_name":"clientInfo","moor_type":"blob","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const SessionClientConverter()","dart_type_name":"SessionClient"}},{"name":"authentication_factor","getter_name":"authenticationFactor","moor_type":"blob","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const AuthenticationFactorConverter()","dart_type_name":"AuthenticationFactor"}},{"name":"state","getter_name":"state","moor_type":"blob","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const SessionStateConverter()","dart_type_name":"SessionState"}},{"name":"ip_address","getter_name":"ipAddress","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"external_session_id","getter_name":"externalSessionId","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"create_time","getter_name":"createTime","moor_type":"double","nullable":false,"customConstraints":"NOT NULL DEFAULT (unixepoch('now', 'subsec'))","default_dart":"const CustomExpression('unixepoch(\\'now\\', \\'subsec\\')')","default_client_dart":null,"dsl_features":[]},{"name":"update_time","getter_name":"updateTime","moor_type":"double","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"expire_time","getter_name":"expireTime","moor_type":"double","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":["CONSTRAINT cloud_auth_sessions_user_fk FOREIGN KEY(user_id)REFERENCES cloud_auth_users(user_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED","CONSTRAINT cloud_auth_sessions_key_fk FOREIGN KEY(crypto_key_id)REFERENCES cloud_auth_crypto_keys(crypto_key_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED"]}},{"id":21,"references":[20],"type":"index","data":{"on":20,"name":"cloud_auth_sessions_user_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_sessions_user_idx ON cloud_auth_sessions(user_id);","unique":false,"columns":[]}},{"id":22,"references":[20],"type":"index","data":{"on":20,"name":"cloud_auth_sessions_crypto_key_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_sessions_crypto_key_idx ON cloud_auth_sessions(crypto_key_id);","unique":false,"columns":[]}},{"id":23,"references":[20],"type":"index","data":{"on":20,"name":"cloud_auth_sessions_external_session_id_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_sessions_external_session_id_idx ON cloud_auth_sessions(external_session_id);","unique":false,"columns":[]}},{"id":24,"references":[20],"type":"trigger","data":{"on":20,"references_in_body":[20],"name":"cloud_auth_sessions_update_time_trg","sql":"CREATE TRIGGER IF NOT EXISTS cloud_auth_sessions_update_time_trg\nAFTER UPDATE ON cloud_auth_sessions\nBEGIN\n UPDATE cloud_auth_sessions\n SET update_time = unixepoch('now', 'subsec')\n WHERE rowid = OLD.rowid;\nEND;"}},{"id":25,"references":[20],"type":"table","data":{"name":"cloud_auth_otp_codes","was_declared_in_moor":true,"columns":[{"name":"rowid","getter_name":"rowid","moor_type":"int","nullable":false,"customConstraints":"PRIMARY KEY AUTOINCREMENT","default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"session_id","getter_name":"sessionId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL UNIQUE","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"resend_attempt","getter_name":"resendAttempt","moor_type":"int","nullable":false,"customConstraints":"NOT NULL DEFAULT 0","default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verify_attempt","getter_name":"verifyAttempt","moor_type":"int","nullable":false,"customConstraints":"NOT NULL DEFAULT 0","default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"update_time","getter_name":"updateTime","moor_type":"double","nullable":false,"customConstraints":"NOT NULL DEFAULT (unixepoch('now', 'subsec'))","default_dart":"const CustomExpression('unixepoch(\\'now\\', \\'subsec\\')')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":["CONSTRAINT cloud_auth_otp_codes_session_id_fk FOREIGN KEY(session_id)REFERENCES cloud_auth_sessions(session_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED"]}},{"id":26,"references":[25],"type":"index","data":{"on":25,"name":"cloud_auth_otp_codes_session_id_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_otp_codes_session_id_idx ON cloud_auth_otp_codes(session_id);","unique":false,"columns":[]}},{"id":27,"references":[18,2],"type":"table","data":{"name":"cloud_auth_corks","was_declared_in_moor":true,"columns":[{"name":"cork_id","getter_name":"corkId","moor_type":"blob","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]},{"name":"crypto_key_id","getter_name":"cryptoKeyId","moor_type":"blob","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"bearer_type","getter_name":"bearerType","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"bearer_id","getter_name":"bearerId","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"audience_type","getter_name":"audienceType","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"audience_id","getter_name":"audienceId","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"issuer_type","getter_name":"issuerType","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"issuer_id","getter_name":"issuerId","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"create_time","getter_name":"createTime","moor_type":"double","nullable":false,"customConstraints":"NOT NULL DEFAULT (unixepoch('now', 'subsec'))","default_dart":"const CustomExpression('unixepoch(\\'now\\', \\'subsec\\')')","default_client_dart":null,"dsl_features":[]},{"name":"expire_time","getter_name":"expireTime","moor_type":"double","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_use_time","getter_name":"lastUseTime","moor_type":"double","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":["CONSTRAINT cloud_auth_corks_crypto_key_fk FOREIGN KEY(crypto_key_id)REFERENCES cloud_auth_crypto_keys(crypto_key_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED","CONSTRAINT cloud_auth_corks_bearer_fk FOREIGN KEY(bearer_type, bearer_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED","CONSTRAINT cloud_auth_corks_audience_fk FOREIGN KEY(audience_type, audience_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED","CONSTRAINT cloud_auth_corks_issuer_fk FOREIGN KEY(issuer_type, issuer_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED"]}},{"id":28,"references":[27],"type":"index","data":{"on":27,"name":"cloud_auth_corks_crypto_key_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_corks_crypto_key_idx ON cloud_auth_corks(crypto_key_id);","unique":false,"columns":[]}},{"id":29,"references":[27],"type":"index","data":{"on":27,"name":"cloud_auth_corks_bearer_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_corks_bearer_idx ON cloud_auth_corks(bearer_type, bearer_id);","unique":false,"columns":[]}},{"id":30,"references":[27],"type":"index","data":{"on":27,"name":"cloud_auth_corks_audience_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_corks_audience_idx ON cloud_auth_corks(audience_type, audience_id);","unique":false,"columns":[]}},{"id":31,"references":[27],"type":"index","data":{"on":27,"name":"cloud_auth_corks_issuer_idx","sql":"CREATE INDEX IF NOT EXISTS cloud_auth_corks_issuer_idx ON cloud_auth_corks(issuer_type, issuer_id);","unique":false,"columns":[]}},{"id":32,"references":[4],"type":"index","data":{"on":4,"name":"cedar_relationships_fk_entity_idx","sql":"CREATE INDEX IF NOT EXISTS cedar_relationships_fk_entity_idx ON cedar_relationships(entity_type, entity_id);","unique":false,"columns":[]}},{"id":33,"references":[4],"type":"index","data":{"on":4,"name":"cedar_relationships_fk_parent_idx","sql":"CREATE INDEX IF NOT EXISTS cedar_relationships_fk_parent_idx ON cedar_relationships(parent_type, parent_id);","unique":false,"columns":[]}},{"id":34,"references":[],"type":"table","data":{"name":"cedar_policies","was_declared_in_moor":true,"columns":[{"name":"id","getter_name":"id","moor_type":"string","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]},{"name":"policy_id","getter_name":"policyId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL UNIQUE","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"policy","getter_name":"policy","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const CedarPolicyConverter()","dart_type_name":"Policy"}},{"name":"enforcement_level","getter_name":"enforcementLevel","moor_type":"int","nullable":false,"customConstraints":"NOT NULL DEFAULT 1","default_dart":"const CustomExpression('1')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":["CHECK(enforcement_level IN (0, 1))"]}},{"id":35,"references":[],"type":"table","data":{"name":"cedar_policy_templates","was_declared_in_moor":true,"columns":[{"name":"id","getter_name":"id","moor_type":"string","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]},{"name":"template_id","getter_name":"templateId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL UNIQUE","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"template","getter_name":"template","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const CedarPolicyConverter()","dart_type_name":"Policy"}}],"is_virtual":false,"without_rowid":false,"constraints":["CHECK(template IS NOT NULL OR template IS NOT NULL)"]}},{"id":36,"references":[35,2],"type":"table","data":{"name":"cedar_policy_template_links","was_declared_in_moor":true,"columns":[{"name":"id","getter_name":"id","moor_type":"string","nullable":false,"customConstraints":"NOT NULL PRIMARY KEY","default_dart":null,"default_client_dart":null,"dsl_features":["primary-key"]},{"name":"policy_id","getter_name":"policyId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL UNIQUE","default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"template_id","getter_name":"templateId","moor_type":"string","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"principal_type","getter_name":"principalType","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"principal_id","getter_name":"principalId","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"resource_type","getter_name":"resourceType","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"resource_id","getter_name":"resourceId","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"enforcement_level","getter_name":"enforcementLevel","moor_type":"int","nullable":false,"customConstraints":"NOT NULL DEFAULT 1","default_dart":"const CustomExpression('1')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":["CHECK(principal_type IS NOT NULL AND principal_id IS NOT NULL OR resource_type IS NOT NULL AND resource_id IS NOT NULL)","CHECK(enforcement_level IN (0, 1))","CONSTRAINT cedar_policy_template_links_fk_template_id FOREIGN KEY(template_id)REFERENCES cedar_policy_templates(template_id)ON UPDATE CASCADE ON DELETE CASCADE","CONSTRAINT cedar_policy_template_links_fk_principal FOREIGN KEY(principal_type, principal_id)REFERENCES cedar_entities(entity_type, entity_id)ON DELETE CASCADE","CONSTRAINT cedar_policy_template_links_fk_resource FOREIGN KEY(resource_type, resource_id)REFERENCES cedar_entities(entity_type, entity_id)ON DELETE CASCADE"]}},{"id":37,"references":[36],"type":"index","data":{"on":36,"name":"cedar_policy_template_links_fk_template_id_idx","sql":"CREATE INDEX IF NOT EXISTS cedar_policy_template_links_fk_template_id_idx ON cedar_policy_template_links(template_id);","unique":false,"columns":[]}},{"id":38,"references":[36],"type":"index","data":{"on":36,"name":"cedar_policy_template_links_fk_principal_idx","sql":"CREATE INDEX IF NOT EXISTS cedar_policy_template_links_fk_principal_idx ON cedar_policy_template_links(principal_type, principal_id);","unique":false,"columns":[]}},{"id":39,"references":[36],"type":"index","data":{"on":36,"name":"cedar_policy_template_links_fk_resource_idx","sql":"CREATE INDEX IF NOT EXISTS cedar_policy_template_links_fk_resource_idx ON cedar_policy_template_links(resource_type, resource_id);","unique":false,"columns":[]}},{"id":40,"references":[],"type":"table","data":{"name":"cedar_authorization_logs","was_declared_in_moor":true,"columns":[{"name":"rowid","getter_name":"rowid","moor_type":"int","nullable":false,"customConstraints":"PRIMARY KEY AUTOINCREMENT","default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"create_time","getter_name":"createTime","moor_type":"dateTime","nullable":false,"customConstraints":"NOT NULL DEFAULT (unixepoch('now', 'subsec'))","default_dart":"const CustomExpression('unixepoch(\\'now\\', \\'subsec\\')')","default_client_dart":null,"dsl_features":[]},{"name":"expire_time","getter_name":"expireTime","moor_type":"dateTime","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"principal_type","getter_name":"principalType","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"principal_id","getter_name":"principalId","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"action_type","getter_name":"actionType","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"action_id","getter_name":"actionId","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"resource_type","getter_name":"resourceType","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"resource_id","getter_name":"resourceId","moor_type":"string","nullable":true,"customConstraints":"","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"context_json","getter_name":"contextJson","moor_type":"string","nullable":false,"customConstraints":"NOT NULL DEFAULT '{}'","default_dart":"const CustomExpression('\\'{}\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const CedarAttributesConverter()","dart_type_name":"Map"}},{"name":"decision","getter_name":"decision","moor_type":"bool","nullable":false,"customConstraints":"NOT NULL","default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"reasons_json","getter_name":"reasonsJson","moor_type":"string","nullable":false,"customConstraints":"NOT NULL DEFAULT '[]'","default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const CedarAuthorizationReasonsConverter()","dart_type_name":"List"}},{"name":"errors_json","getter_name":"errorsJson","moor_type":"string","nullable":false,"customConstraints":"NOT NULL DEFAULT '[]'","default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const CedarAuthorizationErrorsConverter()","dart_type_name":"AuthorizationErrors"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}}]} \ No newline at end of file diff --git a/services/celest_cloud_auth/lib/celest_cloud_auth.dart b/services/celest_cloud_auth/lib/celest_cloud_auth.dart index c1cf473d2..12bf690f2 100644 --- a/services/celest_cloud_auth/lib/celest_cloud_auth.dart +++ b/services/celest_cloud_auth/lib/celest_cloud_auth.dart @@ -104,6 +104,8 @@ final class CelestCloudAuth { issuer: context.rootEntity, routeMap: routeMap, corks: corks, + cryptoKeys: cryptoKeys, + users: users, db: db, authorizer: authorizer, ); @@ -162,6 +164,8 @@ final class CelestCloudAuth { routeMap: routeMap, authorizer: authorizer, corks: corks, + cryptoKeys: cryptoKeys, + users: users, db: db, ); diff --git a/services/celest_cloud_auth/lib/src/authentication/authentication_model.dart b/services/celest_cloud_auth/lib/src/authentication/authentication_model.dart index b8649a6b3..cfc653643 100644 --- a/services/celest_cloud_auth/lib/src/authentication/authentication_model.dart +++ b/services/celest_cloud_auth/lib/src/authentication/authentication_model.dart @@ -177,13 +177,13 @@ final class SessionStateSuccess extends SessionState { factory SessionStateSuccess.fromProto(pb.AuthenticationSuccess success) { return SessionStateSuccess( - cork: Cork.parse(success.identityToken), + cork: CedarCork.parse(success.identityToken), user: success.user.toModel(), isNewUser: success.isNewUser, ); } - final Cork cork; + final CedarCork cork; String get identityToken => cork.toString(); final User user; diff --git a/services/celest_cloud_auth/lib/src/authentication/authentication_service.dart b/services/celest_cloud_auth/lib/src/authentication/authentication_service.dart index 9e5d9582d..9bf669cab 100644 --- a/services/celest_cloud_auth/lib/src/authentication/authentication_service.dart +++ b/services/celest_cloud_auth/lib/src/authentication/authentication_service.dart @@ -5,6 +5,7 @@ import 'package:celest_ast/celest_ast.dart'; import 'package:celest_cloud/src/proto.dart' as pb; import 'package:celest_cloud_auth/src/authorization/authorization_middleware.dart'; import 'package:celest_cloud_auth/src/authorization/authorizer.dart'; +import 'package:celest_cloud_auth/src/authorization/celest_role.dart'; import 'package:celest_cloud_auth/src/authorization/corks_repository.dart'; import 'package:celest_cloud_auth/src/context.dart'; import 'package:celest_cloud_auth/src/crypto/crypto_key_repository.dart'; @@ -16,6 +17,7 @@ import 'package:celest_cloud_auth/src/sessions/sessions_repository.dart'; import 'package:celest_cloud_auth/src/users/users_repository.dart'; import 'package:celest_cloud_auth/src/util/typeid.dart'; import 'package:celest_core/celest_core.dart'; +import 'package:clock/clock.dart'; import 'package:corks_cedar/corks_cedar.dart'; import 'package:meta/meta.dart'; import 'package:shelf/shelf.dart'; @@ -137,6 +139,8 @@ extension type AuthenticationService._(_Deps _deps) implements Object { final requestAuthorizer = AuthorizationMiddleware( routeMap: _deps.routeMap, corks: _deps.corks, + cryptoKeys: _deps.cryptoKeys, + users: _deps.users, db: _deps.db, authorizer: _deps.authorizer, issuer: _deps.issuer, @@ -275,19 +279,19 @@ extension type AuthenticationService._(_Deps _deps) implements Object { throw InternalServerError('Unknown user: ${session.userId}'); } - final isNewUser = user.roles.contains( - const EntityUid.of('Celest::Role', 'anonymous'), - ); + final isNewUser = user.roles.contains(CelestRole.anonymous); if (isNewUser) { user = await _users.updateUser( userId: session.userId, factor: factor, - roles: const [EntityUid.of('Celest::Role', 'authenticated')], + roles: const [CelestRole.authenticated], ); } final cork = await _corks.createCork( + session: session.copyWith( + expireTime: clock.now().add(SessionsRepository.postAuthSessionDuration), + ), user: user, - session: session, ); return SessionStateSuccess( cork: cork, @@ -317,7 +321,7 @@ extension type AuthenticationService._(_Deps _deps) implements Object { 'Failed to send OTP. Please restart the authentication flow.', ); } - final resendIn = nextResend.difference(DateTime.timestamp()); + final resendIn = nextResend.difference(clock.now()); throw ResourceExhaustedException( 'Failed to send OTP. Try again in ${resendIn.inSeconds} seconds', ); @@ -334,7 +338,7 @@ extension type AuthenticationService._(_Deps _deps) implements Object { // 'Failed to send OTP. Please restart the authentication flow.', // ); // } - // final resendIn = nextResend.difference(DateTime.timestamp()); + // final resendIn = nextResend.difference(clock.now()); // throw ResourceExhaustedException( // 'Failed to send OTP. Try again in ${resendIn.inSeconds} seconds', // ); @@ -358,7 +362,7 @@ extension type AuthenticationService._(_Deps _deps) implements Object { SessionStatePendingConfirmation? confirmation, AuthenticationFactor? resend, }) async { - var session = await _db.cloudAuthCoreDrift + final session = await _db.cloudAuthCoreDrift .getSession(sessionId: sessionId.encoded) .getSingleOrNull(); if (session == null) { @@ -386,11 +390,14 @@ extension type AuthenticationService._(_Deps _deps) implements Object { null => throw StateError('Unexpected state'), }; - session = await _sessions.updateSession( + return _sessions.updateSession( session: session, state: updatedState, + sessionDuration: switch (updatedState) { + SessionStateSuccess() => SessionsRepository.postAuthSessionDuration, + _ => SessionsRepository.preAuthSessionDuration, + }, ); - return session.copyWith(sessionToken: sessionToken); } Future handleContinueSession(Request request) async { diff --git a/services/celest_cloud_auth/lib/src/authorization/authorization_middleware.dart b/services/celest_cloud_auth/lib/src/authorization/authorization_middleware.dart index ee9072731..fffe11c7d 100644 --- a/services/celest_cloud_auth/lib/src/authorization/authorization_middleware.dart +++ b/services/celest_cloud_auth/lib/src/authorization/authorization_middleware.dart @@ -3,10 +3,14 @@ import 'package:celest/http.dart'; import 'package:celest_cloud_auth/src/authorization/authorizer.dart'; import 'package:celest_cloud_auth/src/authorization/corks_repository.dart'; import 'package:celest_cloud_auth/src/context.dart'; +import 'package:celest_cloud_auth/src/crypto/crypto_key_repository.dart'; import 'package:celest_cloud_auth/src/database/auth_database_accessors.dart'; import 'package:celest_cloud_auth/src/http/http_helpers.dart'; import 'package:celest_cloud_auth/src/model/interop.dart'; import 'package:celest_cloud_auth/src/model/route_map.dart'; +import 'package:celest_cloud_auth/src/sessions/sessions_repository.dart'; +import 'package:celest_cloud_auth/src/users/users_repository.dart'; +import 'package:celest_cloud_auth/src/util/typeid.dart'; import 'package:celest_core/celest_core.dart' as core; import 'package:celest_core/celest_core.dart'; import 'package:collection/collection.dart'; @@ -17,6 +21,8 @@ import 'package:shelf/shelf.dart' show Handler, Request; typedef _Deps = ({ RouteMap routeMap, CorksRepository corks, + CryptoKeyRepository cryptoKeys, + UsersRepository users, CloudAuthDatabaseMixin db, Authorizer authorizer, EntityUid issuer, @@ -30,6 +36,8 @@ extension type AuthorizationMiddleware._(_Deps _deps) implements Object { AuthorizationMiddleware({ required RouteMap routeMap, required CorksRepository corks, + required CryptoKeyRepository cryptoKeys, + required UsersRepository users, required CloudAuthDatabaseMixin db, required Authorizer authorizer, required EntityUid issuer, @@ -37,6 +45,8 @@ extension type AuthorizationMiddleware._(_Deps _deps) implements Object { ( routeMap: routeMap, corks: corks, + cryptoKeys: cryptoKeys, + users: users, db: db, authorizer: authorizer, issuer: issuer, @@ -47,6 +57,12 @@ extension type AuthorizationMiddleware._(_Deps _deps) implements Object { CorksRepository get _corks => _deps.corks; CloudAuthDatabaseAccessors get _db => _deps.db.cloudAuth; Authorizer get _authorizer => _deps.authorizer; + SessionsRepository get _sessions => SessionsRepository( + corks: _corks, + db: _deps.db, + cryptoKeys: _deps.cryptoKeys, + users: _deps.users, + ); Handler call(Handler inner) { return (request) async { @@ -129,13 +145,20 @@ extension type AuthorizationMiddleware._(_Deps _deps) implements Object { context.put(contextKeyCork, cork); switch (cork.bearer) { case EntityUid(type: 'Celest::Session', id: final sessionId): - final session = await _db.getSession(sessionId: sessionId); + final sessionTid = TypeId.tryDecode(sessionId); + if (sessionTid == null) { + context.logger.severe('Invalid session ID: $sessionId'); + throw const UnauthorizedException('Invalid session ID'); + } + final session = await _sessions.getSession( + sessionId: sessionTid, + ); if (session == null) { - throw const UnauthorizedException('Invalid session'); + throw UnauthorizedException('Invalid session: $sessionId'); } final user = await _db.getUser(userId: session.userId); if (user == null) { - throw const UnauthorizedException('Invalid user'); + throw UnauthorizedException('Invalid user: ${session.userId}'); } context.logger.finest('Found user for cork: $user'); return (user, user.toEntity()); diff --git a/services/celest_cloud_auth/lib/src/authorization/corks_repository.dart b/services/celest_cloud_auth/lib/src/authorization/corks_repository.dart index 5f4675160..81df4d515 100644 --- a/services/celest_cloud_auth/lib/src/authorization/corks_repository.dart +++ b/services/celest_cloud_auth/lib/src/authorization/corks_repository.dart @@ -8,6 +8,7 @@ import 'package:celest_cloud_auth/src/database/schema/cloud_auth_core.drift.dart as drift; import 'package:celest_cloud_auth/src/model/interop.dart'; import 'package:celest_core/celest_core.dart'; +import 'package:clock/clock.dart'; import 'package:corks_cedar/corks_cedar.dart'; import 'package:drift/drift.dart' as drift; @@ -41,7 +42,7 @@ extension type CorksRepository._(_Dependencies _deps) implements Object { } /// Creates a new cork for the given [user]. - Future createCork({ + Future createCork({ required Session session, required User user, EntityUid? audience, @@ -88,7 +89,7 @@ extension type CorksRepository._(_Dependencies _deps) implements Object { expireTime: expireTime, ); }); - return cork; + return CedarCork(cork); } /// Verifies the given [cork]. @@ -115,7 +116,7 @@ extension type CorksRepository._(_Dependencies _deps) implements Object { ..where((tbl) => tbl.corkId.equals(cork.id)); await query.write( drift.CloudAuthCorksCompanion( - lastUseTime: drift.Value(DateTime.timestamp()), + lastUseTime: drift.Value(clock.now()), ), ); } on Object catch (e, st) { diff --git a/services/celest_cloud_auth/lib/src/database/auth_database.dart b/services/celest_cloud_auth/lib/src/database/auth_database.dart index 58811af31..d2bdbde8c 100644 --- a/services/celest_cloud_auth/lib/src/database/auth_database.dart +++ b/services/celest_cloud_auth/lib/src/database/auth_database.dart @@ -57,7 +57,7 @@ class CloudAuthDatabase extends $CloudAuthDatabase with CloudAuthDatabaseMixin { final ResolvedProject? _project; @override - int get schemaVersion => 4; + int get schemaVersion => 5; @override MigrationStrategy get migration { diff --git a/services/celest_cloud_auth/lib/src/database/auth_database.steps.dart b/services/celest_cloud_auth/lib/src/database/auth_database.steps.dart index cc9862bcf..27485d7b6 100644 --- a/services/celest_cloud_auth/lib/src/database/auth_database.steps.dart +++ b/services/celest_cloud_auth/lib/src/database/auth_database.steps.dart @@ -1904,10 +1904,493 @@ final class Schema4 extends i0.VersionedSchema { alias: null); } +final class Schema5 extends i0.VersionedSchema { + Schema5({required super.database}) : super(version: 5); + @override + late final List entities = [ + cloudAuthUsers, + cedarTypes, + cedarEntities, + cloudAuthUsersCreateTrg, + cedarRelationships, + cloudAuthUsersDeleteTrg, + cloudAuthUserEmails, + cloudAuthUserPhoneNumbers, + cloudAuthProjects, + cloudAuthApis, + cloudAuthApisProjectIdx, + cloudAuthApisCreateTrg, + cloudAuthApisDeleteTrg, + cloudAuthFunctions, + cloudAuthFunctionsApiIdx, + cloudAuthFunctionsCreateTrg, + cloudAuthFunctionsDeleteTrg, + cloudAuthMeta, + cloudAuthCryptoKeys, + cloudAuthCryptoKeysExternalCryptoKeyIdIdx, + cloudAuthSessions, + cloudAuthSessionsUserIdx, + cloudAuthSessionsCryptoKeyIdx, + cloudAuthSessionsExternalSessionIdIdx, + cloudAuthSessionsUpdateTimeTrg, + cloudAuthOtpCodes, + cloudAuthOtpCodesSessionIdIdx, + cloudAuthCorks, + cloudAuthCorksCryptoKeyIdx, + cloudAuthCorksBearerIdx, + cloudAuthCorksAudienceIdx, + cloudAuthCorksIssuerIdx, + cedarRelationshipsFkEntityIdx, + cedarRelationshipsFkParentIdx, + cedarPolicies, + cedarPolicyTemplates, + cedarPolicyTemplateLinks, + cedarPolicyTemplateLinksFkTemplateIdIdx, + cedarPolicyTemplateLinksFkPrincipalIdx, + cedarPolicyTemplateLinksFkResourceIdx, + cedarAuthorizationLogs, + ]; + late final Shape0 cloudAuthUsers = Shape0( + source: i0.VersionedTable( + entityName: 'cloud_auth_users', + withoutRowId: false, + isStrict: false, + tableConstraints: [], + columns: [ + _column_0, + _column_1, + _column_2, + _column_3, + _column_4, + _column_5, + _column_6, + ], + attachedDatabase: database, + ), + alias: null); + late final Shape1 cedarTypes = Shape1( + source: i0.VersionedTable( + entityName: 'cedar_types', + withoutRowId: false, + isStrict: false, + tableConstraints: [], + columns: [ + _column_7, + ], + attachedDatabase: database, + ), + alias: null); + late final Shape2 cedarEntities = Shape2( + source: i0.VersionedTable( + entityName: 'cedar_entities', + withoutRowId: true, + isStrict: false, + tableConstraints: [ + 'CONSTRAINT cedar_entities_pk PRIMARY KEY(entity_type, entity_id)ON CONFLICT IGNORE', + ], + columns: [ + _column_8, + _column_9, + _column_10, + _column_11, + ], + attachedDatabase: database, + ), + alias: null); + final i1.Trigger cloudAuthUsersCreateTrg = i1.Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_users_create_trg BEFORE INSERT ON cloud_auth_users BEGIN INSERT INTO cedar_entities (entity_type, entity_id) VALUES (\'Celest::User\', NEW.user_id);END', + 'cloud_auth_users_create_trg'); + late final Shape3 cedarRelationships = Shape3( + source: i0.VersionedTable( + entityName: 'cedar_relationships', + withoutRowId: true, + isStrict: false, + tableConstraints: [ + 'CONSTRAINT cedar_relationships_pk PRIMARY KEY(entity_type, entity_id, parent_type, parent_id)ON CONFLICT IGNORE', + 'CONSTRAINT cedar_relationships_fk_entity FOREIGN KEY(entity_type, entity_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE', + 'CONSTRAINT cedar_relationships_fk_parent FOREIGN KEY(parent_type, parent_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE', + ], + columns: [ + _column_12, + _column_9, + _column_11, + _column_13, + _column_14, + _column_15, + ], + attachedDatabase: database, + ), + alias: null); + final i1.Trigger cloudAuthUsersDeleteTrg = i1.Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_users_delete_trg AFTER DELETE ON cloud_auth_users BEGIN DELETE FROM cedar_relationships WHERE(entity_type = \'Celest::User\' AND entity_id = OLD.user_id)OR(parent_type = \'Celest::User\' AND parent_id = OLD.user_id);DELETE FROM cedar_entities WHERE entity_id = OLD.user_id AND entity_type = \'Celest::User\';END', + 'cloud_auth_users_delete_trg'); + late final Shape4 cloudAuthUserEmails = Shape4( + source: i0.VersionedTable( + entityName: 'cloud_auth_user_emails', + withoutRowId: true, + isStrict: false, + tableConstraints: [ + 'CONSTRAINT cloud_auth_user_emails_pk PRIMARY KEY(user_id, email)', + 'CONSTRAINT cloud_auth_user_emails_user_fk FOREIGN KEY(user_id)REFERENCES cloud_auth_users(user_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + ], + columns: [ + _column_16, + _column_17, + _column_18, + _column_19, + ], + attachedDatabase: database, + ), + alias: null); + late final Shape5 cloudAuthUserPhoneNumbers = Shape5( + source: i0.VersionedTable( + entityName: 'cloud_auth_user_phone_numbers', + withoutRowId: true, + isStrict: false, + tableConstraints: [ + 'CONSTRAINT cloud_auth_user_phone_numbers_pk PRIMARY KEY(user_id, phone_number)', + 'CONSTRAINT cloud_auth_user_phone_numbers_user_fk FOREIGN KEY(user_id)REFERENCES cloud_auth_users(user_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + ], + columns: [ + _column_16, + _column_20, + _column_18, + _column_19, + ], + attachedDatabase: database, + ), + alias: null); + late final Shape6 cloudAuthProjects = Shape6( + source: i0.VersionedTable( + entityName: 'cloud_auth_projects', + withoutRowId: false, + isStrict: false, + tableConstraints: [], + columns: [ + _column_21, + _column_22, + _column_23, + _column_24, + ], + attachedDatabase: database, + ), + alias: null); + late final Shape7 cloudAuthApis = Shape7( + source: i0.VersionedTable( + entityName: 'cloud_auth_apis', + withoutRowId: false, + isStrict: false, + tableConstraints: [ + 'CONSTRAINT cloud_auth_apis_project_fk FOREIGN KEY(project_id)REFERENCES cloud_auth_projects(project_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + ], + columns: [ + _column_25, + _column_26, + _column_23, + _column_24, + ], + attachedDatabase: database, + ), + alias: null); + final i1.Index cloudAuthApisProjectIdx = i1.Index( + 'cloud_auth_apis_project_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_apis_project_idx ON cloud_auth_apis (project_id)'); + final i1.Trigger cloudAuthApisCreateTrg = i1.Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_apis_create_trg BEFORE INSERT ON cloud_auth_apis BEGIN INSERT INTO cedar_entities (entity_type, entity_id) VALUES (\'Celest::Api\', NEW.api_id);END', + 'cloud_auth_apis_create_trg'); + final i1.Trigger cloudAuthApisDeleteTrg = i1.Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_apis_delete_trg AFTER DELETE ON cloud_auth_apis BEGIN DELETE FROM cedar_relationships WHERE entity_type = \'Celest::Api\' AND entity_id = OLD.api_id;DELETE FROM cedar_relationships WHERE parent_type = \'Celest::Api\' AND parent_id = OLD.api_id;DELETE FROM cedar_entities WHERE entity_type = \'Celest::Api\' AND entity_id = OLD.api_id;END', + 'cloud_auth_apis_delete_trg'); + late final Shape8 cloudAuthFunctions = Shape8( + source: i0.VersionedTable( + entityName: 'cloud_auth_functions', + withoutRowId: false, + isStrict: false, + tableConstraints: [ + 'CONSTRAINT cloud_auth_functions_api_fk FOREIGN KEY(api_id)REFERENCES cloud_auth_apis(api_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + ], + columns: [ + _column_27, + _column_28, + _column_23, + _column_24, + ], + attachedDatabase: database, + ), + alias: null); + final i1.Index cloudAuthFunctionsApiIdx = i1.Index( + 'cloud_auth_functions_api_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_functions_api_idx ON cloud_auth_functions (api_id)'); + final i1.Trigger cloudAuthFunctionsCreateTrg = i1.Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_functions_create_trg BEFORE INSERT ON cloud_auth_functions BEGIN INSERT INTO cedar_entities (entity_type, entity_id) VALUES (\'Celest::Function\', NEW.function_id);INSERT INTO cedar_relationships (entity_type, entity_id, parent_type, parent_id) VALUES (\'Celest::Function\', NEW.function_id, \'Celest::Api\', NEW.api_id);END', + 'cloud_auth_functions_create_trg'); + final i1.Trigger cloudAuthFunctionsDeleteTrg = i1.Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_functions_delete_trg AFTER DELETE ON cloud_auth_functions BEGIN DELETE FROM cedar_relationships WHERE entity_type = \'Celest::Function\' AND entity_id = OLD.function_id;DELETE FROM cedar_relationships WHERE parent_type = \'Celest::Function\' AND parent_id = OLD.function_id;DELETE FROM cedar_entities WHERE entity_type = \'Celest::Function\' AND entity_id = OLD.function_id;END', + 'cloud_auth_functions_delete_trg'); + late final Shape17 cloudAuthMeta = Shape17( + source: i0.VersionedTable( + entityName: 'cloud_auth_meta', + withoutRowId: false, + isStrict: false, + tableConstraints: [], + columns: [ + _column_75, + ], + attachedDatabase: database, + ), + alias: null); + late final Shape13 cloudAuthCryptoKeys = Shape13( + source: i0.VersionedTable( + entityName: 'cloud_auth_crypto_keys', + withoutRowId: false, + isStrict: false, + tableConstraints: [ + 'CHECK(key_material IS NOT NULL OR external_crypto_key_id IS NOT NULL)', + ], + columns: [ + _column_49, + _column_50, + _column_51, + _column_52, + _column_53, + ], + attachedDatabase: database, + ), + alias: null); + final i1.Index cloudAuthCryptoKeysExternalCryptoKeyIdIdx = i1.Index( + 'cloud_auth_crypto_keys_external_crypto_key_id_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_crypto_keys_external_crypto_key_id_idx ON cloud_auth_crypto_keys (external_crypto_key_id)'); + late final Shape18 cloudAuthSessions = Shape18( + source: i0.VersionedTable( + entityName: 'cloud_auth_sessions', + withoutRowId: false, + isStrict: false, + tableConstraints: [ + 'CONSTRAINT cloud_auth_sessions_user_fk FOREIGN KEY(user_id)REFERENCES cloud_auth_users(user_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + 'CONSTRAINT cloud_auth_sessions_key_fk FOREIGN KEY(crypto_key_id)REFERENCES cloud_auth_crypto_keys(crypto_key_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + ], + columns: [ + _column_40, + _column_54, + _column_55, + _column_16, + _column_56, + _column_57, + _column_58, + _column_59, + _column_60, + _column_5, + _column_6, + _column_61, + ], + attachedDatabase: database, + ), + alias: null); + final i1.Index cloudAuthSessionsUserIdx = i1.Index( + 'cloud_auth_sessions_user_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_sessions_user_idx ON cloud_auth_sessions (user_id)'); + final i1.Index cloudAuthSessionsCryptoKeyIdx = i1.Index( + 'cloud_auth_sessions_crypto_key_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_sessions_crypto_key_idx ON cloud_auth_sessions (crypto_key_id)'); + final i1.Index cloudAuthSessionsExternalSessionIdIdx = i1.Index( + 'cloud_auth_sessions_external_session_id_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_sessions_external_session_id_idx ON cloud_auth_sessions (external_session_id)'); + final i1.Trigger cloudAuthSessionsUpdateTimeTrg = i1.Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_sessions_update_time_trg AFTER UPDATE ON cloud_auth_sessions BEGIN UPDATE cloud_auth_sessions SET update_time = unixepoch(\'now\', \'subsec\') WHERE "rowid" = OLD."rowid";END', + 'cloud_auth_sessions_update_time_trg'); + late final Shape15 cloudAuthOtpCodes = Shape15( + source: i0.VersionedTable( + entityName: 'cloud_auth_otp_codes', + withoutRowId: false, + isStrict: false, + tableConstraints: [ + 'CONSTRAINT cloud_auth_otp_codes_session_id_fk FOREIGN KEY(session_id)REFERENCES cloud_auth_sessions(session_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + ], + columns: [ + _column_40, + _column_54, + _column_63, + _column_64, + _column_65, + ], + attachedDatabase: database, + ), + alias: null); + final i1.Index cloudAuthOtpCodesSessionIdIdx = i1.Index( + 'cloud_auth_otp_codes_session_id_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_otp_codes_session_id_idx ON cloud_auth_otp_codes (session_id)'); + late final Shape16 cloudAuthCorks = Shape16( + source: i0.VersionedTable( + entityName: 'cloud_auth_corks', + withoutRowId: false, + isStrict: false, + tableConstraints: [ + 'CONSTRAINT cloud_auth_corks_crypto_key_fk FOREIGN KEY(crypto_key_id)REFERENCES cloud_auth_crypto_keys(crypto_key_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + 'CONSTRAINT cloud_auth_corks_bearer_fk FOREIGN KEY(bearer_type, bearer_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + 'CONSTRAINT cloud_auth_corks_audience_fk FOREIGN KEY(audience_type, audience_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + 'CONSTRAINT cloud_auth_corks_issuer_fk FOREIGN KEY(issuer_type, issuer_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + ], + columns: [ + _column_66, + _column_55, + _column_67, + _column_68, + _column_69, + _column_70, + _column_71, + _column_72, + _column_5, + _column_73, + _column_74, + ], + attachedDatabase: database, + ), + alias: null); + final i1.Index cloudAuthCorksCryptoKeyIdx = i1.Index( + 'cloud_auth_corks_crypto_key_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_corks_crypto_key_idx ON cloud_auth_corks (crypto_key_id)'); + final i1.Index cloudAuthCorksBearerIdx = i1.Index( + 'cloud_auth_corks_bearer_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_corks_bearer_idx ON cloud_auth_corks (bearer_type, bearer_id)'); + final i1.Index cloudAuthCorksAudienceIdx = i1.Index( + 'cloud_auth_corks_audience_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_corks_audience_idx ON cloud_auth_corks (audience_type, audience_id)'); + final i1.Index cloudAuthCorksIssuerIdx = i1.Index( + 'cloud_auth_corks_issuer_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_corks_issuer_idx ON cloud_auth_corks (issuer_type, issuer_id)'); + final i1.Index cedarRelationshipsFkEntityIdx = i1.Index( + 'cedar_relationships_fk_entity_idx', + 'CREATE INDEX IF NOT EXISTS cedar_relationships_fk_entity_idx ON cedar_relationships (entity_type, entity_id)'); + final i1.Index cedarRelationshipsFkParentIdx = i1.Index( + 'cedar_relationships_fk_parent_idx', + 'CREATE INDEX IF NOT EXISTS cedar_relationships_fk_parent_idx ON cedar_relationships (parent_type, parent_id)'); + late final Shape9 cedarPolicies = Shape9( + source: i0.VersionedTable( + entityName: 'cedar_policies', + withoutRowId: false, + isStrict: false, + tableConstraints: [ + 'CHECK(enforcement_level IN (0, 1))', + ], + columns: [ + _column_29, + _column_30, + _column_31, + _column_32, + ], + attachedDatabase: database, + ), + alias: null); + late final Shape10 cedarPolicyTemplates = Shape10( + source: i0.VersionedTable( + entityName: 'cedar_policy_templates', + withoutRowId: false, + isStrict: false, + tableConstraints: [ + 'CHECK(template IS NOT NULL OR template IS NOT NULL)', + ], + columns: [ + _column_29, + _column_33, + _column_34, + ], + attachedDatabase: database, + ), + alias: null); + late final Shape11 cedarPolicyTemplateLinks = Shape11( + source: i0.VersionedTable( + entityName: 'cedar_policy_template_links', + withoutRowId: false, + isStrict: false, + tableConstraints: [ + 'CHECK(principal_type IS NOT NULL AND principal_id IS NOT NULL OR resource_type IS NOT NULL AND resource_id IS NOT NULL)', + 'CHECK(enforcement_level IN (0, 1))', + 'CONSTRAINT cedar_policy_template_links_fk_template_id FOREIGN KEY(template_id)REFERENCES cedar_policy_templates(template_id)ON UPDATE CASCADE ON DELETE CASCADE', + 'CONSTRAINT cedar_policy_template_links_fk_principal FOREIGN KEY(principal_type, principal_id)REFERENCES cedar_entities(entity_type, entity_id)ON DELETE CASCADE', + 'CONSTRAINT cedar_policy_template_links_fk_resource FOREIGN KEY(resource_type, resource_id)REFERENCES cedar_entities(entity_type, entity_id)ON DELETE CASCADE', + ], + columns: [ + _column_29, + _column_30, + _column_35, + _column_36, + _column_37, + _column_38, + _column_39, + _column_32, + ], + attachedDatabase: database, + ), + alias: null); + final i1.Index cedarPolicyTemplateLinksFkTemplateIdIdx = i1.Index( + 'cedar_policy_template_links_fk_template_id_idx', + 'CREATE INDEX IF NOT EXISTS cedar_policy_template_links_fk_template_id_idx ON cedar_policy_template_links (template_id)'); + final i1.Index cedarPolicyTemplateLinksFkPrincipalIdx = i1.Index( + 'cedar_policy_template_links_fk_principal_idx', + 'CREATE INDEX IF NOT EXISTS cedar_policy_template_links_fk_principal_idx ON cedar_policy_template_links (principal_type, principal_id)'); + final i1.Index cedarPolicyTemplateLinksFkResourceIdx = i1.Index( + 'cedar_policy_template_links_fk_resource_idx', + 'CREATE INDEX IF NOT EXISTS cedar_policy_template_links_fk_resource_idx ON cedar_policy_template_links (resource_type, resource_id)'); + late final Shape12 cedarAuthorizationLogs = Shape12( + source: i0.VersionedTable( + entityName: 'cedar_authorization_logs', + withoutRowId: false, + isStrict: false, + tableConstraints: [], + columns: [ + _column_40, + _column_41, + _column_42, + _column_36, + _column_37, + _column_43, + _column_44, + _column_38, + _column_39, + _column_45, + _column_46, + _column_47, + _column_48, + ], + attachedDatabase: database, + ), + alias: null); +} + +class Shape18 extends i0.VersionedTable { + Shape18({required super.source, required super.alias}) : super.aliased(); + i1.GeneratedColumn get rowid => + columnsByName['rowid']! as i1.GeneratedColumn; + i1.GeneratedColumn get sessionId => + columnsByName['session_id']! as i1.GeneratedColumn; + i1.GeneratedColumn get cryptoKeyId => + columnsByName['crypto_key_id']! as i1.GeneratedColumn; + i1.GeneratedColumn get userId => + columnsByName['user_id']! as i1.GeneratedColumn; + i1.GeneratedColumn get clientInfo => + columnsByName['client_info']! as i1.GeneratedColumn; + i1.GeneratedColumn get authenticationFactor => + columnsByName['authentication_factor']! + as i1.GeneratedColumn; + i1.GeneratedColumn get state => + columnsByName['state']! as i1.GeneratedColumn; + i1.GeneratedColumn get ipAddress => + columnsByName['ip_address']! as i1.GeneratedColumn; + i1.GeneratedColumn get externalSessionId => + columnsByName['external_session_id']! as i1.GeneratedColumn; + i1.GeneratedColumn get createTime => + columnsByName['create_time']! as i1.GeneratedColumn; + i1.GeneratedColumn get updateTime => + columnsByName['update_time']! as i1.GeneratedColumn; + i1.GeneratedColumn get expireTime => + columnsByName['expire_time']! as i1.GeneratedColumn; +} + i0.MigrationStepWithVersion migrationSteps({ required Future Function(i1.Migrator m, Schema2 schema) from1To2, required Future Function(i1.Migrator m, Schema3 schema) from2To3, required Future Function(i1.Migrator m, Schema4 schema) from3To4, + required Future Function(i1.Migrator m, Schema5 schema) from4To5, }) { return (currentVersion, database) async { switch (currentVersion) { @@ -1926,6 +2409,11 @@ i0.MigrationStepWithVersion migrationSteps({ final migrator = i1.Migrator(database, schema); await from3To4(migrator, schema); return 4; + case 4: + final schema = Schema5(database: database); + final migrator = i1.Migrator(database, schema); + await from4To5(migrator, schema); + return 5; default: throw ArgumentError.value('Unknown migration from $currentVersion'); } @@ -1936,10 +2424,12 @@ i1.OnUpgrade stepByStep({ required Future Function(i1.Migrator m, Schema2 schema) from1To2, required Future Function(i1.Migrator m, Schema3 schema) from2To3, required Future Function(i1.Migrator m, Schema4 schema) from3To4, + required Future Function(i1.Migrator m, Schema5 schema) from4To5, }) => i0.VersionedSchema.stepByStepHelper( step: migrationSteps( from1To2: from1To2, from2To3: from2To3, from3To4: from3To4, + from4To5: from4To5, )); diff --git a/services/celest_cloud_auth/lib/src/database/auth_database_accessors.dart b/services/celest_cloud_auth/lib/src/database/auth_database_accessors.dart index 290e71f45..e5cbe5d76 100644 --- a/services/celest_cloud_auth/lib/src/database/auth_database_accessors.dart +++ b/services/celest_cloud_auth/lib/src/database/auth_database_accessors.dart @@ -2,7 +2,6 @@ import 'package:async/async.dart'; import 'package:cedar/ast.dart'; import 'package:cedar/cedar.dart'; import 'package:celest_ast/celest_ast.dart'; -import 'package:celest_cloud_auth/src/authentication/authentication_model.dart'; import 'package:celest_cloud_auth/src/authorization/cedar_interop.dart'; import 'package:celest_cloud_auth/src/authorization/celest_action.dart'; import 'package:celest_cloud_auth/src/authorization/celest_role.dart'; @@ -325,6 +324,9 @@ class CloudAuthDatabaseAccessors extends DatabaseAccessor } }); }, + from4To5: (m, schema) async { + await m.alterTable(TableMigration(schema.cloudAuthSessions)); + }, ); /// The default [MigrationStrategy.onUpgrade] for Cloud Auth. @@ -819,14 +821,6 @@ class CloudAuthDatabaseAccessors extends DatabaseAccessor return getUser(userId: user.userId); }); } - - Future getSession({ - required String sessionId, - }) async { - return cloudAuthCoreDrift - .getSession(sessionId: sessionId) - .getSingleOrNull(); - } } /// Creates a diff of a project's authorization config between two versions. diff --git a/services/celest_cloud_auth/lib/src/database/schema/cloud_auth_core.drift b/services/celest_cloud_auth/lib/src/database/schema/cloud_auth_core.drift index 7c17afd3f..af0ae1189 100644 --- a/services/celest_cloud_auth/lib/src/database/schema/cloud_auth_core.drift +++ b/services/celest_cloud_auth/lib/src/database/schema/cloud_auth_core.drift @@ -73,7 +73,6 @@ CREATE TABLE IF NOT EXISTS cloud_auth_sessions ( create_time `const TimestampType()` NOT NULL DEFAULT (unixepoch('now', 'subsec')), update_time `const TimestampType()`, expire_time `const TimestampType()` NOT NULL, - cancel_time `const TimestampType()`, CONSTRAINT cloud_auth_sessions_user_fk FOREIGN KEY (user_id) REFERENCES cloud_auth_users(user_id) ON UPDATE CASCADE ON DELETE CASCADE @@ -240,7 +239,6 @@ createSession: state, ip_address, expire_time, - cancel_time, external_session_id ) VALUES ( @@ -252,7 +250,6 @@ createSession: :state, :ip_address, :expire_time, - :cancel_time, :external_session_id ) RETURNING *; @@ -260,20 +257,16 @@ createSession: -- Retrieves the auth session for the given ID. getSession: SELECT * FROM cloud_auth_sessions - WHERE - ( - cloud_auth_sessions.session_id = :session_id - OR cloud_auth_sessions.external_session_id = :session_id - ) - AND cloud_auth_sessions.expire_time > unixepoch('now', 'subsec') - AND cloud_auth_sessions.cancel_time IS NULL; + WHERE cloud_auth_sessions.session_id = :session_id + OR cloud_auth_sessions.external_session_id = :session_id; -- Updates the state of the auth session for the given ID. updateSession: UPDATE cloud_auth_sessions SET state = :state, - user_id = :user_id + user_id = :user_id, + expire_time = :expire_time WHERE session_id = :session_id OR external_session_id = :session_id @@ -286,14 +279,6 @@ deleteSession: session_id = :session_id OR external_session_id = :session_id; --- Cancels the auth session for the given ID. -cancelSession: - UPDATE cloud_auth_sessions - SET cancel_time = unixepoch('now', 'subsec') - WHERE - session_id = :session_id - OR external_session_id = :session_id; - -- Creates a cork in the database. createCork: INSERT INTO cloud_auth_corks( diff --git a/services/celest_cloud_auth/lib/src/database/schema/cloud_auth_core.drift.dart b/services/celest_cloud_auth/lib/src/database/schema/cloud_auth_core.drift.dart index 1a84aba74..b4dc74a1d 100644 --- a/services/celest_cloud_auth/lib/src/database/schema/cloud_auth_core.drift.dart +++ b/services/celest_cloud_auth/lib/src/database/schema/cloud_auth_core.drift.dart @@ -215,7 +215,6 @@ typedef $CloudAuthSessionsCreateCompanionBuilder = i3.CloudAuthSessionsCompanion i0.Value createTime, i0.Value updateTime, required DateTime expireTime, - i0.Value cancelTime, }); typedef $CloudAuthSessionsUpdateCompanionBuilder = i3.CloudAuthSessionsCompanion Function({ @@ -231,7 +230,6 @@ typedef $CloudAuthSessionsUpdateCompanionBuilder = i3.CloudAuthSessionsCompanion i0.Value createTime, i0.Value updateTime, i0.Value expireTime, - i0.Value cancelTime, }); class $CloudAuthSessionsFilterComposer @@ -289,9 +287,6 @@ class $CloudAuthSessionsFilterComposer i0.ColumnFilters get expireTime => $composableBuilder( column: $table.expireTime, builder: (column) => i0.ColumnFilters(column)); - - i0.ColumnFilters get cancelTime => $composableBuilder( - column: $table.cancelTime, builder: (column) => i0.ColumnFilters(column)); } class $CloudAuthSessionsOrderingComposer @@ -348,10 +343,6 @@ class $CloudAuthSessionsOrderingComposer i0.ColumnOrderings get expireTime => $composableBuilder( column: $table.expireTime, builder: (column) => i0.ColumnOrderings(column)); - - i0.ColumnOrderings get cancelTime => $composableBuilder( - column: $table.cancelTime, - builder: (column) => i0.ColumnOrderings(column)); } class $CloudAuthSessionsAnnotationComposer @@ -401,9 +392,6 @@ class $CloudAuthSessionsAnnotationComposer i0.GeneratedColumn get expireTime => $composableBuilder( column: $table.expireTime, builder: (column) => column); - - i0.GeneratedColumn get cancelTime => $composableBuilder( - column: $table.cancelTime, builder: (column) => column); } class $CloudAuthSessionsTableManager extends i0.RootTableManager< @@ -446,7 +434,6 @@ class $CloudAuthSessionsTableManager extends i0.RootTableManager< i0.Value createTime = const i0.Value.absent(), i0.Value updateTime = const i0.Value.absent(), i0.Value expireTime = const i0.Value.absent(), - i0.Value cancelTime = const i0.Value.absent(), }) => i3.CloudAuthSessionsCompanion( rowid: rowid, @@ -461,7 +448,6 @@ class $CloudAuthSessionsTableManager extends i0.RootTableManager< createTime: createTime, updateTime: updateTime, expireTime: expireTime, - cancelTime: cancelTime, ), createCompanionCallback: ({ i0.Value rowid = const i0.Value.absent(), @@ -476,7 +462,6 @@ class $CloudAuthSessionsTableManager extends i0.RootTableManager< i0.Value createTime = const i0.Value.absent(), i0.Value updateTime = const i0.Value.absent(), required DateTime expireTime, - i0.Value cancelTime = const i0.Value.absent(), }) => i3.CloudAuthSessionsCompanion.insert( rowid: rowid, @@ -491,7 +476,6 @@ class $CloudAuthSessionsTableManager extends i0.RootTableManager< createTime: createTime, updateTime: updateTime, expireTime: expireTime, - cancelTime: cancelTime, ), withReferenceMapper: (p0) => p0 .map((e) => (e.readTable(table), i0.BaseReferences(db, table, e))) @@ -1225,11 +1209,6 @@ class CloudAuthSessions extends i0.Table type: const i5.TimestampType(), requiredDuringInsert: true, $customConstraints: 'NOT NULL'); - late final i0.GeneratedColumn cancelTime = - i0.GeneratedColumn('cancel_time', aliasedName, true, - type: const i5.TimestampType(), - requiredDuringInsert: false, - $customConstraints: ''); @override List get $columns => [ rowid, @@ -1243,8 +1222,7 @@ class CloudAuthSessions extends i0.Table externalSessionId, createTime, updateTime, - expireTime, - cancelTime + expireTime ]; @override String get aliasedName => _alias ?? actualTableName; @@ -1320,7 +1298,6 @@ class CloudAuthSessionsCompanion extends i0.UpdateCompanion { final i0.Value createTime; final i0.Value updateTime; final i0.Value expireTime; - final i0.Value cancelTime; const CloudAuthSessionsCompanion({ this.rowid = const i0.Value.absent(), this.sessionId = const i0.Value.absent(), @@ -1334,7 +1311,6 @@ class CloudAuthSessionsCompanion extends i0.UpdateCompanion { this.createTime = const i0.Value.absent(), this.updateTime = const i0.Value.absent(), this.expireTime = const i0.Value.absent(), - this.cancelTime = const i0.Value.absent(), }); CloudAuthSessionsCompanion.insert({ this.rowid = const i0.Value.absent(), @@ -1349,7 +1325,6 @@ class CloudAuthSessionsCompanion extends i0.UpdateCompanion { this.createTime = const i0.Value.absent(), this.updateTime = const i0.Value.absent(), required DateTime expireTime, - this.cancelTime = const i0.Value.absent(), }) : sessionId = i0.Value(sessionId), cryptoKeyId = i0.Value(cryptoKeyId), userId = i0.Value(userId), @@ -1368,7 +1343,6 @@ class CloudAuthSessionsCompanion extends i0.UpdateCompanion { i0.Expression? createTime, i0.Expression? updateTime, i0.Expression? expireTime, - i0.Expression? cancelTime, }) { return i0.RawValuesInsertable({ if (rowid != null) 'rowid': rowid, @@ -1384,7 +1358,6 @@ class CloudAuthSessionsCompanion extends i0.UpdateCompanion { if (createTime != null) 'create_time': createTime, if (updateTime != null) 'update_time': updateTime, if (expireTime != null) 'expire_time': expireTime, - if (cancelTime != null) 'cancel_time': cancelTime, }); } @@ -1400,8 +1373,7 @@ class CloudAuthSessionsCompanion extends i0.UpdateCompanion { i0.Value? externalSessionId, i0.Value? createTime, i0.Value? updateTime, - i0.Value? expireTime, - i0.Value? cancelTime}) { + i0.Value? expireTime}) { return i3.CloudAuthSessionsCompanion( rowid: rowid ?? this.rowid, sessionId: sessionId ?? this.sessionId, @@ -1415,7 +1387,6 @@ class CloudAuthSessionsCompanion extends i0.UpdateCompanion { createTime: createTime ?? this.createTime, updateTime: updateTime ?? this.updateTime, expireTime: expireTime ?? this.expireTime, - cancelTime: cancelTime ?? this.cancelTime, ); } @@ -1465,10 +1436,6 @@ class CloudAuthSessionsCompanion extends i0.UpdateCompanion { map['expire_time'] = i0.Variable(expireTime.value, const i5.TimestampType()); } - if (cancelTime.present) { - map['cancel_time'] = - i0.Variable(cancelTime.value, const i5.TimestampType()); - } return map; } @@ -1486,8 +1453,7 @@ class CloudAuthSessionsCompanion extends i0.UpdateCompanion { ..write('externalSessionId: $externalSessionId, ') ..write('createTime: $createTime, ') ..write('updateTime: $updateTime, ') - ..write('expireTime: $expireTime, ') - ..write('cancelTime: $cancelTime') + ..write('expireTime: $expireTime') ..write(')')) .toString(); } @@ -2395,10 +2361,9 @@ class CloudAuthCoreDrift extends i7.ModularAccessor { i4.SessionState? state, String? ipAddress, required DateTime expireTime, - DateTime? cancelTime, String? externalSessionId}) { return customWriteReturning( - 'INSERT INTO cloud_auth_sessions (session_id, crypto_key_id, user_id, client_info, authentication_factor, state, ip_address, expire_time, cancel_time, external_session_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) RETURNING *', + 'INSERT INTO cloud_auth_sessions (session_id, crypto_key_id, user_id, client_info, authentication_factor, state, ip_address, expire_time, external_session_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) RETURNING *', variables: [ i0.Variable(sessionId), i0.Variable(cryptoKeyId), @@ -2412,7 +2377,6 @@ class CloudAuthCoreDrift extends i7.ModularAccessor { i3.CloudAuthSessions.$converterstaten.toSql(state)), i0.Variable(ipAddress), i0.Variable(expireTime, const i5.TimestampType()), - i0.Variable(cancelTime, const i5.TimestampType()), i0.Variable(externalSessionId) ], updates: { @@ -2422,7 +2386,7 @@ class CloudAuthCoreDrift extends i7.ModularAccessor { i0.Selectable getSession({String? sessionId}) { return customSelect( - 'SELECT * FROM cloud_auth_sessions WHERE(cloud_auth_sessions.session_id = ?1 OR cloud_auth_sessions.external_session_id = ?1)AND cloud_auth_sessions.expire_time > unixepoch(\'now\', \'subsec\') AND cloud_auth_sessions.cancel_time IS NULL', + 'SELECT * FROM cloud_auth_sessions WHERE cloud_auth_sessions.session_id = ?1 OR cloud_auth_sessions.external_session_id = ?1', variables: [ i0.Variable(sessionId) ], @@ -2432,13 +2396,17 @@ class CloudAuthCoreDrift extends i7.ModularAccessor { } i8.Future> updateSession( - {i4.SessionState? state, required String userId, String? sessionId}) { + {i4.SessionState? state, + required String userId, + required DateTime expireTime, + String? sessionId}) { return customWriteReturning( - 'UPDATE cloud_auth_sessions SET state = ?1, user_id = ?2 WHERE session_id = ?3 OR external_session_id = ?3 RETURNING *', + 'UPDATE cloud_auth_sessions SET state = ?1, user_id = ?2, expire_time = ?3 WHERE session_id = ?4 OR external_session_id = ?4 RETURNING *', variables: [ i0.Variable( i3.CloudAuthSessions.$converterstaten.toSql(state)), i0.Variable(userId), + i0.Variable(expireTime, const i5.TimestampType()), i0.Variable(sessionId) ], updates: {cloudAuthSessions}, @@ -2455,15 +2423,6 @@ class CloudAuthCoreDrift extends i7.ModularAccessor { ); } - Future cancelSession({String? sessionId}) { - return customUpdate( - 'UPDATE cloud_auth_sessions SET cancel_time = unixepoch(\'now\', \'subsec\') WHERE session_id = ?1 OR external_session_id = ?1', - variables: [i0.Variable(sessionId)], - updates: {cloudAuthSessions}, - updateKind: i0.UpdateKind.update, - ); - } - Future createCork( {required i2.Uint8List corkId, required i2.Uint8List cryptoKeyId, diff --git a/services/celest_cloud_auth/lib/src/http/cookie_cork.dart b/services/celest_cloud_auth/lib/src/http/cookie_cork.dart index 2afdb42ab..fe878a4db 100644 --- a/services/celest_cloud_auth/lib/src/http/cookie_cork.dart +++ b/services/celest_cloud_auth/lib/src/http/cookie_cork.dart @@ -1,15 +1,21 @@ import 'dart:io'; +import 'package:cedar/ast.dart'; import 'package:celest_cloud_auth/src/context.dart'; +import 'package:celest_cloud_auth/src/sessions/sessions_repository.dart'; import 'package:clock/clock.dart'; import 'package:corks_cedar/corks_cedar.dart'; /// A wrapper over a [Cookie] for corks. extension type Corkie._(Cookie cookie) implements Cookie { - Corkie.set(Cork cork) + Corkie.set(CedarCork cork) : this._create( cork.toString(), - expiration: clock.now().add(const Duration(days: 30)), + expiration: switch (cork.claims?.attributes['expireTime']) { + LongValue(:final value) => + DateTime.fromMillisecondsSinceEpoch(value.toInt()), + _ => clock.now().add(SessionsRepository.postAuthSessionDuration), + }, ); Corkie.clear() : this._create('', expiration: clock.now()); diff --git a/services/celest_cloud_auth/lib/src/http/http_helpers.dart b/services/celest_cloud_auth/lib/src/http/http_helpers.dart index bdf2c764f..81ae0b102 100644 --- a/services/celest_cloud_auth/lib/src/http/http_helpers.dart +++ b/services/celest_cloud_auth/lib/src/http/http_helpers.dart @@ -40,7 +40,7 @@ extension ResponseHelpers on Response { } /// Adds a `Set-Cookie` header with the given [cork]. - Response setCork(Cork cork) { + Response setCork(CedarCork cork) { return setCookie(Corkie.set(cork)); } diff --git a/services/celest_cloud_auth/lib/src/sessions/sessions_repository.dart b/services/celest_cloud_auth/lib/src/sessions/sessions_repository.dart index b91170edb..a3d6c4421 100644 --- a/services/celest_cloud_auth/lib/src/sessions/sessions_repository.dart +++ b/services/celest_cloud_auth/lib/src/sessions/sessions_repository.dart @@ -4,6 +4,7 @@ import 'package:celest_cloud_auth/src/crypto/crypto_key_repository.dart'; import 'package:celest_cloud_auth/src/database/auth_database_accessors.dart'; import 'package:celest_cloud_auth/src/users/users_repository.dart'; import 'package:celest_cloud_auth/src/util/typeid.dart'; +import 'package:clock/clock.dart'; import 'package:drift/drift.dart'; typedef _Deps = ({ @@ -31,15 +32,18 @@ extension type SessionsRepository._(_Deps _deps) { CryptoKeyRepository get _cryptoKeys => _deps.cryptoKeys; UsersRepository get _users => _deps.users; + static const Duration preAuthSessionDuration = Duration(minutes: 15); + static const Duration postAuthSessionDuration = Duration(days: 30); + Future createSession({ required String? userId, required AuthenticationFactor factor, SessionClient? clientInfo, - DateTime? expireTime, String? ipAddress, + Duration sessionDuration = preAuthSessionDuration, }) { final sessionId = TypeId(); - expireTime ??= DateTime.timestamp().add(const Duration(minutes: 15)); + final expireTime = clock.now().add(sessionDuration); return _db.transaction(() async { final keyData = await _cryptoKeys.mintHmacKey( cryptoKeyId: sessionId.uuid.value, @@ -61,7 +65,7 @@ extension type SessionsRepository._(_Deps _deps) { sessionId: sessionId.encoded, cryptoKeyId: keyData.cryptoKeyId, userId: userId!, - expireTime: expireTime!, + expireTime: expireTime, authenticationFactor: factor, clientInfo: clientInfo, ipAddress: ipAddress, @@ -75,20 +79,44 @@ extension type SessionsRepository._(_Deps _deps) { }); } + Future getSession({ + required TypeId sessionId, + }) async { + final session = await _db.cloudAuthCoreDrift + .getSession(sessionId: sessionId.encoded) + .getSingleOrNull(); + if (session == null) { + return null; + } + if (session.expireTime.isBefore(clock.now())) { + return null; + } + return session; + } + Future updateSession({ required Session session, SessionState? state, String? userId, + Duration sessionDuration = preAuthSessionDuration, }) { return _db.transaction(() async { - final sessionToken = session.sessionToken; session = (await _db.cloudAuthCoreDrift.updateSession( sessionId: session.sessionId.encoded, state: state ?? session.state, userId: userId ?? session.userId, + expireTime: clock.now().add(sessionDuration), )) .first; - return session.copyWith(sessionToken: sessionToken); + final user = await _users.getUser(userId: session.userId); + if (user == null) { + throw InternalServerError('User not found: ${session.userId}'); + } + final sessionToken = await _corks.createCork( + session: session, + user: user, + ); + return session.copyWith(sessionToken: sessionToken.toString()); }); } diff --git a/services/celest_cloud_auth/lib/src/users/users_service.dart b/services/celest_cloud_auth/lib/src/users/users_service.dart index 58fd38ba0..b211ff5d4 100644 --- a/services/celest_cloud_auth/lib/src/users/users_service.dart +++ b/services/celest_cloud_auth/lib/src/users/users_service.dart @@ -8,6 +8,7 @@ import 'package:celest_cloud_auth/src/authorization/authorizer.dart'; import 'package:celest_cloud_auth/src/authorization/celest_action.dart'; import 'package:celest_cloud_auth/src/authorization/corks_repository.dart'; import 'package:celest_cloud_auth/src/context.dart'; +import 'package:celest_cloud_auth/src/crypto/crypto_key_repository.dart'; import 'package:celest_cloud_auth/src/database/auth_database_accessors.dart'; import 'package:celest_cloud_auth/src/database/schema/cloud_auth_users.drift.dart'; import 'package:celest_cloud_auth/src/http/http_helpers.dart'; @@ -15,7 +16,9 @@ import 'package:celest_cloud_auth/src/model/interop.dart'; import 'package:celest_cloud_auth/src/model/order_by.dart'; import 'package:celest_cloud_auth/src/model/page_token.dart'; import 'package:celest_cloud_auth/src/model/route_map.dart'; +import 'package:celest_cloud_auth/src/users/users_repository.dart'; import 'package:celest_core/celest_core.dart'; +import 'package:clock/clock.dart'; import 'package:drift/drift.dart'; import 'package:meta/meta.dart'; import 'package:shelf/shelf.dart'; @@ -25,6 +28,8 @@ typedef _Deps = ({ EntityUid issuer, RouteMap routeMap, CorksRepository corks, + CryptoKeyRepository cryptoKeys, + UsersRepository users, CloudAuthDatabaseMixin db, Authorizer authorizer, }); @@ -34,6 +39,8 @@ extension type UsersService._(_Deps _deps) implements Object { required EntityUid issuer, required RouteMap routeMap, required CorksRepository corks, + required CryptoKeyRepository cryptoKeys, + required UsersRepository users, required CloudAuthDatabaseMixin db, required Authorizer authorizer, }) : this._( @@ -41,6 +48,8 @@ extension type UsersService._(_Deps _deps) implements Object { issuer: issuer, routeMap: routeMap, corks: corks, + cryptoKeys: cryptoKeys, + users: users, db: db, authorizer: authorizer, ), @@ -61,6 +70,8 @@ extension type UsersService._(_Deps _deps) implements Object { final requestAuthorizer = AuthorizationMiddleware( routeMap: _deps.routeMap, corks: _deps.corks, + cryptoKeys: _deps.cryptoKeys, + users: _deps.users, db: _deps.db, authorizer: _deps.authorizer, issuer: _deps.issuer, @@ -189,8 +200,8 @@ extension type UsersService._(_Deps _deps) implements Object { final pageOffset = pageData?.offset ?? 0; const defaultPageSize = 10; pageSize ??= defaultPageSize; - final startTime = pageData?.startTime ?? - DateTime.timestamp().add(const Duration(seconds: 1)); + final startTime = + pageData?.startTime ?? clock.now().add(const Duration(seconds: 1)); OrderByClause? orderByClause; if (orderBy != null) { @@ -273,7 +284,7 @@ extension type UsersService._(_Deps _deps) implements Object { familyName: mask('family_name', familyName), timeZone: mask('time_zone', timeZone), languageCode: mask('language_code', languageCode), - updateTime: Value(DateTime.timestamp()), + updateTime: Value(clock.now()), ); await (_db.update(_db.cloudAuthUsers) diff --git a/services/celest_cloud_auth/lib/src/util/typeid.dart b/services/celest_cloud_auth/lib/src/util/typeid.dart index b1c3986e1..5c3196e05 100644 --- a/services/celest_cloud_auth/lib/src/util/typeid.dart +++ b/services/celest_cloud_auth/lib/src/util/typeid.dart @@ -30,6 +30,14 @@ extension type TypeId._(TypeIdData _data) implements Id { } factory TypeId.decode(String encoded) { + final typeId = tryDecode(encoded); + if (typeId == null) { + throw FormatException('Invalid TypeId: $encoded'); + } + return typeId; + } + + static TypeId? tryDecode(String encoded) { final codeUnits = encoded.codeUnits; for (var i = 0; i < codeUnits.length; i++) { const divider = 0x5f; // `_` @@ -43,7 +51,7 @@ extension type TypeId._(TypeIdData _data) implements Id { ); } } - throw FormatException('Invalid TypeId: $encoded'); + return null; } static const Map _knownTypes = { diff --git a/services/celest_cloud_auth/pubspec.yaml b/services/celest_cloud_auth/pubspec.yaml index b67168b9b..7b3791fc9 100644 --- a/services/celest_cloud_auth/pubspec.yaml +++ b/services/celest_cloud_auth/pubspec.yaml @@ -1,6 +1,6 @@ name: celest_cloud_auth description: A Dart-native authentication and authorization service built on Celest, Cedar, and SQLite. -version: 0.3.1 +version: 0.3.2 homepage: https://celest.dev repository: https://github.com/celest-dev/celest/tree/main/services/celest_cloud_auth diff --git a/services/celest_cloud_auth/test/authentication/authentication_service_test.dart b/services/celest_cloud_auth/test/authentication/authentication_service_test.dart index 0535e07a7..3f8c71bb2 100644 --- a/services/celest_cloud_auth/test/authentication/authentication_service_test.dart +++ b/services/celest_cloud_auth/test/authentication/authentication_service_test.dart @@ -1,6 +1,6 @@ import 'dart:math'; -import 'package:cedar/cedar.dart' show EntityUid; +import 'package:cedar/ast.dart'; import 'package:celest_cloud/celest_cloud.dart' as pb; import 'package:celest_cloud_auth/src/authentication/authentication_model.dart'; import 'package:celest_cloud_auth/src/model/interop.dart'; @@ -76,6 +76,11 @@ void main() { ); check(session.sessionToken).isNotNull(); + final sessionCork = CedarCork.parse(session.sessionToken!); + final expireTime = + (sessionCork.claims!.attributes['expireTime'] as LongValue) + .value + .toInt(); check(session.state) .isA() .has((s) => s.factor, 'factor') @@ -83,6 +88,7 @@ void main() { final (to: _, :code) = tester.lastSentCode!; + await Future.delayed(const Duration(seconds: 1)); final result = await tester.authenticationService.continueSession( sessionId: session.sessionId, sessionToken: session.sessionToken!, @@ -106,7 +112,19 @@ void main() { ?.parents .contains(EntityUid.of('Celest::User', s.user.userId)), 'cork <: user', - ).isNotNull().isTrue(); + ).isNotNull().isTrue() + ..has((s) => s.cork.toString(), 'cork != original sessionToken').not( + (it) => it.equals(session.sessionToken!), + ); + + check(result.sessionToken).isNotNull(); + check(result.sessionToken).not((it) => it.equals(session.sessionToken)); + final updatedCork = CedarCork.parse(result.sessionToken!); + check(updatedCork.claims!.attributes['expireTime']) + .isNotNull() + .isA() + .has((it) => it.value.toInt(), 'expireTime') + .not((it) => it.equals(expireTime)); }); test('re-authenticate', () async { diff --git a/services/celest_cloud_auth/test/authorization/authorization_middleware_test.dart b/services/celest_cloud_auth/test/authorization/authorization_middleware_test.dart index 8a489d522..317e764e5 100644 --- a/services/celest_cloud_auth/test/authorization/authorization_middleware_test.dart +++ b/services/celest_cloud_auth/test/authorization/authorization_middleware_test.dart @@ -4,7 +4,7 @@ import 'package:test/test.dart'; import '../tester.dart'; void main() { - final tester = AuthorizationTester(persistData: true); + final tester = AuthorizationTester(persistData: false); group('AuthorizationMiddleware', () { tester.setUp(); diff --git a/services/celest_cloud_auth/test/database/auth_database/generated/schema.dart b/services/celest_cloud_auth/test/database/auth_database/generated/schema.dart index 22131b11b..c42542afb 100644 --- a/services/celest_cloud_auth/test/database/auth_database/generated/schema.dart +++ b/services/celest_cloud_auth/test/database/auth_database/generated/schema.dart @@ -7,6 +7,7 @@ import 'schema_v1.dart' as v1; import 'schema_v2.dart' as v2; import 'schema_v3.dart' as v3; import 'schema_v4.dart' as v4; +import 'schema_v5.dart' as v5; class GeneratedHelper implements SchemaInstantiationHelper { @override @@ -20,10 +21,12 @@ class GeneratedHelper implements SchemaInstantiationHelper { return v3.DatabaseAtV3(db); case 4: return v4.DatabaseAtV4(db); + case 5: + return v5.DatabaseAtV5(db); default: throw MissingSchemaException(version, versions); } } - static const versions = const [1, 2, 3, 4]; + static const versions = const [1, 2, 3, 4, 5]; } diff --git a/services/celest_cloud_auth/test/database/auth_database/generated/schema_v5.dart b/services/celest_cloud_auth/test/database/auth_database/generated/schema_v5.dart new file mode 100644 index 000000000..803a99c85 --- /dev/null +++ b/services/celest_cloud_auth/test/database/auth_database/generated/schema_v5.dart @@ -0,0 +1,5403 @@ +// dart format width=80 +// GENERATED CODE, DO NOT EDIT BY HAND. +// ignore_for_file: type=lint +import 'package:drift/drift.dart'; + +class CloudAuthUsers extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthUsers(this.attachedDatabase, [this._alias]); + late final GeneratedColumn userId = GeneratedColumn( + 'user_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + late final GeneratedColumn givenName = GeneratedColumn( + 'given_name', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn familyName = GeneratedColumn( + 'family_name', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn timeZone = GeneratedColumn( + 'time_zone', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn languageCode = GeneratedColumn( + 'language_code', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn createTime = GeneratedColumn( + 'create_time', aliasedName, false, + type: DriftSqlType.double, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT (unixepoch(\'now\', \'subsec\'))', + defaultValue: const CustomExpression('unixepoch(\'now\', \'subsec\')')); + late final GeneratedColumn updateTime = GeneratedColumn( + 'update_time', aliasedName, true, + type: DriftSqlType.double, + requiredDuringInsert: false, + $customConstraints: ''); + @override + List get $columns => [ + userId, + givenName, + familyName, + timeZone, + languageCode, + createTime, + updateTime + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_users'; + @override + Set get $primaryKey => {userId}; + @override + CloudAuthUsersData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthUsersData( + userId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}user_id'])!, + givenName: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}given_name']), + familyName: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}family_name']), + timeZone: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}time_zone']), + languageCode: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}language_code']), + createTime: attachedDatabase.typeMapping + .read(DriftSqlType.double, data['${effectivePrefix}create_time'])!, + updateTime: attachedDatabase.typeMapping + .read(DriftSqlType.double, data['${effectivePrefix}update_time']), + ); + } + + @override + CloudAuthUsers createAlias(String alias) { + return CloudAuthUsers(attachedDatabase, alias); + } + + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthUsersData extends DataClass + implements Insertable { + final String userId; + final String? givenName; + final String? familyName; + final String? timeZone; + final String? languageCode; + final double createTime; + final double? updateTime; + const CloudAuthUsersData( + {required this.userId, + this.givenName, + this.familyName, + this.timeZone, + this.languageCode, + required this.createTime, + this.updateTime}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['user_id'] = Variable(userId); + if (!nullToAbsent || givenName != null) { + map['given_name'] = Variable(givenName); + } + if (!nullToAbsent || familyName != null) { + map['family_name'] = Variable(familyName); + } + if (!nullToAbsent || timeZone != null) { + map['time_zone'] = Variable(timeZone); + } + if (!nullToAbsent || languageCode != null) { + map['language_code'] = Variable(languageCode); + } + map['create_time'] = Variable(createTime); + if (!nullToAbsent || updateTime != null) { + map['update_time'] = Variable(updateTime); + } + return map; + } + + factory CloudAuthUsersData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthUsersData( + userId: serializer.fromJson(json['userId']), + givenName: serializer.fromJson(json['givenName']), + familyName: serializer.fromJson(json['familyName']), + timeZone: serializer.fromJson(json['timeZone']), + languageCode: serializer.fromJson(json['languageCode']), + createTime: serializer.fromJson(json['createTime']), + updateTime: serializer.fromJson(json['updateTime']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'userId': serializer.toJson(userId), + 'givenName': serializer.toJson(givenName), + 'familyName': serializer.toJson(familyName), + 'timeZone': serializer.toJson(timeZone), + 'languageCode': serializer.toJson(languageCode), + 'createTime': serializer.toJson(createTime), + 'updateTime': serializer.toJson(updateTime), + }; + } + + CloudAuthUsersData copyWith( + {String? userId, + Value givenName = const Value.absent(), + Value familyName = const Value.absent(), + Value timeZone = const Value.absent(), + Value languageCode = const Value.absent(), + double? createTime, + Value updateTime = const Value.absent()}) => + CloudAuthUsersData( + userId: userId ?? this.userId, + givenName: givenName.present ? givenName.value : this.givenName, + familyName: familyName.present ? familyName.value : this.familyName, + timeZone: timeZone.present ? timeZone.value : this.timeZone, + languageCode: + languageCode.present ? languageCode.value : this.languageCode, + createTime: createTime ?? this.createTime, + updateTime: updateTime.present ? updateTime.value : this.updateTime, + ); + CloudAuthUsersData copyWithCompanion(CloudAuthUsersCompanion data) { + return CloudAuthUsersData( + userId: data.userId.present ? data.userId.value : this.userId, + givenName: data.givenName.present ? data.givenName.value : this.givenName, + familyName: + data.familyName.present ? data.familyName.value : this.familyName, + timeZone: data.timeZone.present ? data.timeZone.value : this.timeZone, + languageCode: data.languageCode.present + ? data.languageCode.value + : this.languageCode, + createTime: + data.createTime.present ? data.createTime.value : this.createTime, + updateTime: + data.updateTime.present ? data.updateTime.value : this.updateTime, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthUsersData(') + ..write('userId: $userId, ') + ..write('givenName: $givenName, ') + ..write('familyName: $familyName, ') + ..write('timeZone: $timeZone, ') + ..write('languageCode: $languageCode, ') + ..write('createTime: $createTime, ') + ..write('updateTime: $updateTime') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(userId, givenName, familyName, timeZone, + languageCode, createTime, updateTime); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthUsersData && + other.userId == this.userId && + other.givenName == this.givenName && + other.familyName == this.familyName && + other.timeZone == this.timeZone && + other.languageCode == this.languageCode && + other.createTime == this.createTime && + other.updateTime == this.updateTime); +} + +class CloudAuthUsersCompanion extends UpdateCompanion { + final Value userId; + final Value givenName; + final Value familyName; + final Value timeZone; + final Value languageCode; + final Value createTime; + final Value updateTime; + final Value rowid; + const CloudAuthUsersCompanion({ + this.userId = const Value.absent(), + this.givenName = const Value.absent(), + this.familyName = const Value.absent(), + this.timeZone = const Value.absent(), + this.languageCode = const Value.absent(), + this.createTime = const Value.absent(), + this.updateTime = const Value.absent(), + this.rowid = const Value.absent(), + }); + CloudAuthUsersCompanion.insert({ + required String userId, + this.givenName = const Value.absent(), + this.familyName = const Value.absent(), + this.timeZone = const Value.absent(), + this.languageCode = const Value.absent(), + this.createTime = const Value.absent(), + this.updateTime = const Value.absent(), + this.rowid = const Value.absent(), + }) : userId = Value(userId); + static Insertable custom({ + Expression? userId, + Expression? givenName, + Expression? familyName, + Expression? timeZone, + Expression? languageCode, + Expression? createTime, + Expression? updateTime, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (userId != null) 'user_id': userId, + if (givenName != null) 'given_name': givenName, + if (familyName != null) 'family_name': familyName, + if (timeZone != null) 'time_zone': timeZone, + if (languageCode != null) 'language_code': languageCode, + if (createTime != null) 'create_time': createTime, + if (updateTime != null) 'update_time': updateTime, + if (rowid != null) 'rowid': rowid, + }); + } + + CloudAuthUsersCompanion copyWith( + {Value? userId, + Value? givenName, + Value? familyName, + Value? timeZone, + Value? languageCode, + Value? createTime, + Value? updateTime, + Value? rowid}) { + return CloudAuthUsersCompanion( + userId: userId ?? this.userId, + givenName: givenName ?? this.givenName, + familyName: familyName ?? this.familyName, + timeZone: timeZone ?? this.timeZone, + languageCode: languageCode ?? this.languageCode, + createTime: createTime ?? this.createTime, + updateTime: updateTime ?? this.updateTime, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (userId.present) { + map['user_id'] = Variable(userId.value); + } + if (givenName.present) { + map['given_name'] = Variable(givenName.value); + } + if (familyName.present) { + map['family_name'] = Variable(familyName.value); + } + if (timeZone.present) { + map['time_zone'] = Variable(timeZone.value); + } + if (languageCode.present) { + map['language_code'] = Variable(languageCode.value); + } + if (createTime.present) { + map['create_time'] = Variable(createTime.value); + } + if (updateTime.present) { + map['update_time'] = Variable(updateTime.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthUsersCompanion(') + ..write('userId: $userId, ') + ..write('givenName: $givenName, ') + ..write('familyName: $familyName, ') + ..write('timeZone: $timeZone, ') + ..write('languageCode: $languageCode, ') + ..write('createTime: $createTime, ') + ..write('updateTime: $updateTime, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CedarTypes extends Table with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CedarTypes(this.attachedDatabase, [this._alias]); + late final GeneratedColumn fqn = GeneratedColumn( + 'fqn', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + @override + List get $columns => [fqn]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cedar_types'; + @override + Set get $primaryKey => {fqn}; + @override + CedarTypesData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CedarTypesData( + fqn: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}fqn'])!, + ); + } + + @override + CedarTypes createAlias(String alias) { + return CedarTypes(attachedDatabase, alias); + } + + @override + bool get dontWriteConstraints => true; +} + +class CedarTypesData extends DataClass implements Insertable { + final String fqn; + const CedarTypesData({required this.fqn}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['fqn'] = Variable(fqn); + return map; + } + + factory CedarTypesData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CedarTypesData( + fqn: serializer.fromJson(json['fqn']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'fqn': serializer.toJson(fqn), + }; + } + + CedarTypesData copyWith({String? fqn}) => CedarTypesData( + fqn: fqn ?? this.fqn, + ); + CedarTypesData copyWithCompanion(CedarTypesCompanion data) { + return CedarTypesData( + fqn: data.fqn.present ? data.fqn.value : this.fqn, + ); + } + + @override + String toString() { + return (StringBuffer('CedarTypesData(') + ..write('fqn: $fqn') + ..write(')')) + .toString(); + } + + @override + int get hashCode => fqn.hashCode; + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CedarTypesData && other.fqn == this.fqn); +} + +class CedarTypesCompanion extends UpdateCompanion { + final Value fqn; + final Value rowid; + const CedarTypesCompanion({ + this.fqn = const Value.absent(), + this.rowid = const Value.absent(), + }); + CedarTypesCompanion.insert({ + required String fqn, + this.rowid = const Value.absent(), + }) : fqn = Value(fqn); + static Insertable custom({ + Expression? fqn, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (fqn != null) 'fqn': fqn, + if (rowid != null) 'rowid': rowid, + }); + } + + CedarTypesCompanion copyWith({Value? fqn, Value? rowid}) { + return CedarTypesCompanion( + fqn: fqn ?? this.fqn, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (fqn.present) { + map['fqn'] = Variable(fqn.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CedarTypesCompanion(') + ..write('fqn: $fqn, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CedarEntities extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CedarEntities(this.attachedDatabase, [this._alias]); + late final GeneratedColumn entityType = GeneratedColumn( + 'entity_type', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL REFERENCES cedar_types(fqn)'); + late final GeneratedColumn entityId = GeneratedColumn( + 'entity_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn attributeJson = GeneratedColumn( + 'attribute_json', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT \'{}\'', + defaultValue: const CustomExpression('\'{}\'')); + late final GeneratedColumn entityJson = GeneratedColumn( + 'entity_json', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: + 'NOT NULL GENERATED ALWAYS AS (json_object(\'type\', entity_type, \'id\', entity_id)) VIRTUAL'); + @override + List get $columns => + [entityType, entityId, attributeJson, entityJson]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cedar_entities'; + @override + Set get $primaryKey => {entityType, entityId}; + @override + CedarEntitiesData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CedarEntitiesData( + entityType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}entity_type'])!, + entityId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}entity_id'])!, + attributeJson: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}attribute_json'])!, + entityJson: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}entity_json'])!, + ); + } + + @override + CedarEntities createAlias(String alias) { + return CedarEntities(attachedDatabase, alias); + } + + @override + bool get withoutRowId => true; + @override + List get customConstraints => const [ + 'CONSTRAINT cedar_entities_pk PRIMARY KEY(entity_type, entity_id)ON CONFLICT IGNORE' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CedarEntitiesData extends DataClass + implements Insertable { + final String entityType; + final String entityId; + final String attributeJson; + final String entityJson; + const CedarEntitiesData( + {required this.entityType, + required this.entityId, + required this.attributeJson, + required this.entityJson}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['entity_type'] = Variable(entityType); + map['entity_id'] = Variable(entityId); + map['attribute_json'] = Variable(attributeJson); + map['entity_json'] = Variable(entityJson); + return map; + } + + factory CedarEntitiesData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CedarEntitiesData( + entityType: serializer.fromJson(json['entityType']), + entityId: serializer.fromJson(json['entityId']), + attributeJson: serializer.fromJson(json['attributeJson']), + entityJson: serializer.fromJson(json['entityJson']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'entityType': serializer.toJson(entityType), + 'entityId': serializer.toJson(entityId), + 'attributeJson': serializer.toJson(attributeJson), + 'entityJson': serializer.toJson(entityJson), + }; + } + + CedarEntitiesData copyWith( + {String? entityType, + String? entityId, + String? attributeJson, + String? entityJson}) => + CedarEntitiesData( + entityType: entityType ?? this.entityType, + entityId: entityId ?? this.entityId, + attributeJson: attributeJson ?? this.attributeJson, + entityJson: entityJson ?? this.entityJson, + ); + CedarEntitiesData copyWithCompanion(CedarEntitiesCompanion data) { + return CedarEntitiesData( + entityType: + data.entityType.present ? data.entityType.value : this.entityType, + entityId: data.entityId.present ? data.entityId.value : this.entityId, + attributeJson: data.attributeJson.present + ? data.attributeJson.value + : this.attributeJson, + entityJson: + data.entityJson.present ? data.entityJson.value : this.entityJson, + ); + } + + @override + String toString() { + return (StringBuffer('CedarEntitiesData(') + ..write('entityType: $entityType, ') + ..write('entityId: $entityId, ') + ..write('attributeJson: $attributeJson, ') + ..write('entityJson: $entityJson') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(entityType, entityId, attributeJson, entityJson); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CedarEntitiesData && + other.entityType == this.entityType && + other.entityId == this.entityId && + other.attributeJson == this.attributeJson && + other.entityJson == this.entityJson); +} + +class CedarEntitiesCompanion extends UpdateCompanion { + final Value entityType; + final Value entityId; + final Value attributeJson; + final Value entityJson; + const CedarEntitiesCompanion({ + this.entityType = const Value.absent(), + this.entityId = const Value.absent(), + this.attributeJson = const Value.absent(), + this.entityJson = const Value.absent(), + }); + CedarEntitiesCompanion.insert({ + required String entityType, + required String entityId, + this.attributeJson = const Value.absent(), + required String entityJson, + }) : entityType = Value(entityType), + entityId = Value(entityId), + entityJson = Value(entityJson); + static Insertable custom({ + Expression? entityType, + Expression? entityId, + Expression? attributeJson, + Expression? entityJson, + }) { + return RawValuesInsertable({ + if (entityType != null) 'entity_type': entityType, + if (entityId != null) 'entity_id': entityId, + if (attributeJson != null) 'attribute_json': attributeJson, + if (entityJson != null) 'entity_json': entityJson, + }); + } + + CedarEntitiesCompanion copyWith( + {Value? entityType, + Value? entityId, + Value? attributeJson, + Value? entityJson}) { + return CedarEntitiesCompanion( + entityType: entityType ?? this.entityType, + entityId: entityId ?? this.entityId, + attributeJson: attributeJson ?? this.attributeJson, + entityJson: entityJson ?? this.entityJson, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (entityType.present) { + map['entity_type'] = Variable(entityType.value); + } + if (entityId.present) { + map['entity_id'] = Variable(entityId.value); + } + if (attributeJson.present) { + map['attribute_json'] = Variable(attributeJson.value); + } + if (entityJson.present) { + map['entity_json'] = Variable(entityJson.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CedarEntitiesCompanion(') + ..write('entityType: $entityType, ') + ..write('entityId: $entityId, ') + ..write('attributeJson: $attributeJson, ') + ..write('entityJson: $entityJson') + ..write(')')) + .toString(); + } +} + +class CedarRelationships extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CedarRelationships(this.attachedDatabase, [this._alias]); + late final GeneratedColumn entityType = GeneratedColumn( + 'entity_type', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn entityId = GeneratedColumn( + 'entity_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn entityJson = GeneratedColumn( + 'entity_json', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: + 'NOT NULL GENERATED ALWAYS AS (json_object(\'type\', entity_type, \'id\', entity_id)) VIRTUAL'); + late final GeneratedColumn parentType = GeneratedColumn( + 'parent_type', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn parentId = GeneratedColumn( + 'parent_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn parentJson = GeneratedColumn( + 'parent_json', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: + 'NOT NULL GENERATED ALWAYS AS (json_object(\'type\', parent_type, \'id\', parent_id)) VIRTUAL'); + @override + List get $columns => + [entityType, entityId, entityJson, parentType, parentId, parentJson]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cedar_relationships'; + @override + Set get $primaryKey => + {entityType, entityId, parentType, parentId}; + @override + CedarRelationshipsData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CedarRelationshipsData( + entityType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}entity_type'])!, + entityId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}entity_id'])!, + entityJson: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}entity_json'])!, + parentType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}parent_type'])!, + parentId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}parent_id'])!, + parentJson: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}parent_json'])!, + ); + } + + @override + CedarRelationships createAlias(String alias) { + return CedarRelationships(attachedDatabase, alias); + } + + @override + bool get withoutRowId => true; + @override + List get customConstraints => const [ + 'CONSTRAINT cedar_relationships_pk PRIMARY KEY(entity_type, entity_id, parent_type, parent_id)ON CONFLICT IGNORE', + 'CONSTRAINT cedar_relationships_fk_entity FOREIGN KEY(entity_type, entity_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE', + 'CONSTRAINT cedar_relationships_fk_parent FOREIGN KEY(parent_type, parent_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CedarRelationshipsData extends DataClass + implements Insertable { + final String entityType; + final String entityId; + final String entityJson; + final String parentType; + final String parentId; + final String parentJson; + const CedarRelationshipsData( + {required this.entityType, + required this.entityId, + required this.entityJson, + required this.parentType, + required this.parentId, + required this.parentJson}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['entity_type'] = Variable(entityType); + map['entity_id'] = Variable(entityId); + map['entity_json'] = Variable(entityJson); + map['parent_type'] = Variable(parentType); + map['parent_id'] = Variable(parentId); + map['parent_json'] = Variable(parentJson); + return map; + } + + factory CedarRelationshipsData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CedarRelationshipsData( + entityType: serializer.fromJson(json['entityType']), + entityId: serializer.fromJson(json['entityId']), + entityJson: serializer.fromJson(json['entityJson']), + parentType: serializer.fromJson(json['parentType']), + parentId: serializer.fromJson(json['parentId']), + parentJson: serializer.fromJson(json['parentJson']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'entityType': serializer.toJson(entityType), + 'entityId': serializer.toJson(entityId), + 'entityJson': serializer.toJson(entityJson), + 'parentType': serializer.toJson(parentType), + 'parentId': serializer.toJson(parentId), + 'parentJson': serializer.toJson(parentJson), + }; + } + + CedarRelationshipsData copyWith( + {String? entityType, + String? entityId, + String? entityJson, + String? parentType, + String? parentId, + String? parentJson}) => + CedarRelationshipsData( + entityType: entityType ?? this.entityType, + entityId: entityId ?? this.entityId, + entityJson: entityJson ?? this.entityJson, + parentType: parentType ?? this.parentType, + parentId: parentId ?? this.parentId, + parentJson: parentJson ?? this.parentJson, + ); + CedarRelationshipsData copyWithCompanion(CedarRelationshipsCompanion data) { + return CedarRelationshipsData( + entityType: + data.entityType.present ? data.entityType.value : this.entityType, + entityId: data.entityId.present ? data.entityId.value : this.entityId, + entityJson: + data.entityJson.present ? data.entityJson.value : this.entityJson, + parentType: + data.parentType.present ? data.parentType.value : this.parentType, + parentId: data.parentId.present ? data.parentId.value : this.parentId, + parentJson: + data.parentJson.present ? data.parentJson.value : this.parentJson, + ); + } + + @override + String toString() { + return (StringBuffer('CedarRelationshipsData(') + ..write('entityType: $entityType, ') + ..write('entityId: $entityId, ') + ..write('entityJson: $entityJson, ') + ..write('parentType: $parentType, ') + ..write('parentId: $parentId, ') + ..write('parentJson: $parentJson') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash( + entityType, entityId, entityJson, parentType, parentId, parentJson); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CedarRelationshipsData && + other.entityType == this.entityType && + other.entityId == this.entityId && + other.entityJson == this.entityJson && + other.parentType == this.parentType && + other.parentId == this.parentId && + other.parentJson == this.parentJson); +} + +class CedarRelationshipsCompanion + extends UpdateCompanion { + final Value entityType; + final Value entityId; + final Value entityJson; + final Value parentType; + final Value parentId; + final Value parentJson; + const CedarRelationshipsCompanion({ + this.entityType = const Value.absent(), + this.entityId = const Value.absent(), + this.entityJson = const Value.absent(), + this.parentType = const Value.absent(), + this.parentId = const Value.absent(), + this.parentJson = const Value.absent(), + }); + CedarRelationshipsCompanion.insert({ + required String entityType, + required String entityId, + required String entityJson, + required String parentType, + required String parentId, + required String parentJson, + }) : entityType = Value(entityType), + entityId = Value(entityId), + entityJson = Value(entityJson), + parentType = Value(parentType), + parentId = Value(parentId), + parentJson = Value(parentJson); + static Insertable custom({ + Expression? entityType, + Expression? entityId, + Expression? entityJson, + Expression? parentType, + Expression? parentId, + Expression? parentJson, + }) { + return RawValuesInsertable({ + if (entityType != null) 'entity_type': entityType, + if (entityId != null) 'entity_id': entityId, + if (entityJson != null) 'entity_json': entityJson, + if (parentType != null) 'parent_type': parentType, + if (parentId != null) 'parent_id': parentId, + if (parentJson != null) 'parent_json': parentJson, + }); + } + + CedarRelationshipsCompanion copyWith( + {Value? entityType, + Value? entityId, + Value? entityJson, + Value? parentType, + Value? parentId, + Value? parentJson}) { + return CedarRelationshipsCompanion( + entityType: entityType ?? this.entityType, + entityId: entityId ?? this.entityId, + entityJson: entityJson ?? this.entityJson, + parentType: parentType ?? this.parentType, + parentId: parentId ?? this.parentId, + parentJson: parentJson ?? this.parentJson, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (entityType.present) { + map['entity_type'] = Variable(entityType.value); + } + if (entityId.present) { + map['entity_id'] = Variable(entityId.value); + } + if (entityJson.present) { + map['entity_json'] = Variable(entityJson.value); + } + if (parentType.present) { + map['parent_type'] = Variable(parentType.value); + } + if (parentId.present) { + map['parent_id'] = Variable(parentId.value); + } + if (parentJson.present) { + map['parent_json'] = Variable(parentJson.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CedarRelationshipsCompanion(') + ..write('entityType: $entityType, ') + ..write('entityId: $entityId, ') + ..write('entityJson: $entityJson, ') + ..write('parentType: $parentType, ') + ..write('parentId: $parentId, ') + ..write('parentJson: $parentJson') + ..write(')')) + .toString(); + } +} + +class CloudAuthUserEmails extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthUserEmails(this.attachedDatabase, [this._alias]); + late final GeneratedColumn userId = GeneratedColumn( + 'user_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn email = GeneratedColumn( + 'email', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn isVerified = GeneratedColumn( + 'is_verified', aliasedName, false, + type: DriftSqlType.bool, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT FALSE', + defaultValue: const CustomExpression('FALSE')); + late final GeneratedColumn isPrimary = GeneratedColumn( + 'is_primary', aliasedName, false, + type: DriftSqlType.bool, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT FALSE', + defaultValue: const CustomExpression('FALSE')); + @override + List get $columns => [userId, email, isVerified, isPrimary]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_user_emails'; + @override + Set get $primaryKey => {userId, email}; + @override + CloudAuthUserEmailsData map(Map data, + {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthUserEmailsData( + userId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}user_id'])!, + email: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}email'])!, + isVerified: attachedDatabase.typeMapping + .read(DriftSqlType.bool, data['${effectivePrefix}is_verified'])!, + isPrimary: attachedDatabase.typeMapping + .read(DriftSqlType.bool, data['${effectivePrefix}is_primary'])!, + ); + } + + @override + CloudAuthUserEmails createAlias(String alias) { + return CloudAuthUserEmails(attachedDatabase, alias); + } + + @override + bool get withoutRowId => true; + @override + List get customConstraints => const [ + 'CONSTRAINT cloud_auth_user_emails_pk PRIMARY KEY(user_id, email)', + 'CONSTRAINT cloud_auth_user_emails_user_fk FOREIGN KEY(user_id)REFERENCES cloud_auth_users(user_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthUserEmailsData extends DataClass + implements Insertable { + final String userId; + final String email; + final bool isVerified; + final bool isPrimary; + const CloudAuthUserEmailsData( + {required this.userId, + required this.email, + required this.isVerified, + required this.isPrimary}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['user_id'] = Variable(userId); + map['email'] = Variable(email); + map['is_verified'] = Variable(isVerified); + map['is_primary'] = Variable(isPrimary); + return map; + } + + factory CloudAuthUserEmailsData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthUserEmailsData( + userId: serializer.fromJson(json['userId']), + email: serializer.fromJson(json['email']), + isVerified: serializer.fromJson(json['isVerified']), + isPrimary: serializer.fromJson(json['isPrimary']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'userId': serializer.toJson(userId), + 'email': serializer.toJson(email), + 'isVerified': serializer.toJson(isVerified), + 'isPrimary': serializer.toJson(isPrimary), + }; + } + + CloudAuthUserEmailsData copyWith( + {String? userId, String? email, bool? isVerified, bool? isPrimary}) => + CloudAuthUserEmailsData( + userId: userId ?? this.userId, + email: email ?? this.email, + isVerified: isVerified ?? this.isVerified, + isPrimary: isPrimary ?? this.isPrimary, + ); + CloudAuthUserEmailsData copyWithCompanion(CloudAuthUserEmailsCompanion data) { + return CloudAuthUserEmailsData( + userId: data.userId.present ? data.userId.value : this.userId, + email: data.email.present ? data.email.value : this.email, + isVerified: + data.isVerified.present ? data.isVerified.value : this.isVerified, + isPrimary: data.isPrimary.present ? data.isPrimary.value : this.isPrimary, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthUserEmailsData(') + ..write('userId: $userId, ') + ..write('email: $email, ') + ..write('isVerified: $isVerified, ') + ..write('isPrimary: $isPrimary') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(userId, email, isVerified, isPrimary); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthUserEmailsData && + other.userId == this.userId && + other.email == this.email && + other.isVerified == this.isVerified && + other.isPrimary == this.isPrimary); +} + +class CloudAuthUserEmailsCompanion + extends UpdateCompanion { + final Value userId; + final Value email; + final Value isVerified; + final Value isPrimary; + const CloudAuthUserEmailsCompanion({ + this.userId = const Value.absent(), + this.email = const Value.absent(), + this.isVerified = const Value.absent(), + this.isPrimary = const Value.absent(), + }); + CloudAuthUserEmailsCompanion.insert({ + required String userId, + required String email, + this.isVerified = const Value.absent(), + this.isPrimary = const Value.absent(), + }) : userId = Value(userId), + email = Value(email); + static Insertable custom({ + Expression? userId, + Expression? email, + Expression? isVerified, + Expression? isPrimary, + }) { + return RawValuesInsertable({ + if (userId != null) 'user_id': userId, + if (email != null) 'email': email, + if (isVerified != null) 'is_verified': isVerified, + if (isPrimary != null) 'is_primary': isPrimary, + }); + } + + CloudAuthUserEmailsCompanion copyWith( + {Value? userId, + Value? email, + Value? isVerified, + Value? isPrimary}) { + return CloudAuthUserEmailsCompanion( + userId: userId ?? this.userId, + email: email ?? this.email, + isVerified: isVerified ?? this.isVerified, + isPrimary: isPrimary ?? this.isPrimary, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (userId.present) { + map['user_id'] = Variable(userId.value); + } + if (email.present) { + map['email'] = Variable(email.value); + } + if (isVerified.present) { + map['is_verified'] = Variable(isVerified.value); + } + if (isPrimary.present) { + map['is_primary'] = Variable(isPrimary.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthUserEmailsCompanion(') + ..write('userId: $userId, ') + ..write('email: $email, ') + ..write('isVerified: $isVerified, ') + ..write('isPrimary: $isPrimary') + ..write(')')) + .toString(); + } +} + +class CloudAuthUserPhoneNumbers extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthUserPhoneNumbers(this.attachedDatabase, [this._alias]); + late final GeneratedColumn userId = GeneratedColumn( + 'user_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn phoneNumber = GeneratedColumn( + 'phone_number', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn isVerified = GeneratedColumn( + 'is_verified', aliasedName, false, + type: DriftSqlType.bool, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT FALSE', + defaultValue: const CustomExpression('FALSE')); + late final GeneratedColumn isPrimary = GeneratedColumn( + 'is_primary', aliasedName, false, + type: DriftSqlType.bool, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT FALSE', + defaultValue: const CustomExpression('FALSE')); + @override + List get $columns => + [userId, phoneNumber, isVerified, isPrimary]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_user_phone_numbers'; + @override + Set get $primaryKey => {userId, phoneNumber}; + @override + CloudAuthUserPhoneNumbersData map(Map data, + {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthUserPhoneNumbersData( + userId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}user_id'])!, + phoneNumber: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}phone_number'])!, + isVerified: attachedDatabase.typeMapping + .read(DriftSqlType.bool, data['${effectivePrefix}is_verified'])!, + isPrimary: attachedDatabase.typeMapping + .read(DriftSqlType.bool, data['${effectivePrefix}is_primary'])!, + ); + } + + @override + CloudAuthUserPhoneNumbers createAlias(String alias) { + return CloudAuthUserPhoneNumbers(attachedDatabase, alias); + } + + @override + bool get withoutRowId => true; + @override + List get customConstraints => const [ + 'CONSTRAINT cloud_auth_user_phone_numbers_pk PRIMARY KEY(user_id, phone_number)', + 'CONSTRAINT cloud_auth_user_phone_numbers_user_fk FOREIGN KEY(user_id)REFERENCES cloud_auth_users(user_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthUserPhoneNumbersData extends DataClass + implements Insertable { + final String userId; + final String phoneNumber; + final bool isVerified; + final bool isPrimary; + const CloudAuthUserPhoneNumbersData( + {required this.userId, + required this.phoneNumber, + required this.isVerified, + required this.isPrimary}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['user_id'] = Variable(userId); + map['phone_number'] = Variable(phoneNumber); + map['is_verified'] = Variable(isVerified); + map['is_primary'] = Variable(isPrimary); + return map; + } + + factory CloudAuthUserPhoneNumbersData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthUserPhoneNumbersData( + userId: serializer.fromJson(json['userId']), + phoneNumber: serializer.fromJson(json['phoneNumber']), + isVerified: serializer.fromJson(json['isVerified']), + isPrimary: serializer.fromJson(json['isPrimary']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'userId': serializer.toJson(userId), + 'phoneNumber': serializer.toJson(phoneNumber), + 'isVerified': serializer.toJson(isVerified), + 'isPrimary': serializer.toJson(isPrimary), + }; + } + + CloudAuthUserPhoneNumbersData copyWith( + {String? userId, + String? phoneNumber, + bool? isVerified, + bool? isPrimary}) => + CloudAuthUserPhoneNumbersData( + userId: userId ?? this.userId, + phoneNumber: phoneNumber ?? this.phoneNumber, + isVerified: isVerified ?? this.isVerified, + isPrimary: isPrimary ?? this.isPrimary, + ); + CloudAuthUserPhoneNumbersData copyWithCompanion( + CloudAuthUserPhoneNumbersCompanion data) { + return CloudAuthUserPhoneNumbersData( + userId: data.userId.present ? data.userId.value : this.userId, + phoneNumber: + data.phoneNumber.present ? data.phoneNumber.value : this.phoneNumber, + isVerified: + data.isVerified.present ? data.isVerified.value : this.isVerified, + isPrimary: data.isPrimary.present ? data.isPrimary.value : this.isPrimary, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthUserPhoneNumbersData(') + ..write('userId: $userId, ') + ..write('phoneNumber: $phoneNumber, ') + ..write('isVerified: $isVerified, ') + ..write('isPrimary: $isPrimary') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(userId, phoneNumber, isVerified, isPrimary); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthUserPhoneNumbersData && + other.userId == this.userId && + other.phoneNumber == this.phoneNumber && + other.isVerified == this.isVerified && + other.isPrimary == this.isPrimary); +} + +class CloudAuthUserPhoneNumbersCompanion + extends UpdateCompanion { + final Value userId; + final Value phoneNumber; + final Value isVerified; + final Value isPrimary; + const CloudAuthUserPhoneNumbersCompanion({ + this.userId = const Value.absent(), + this.phoneNumber = const Value.absent(), + this.isVerified = const Value.absent(), + this.isPrimary = const Value.absent(), + }); + CloudAuthUserPhoneNumbersCompanion.insert({ + required String userId, + required String phoneNumber, + this.isVerified = const Value.absent(), + this.isPrimary = const Value.absent(), + }) : userId = Value(userId), + phoneNumber = Value(phoneNumber); + static Insertable custom({ + Expression? userId, + Expression? phoneNumber, + Expression? isVerified, + Expression? isPrimary, + }) { + return RawValuesInsertable({ + if (userId != null) 'user_id': userId, + if (phoneNumber != null) 'phone_number': phoneNumber, + if (isVerified != null) 'is_verified': isVerified, + if (isPrimary != null) 'is_primary': isPrimary, + }); + } + + CloudAuthUserPhoneNumbersCompanion copyWith( + {Value? userId, + Value? phoneNumber, + Value? isVerified, + Value? isPrimary}) { + return CloudAuthUserPhoneNumbersCompanion( + userId: userId ?? this.userId, + phoneNumber: phoneNumber ?? this.phoneNumber, + isVerified: isVerified ?? this.isVerified, + isPrimary: isPrimary ?? this.isPrimary, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (userId.present) { + map['user_id'] = Variable(userId.value); + } + if (phoneNumber.present) { + map['phone_number'] = Variable(phoneNumber.value); + } + if (isVerified.present) { + map['is_verified'] = Variable(isVerified.value); + } + if (isPrimary.present) { + map['is_primary'] = Variable(isPrimary.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthUserPhoneNumbersCompanion(') + ..write('userId: $userId, ') + ..write('phoneNumber: $phoneNumber, ') + ..write('isVerified: $isVerified, ') + ..write('isPrimary: $isPrimary') + ..write(')')) + .toString(); + } +} + +class CloudAuthProjects extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthProjects(this.attachedDatabase, [this._alias]); + late final GeneratedColumn projectId = GeneratedColumn( + 'project_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + late final GeneratedColumn version = GeneratedColumn( + 'version', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn resolvedAst = + GeneratedColumn('resolved_ast', aliasedName, false, + type: DriftSqlType.blob, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn etag = GeneratedColumn( + 'etag', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + @override + List get $columns => [projectId, version, resolvedAst, etag]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_projects'; + @override + Set get $primaryKey => {projectId}; + @override + CloudAuthProjectsData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthProjectsData( + projectId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}project_id'])!, + version: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}version'])!, + resolvedAst: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}resolved_ast'])!, + etag: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}etag'])!, + ); + } + + @override + CloudAuthProjects createAlias(String alias) { + return CloudAuthProjects(attachedDatabase, alias); + } + + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthProjectsData extends DataClass + implements Insertable { + final String projectId; + final String version; + final Uint8List resolvedAst; + final String etag; + const CloudAuthProjectsData( + {required this.projectId, + required this.version, + required this.resolvedAst, + required this.etag}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['project_id'] = Variable(projectId); + map['version'] = Variable(version); + map['resolved_ast'] = Variable(resolvedAst); + map['etag'] = Variable(etag); + return map; + } + + factory CloudAuthProjectsData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthProjectsData( + projectId: serializer.fromJson(json['projectId']), + version: serializer.fromJson(json['version']), + resolvedAst: serializer.fromJson(json['resolvedAst']), + etag: serializer.fromJson(json['etag']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'projectId': serializer.toJson(projectId), + 'version': serializer.toJson(version), + 'resolvedAst': serializer.toJson(resolvedAst), + 'etag': serializer.toJson(etag), + }; + } + + CloudAuthProjectsData copyWith( + {String? projectId, + String? version, + Uint8List? resolvedAst, + String? etag}) => + CloudAuthProjectsData( + projectId: projectId ?? this.projectId, + version: version ?? this.version, + resolvedAst: resolvedAst ?? this.resolvedAst, + etag: etag ?? this.etag, + ); + CloudAuthProjectsData copyWithCompanion(CloudAuthProjectsCompanion data) { + return CloudAuthProjectsData( + projectId: data.projectId.present ? data.projectId.value : this.projectId, + version: data.version.present ? data.version.value : this.version, + resolvedAst: + data.resolvedAst.present ? data.resolvedAst.value : this.resolvedAst, + etag: data.etag.present ? data.etag.value : this.etag, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthProjectsData(') + ..write('projectId: $projectId, ') + ..write('version: $version, ') + ..write('resolvedAst: $resolvedAst, ') + ..write('etag: $etag') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash( + projectId, version, $driftBlobEquality.hash(resolvedAst), etag); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthProjectsData && + other.projectId == this.projectId && + other.version == this.version && + $driftBlobEquality.equals(other.resolvedAst, this.resolvedAst) && + other.etag == this.etag); +} + +class CloudAuthProjectsCompanion + extends UpdateCompanion { + final Value projectId; + final Value version; + final Value resolvedAst; + final Value etag; + final Value rowid; + const CloudAuthProjectsCompanion({ + this.projectId = const Value.absent(), + this.version = const Value.absent(), + this.resolvedAst = const Value.absent(), + this.etag = const Value.absent(), + this.rowid = const Value.absent(), + }); + CloudAuthProjectsCompanion.insert({ + required String projectId, + required String version, + required Uint8List resolvedAst, + required String etag, + this.rowid = const Value.absent(), + }) : projectId = Value(projectId), + version = Value(version), + resolvedAst = Value(resolvedAst), + etag = Value(etag); + static Insertable custom({ + Expression? projectId, + Expression? version, + Expression? resolvedAst, + Expression? etag, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (projectId != null) 'project_id': projectId, + if (version != null) 'version': version, + if (resolvedAst != null) 'resolved_ast': resolvedAst, + if (etag != null) 'etag': etag, + if (rowid != null) 'rowid': rowid, + }); + } + + CloudAuthProjectsCompanion copyWith( + {Value? projectId, + Value? version, + Value? resolvedAst, + Value? etag, + Value? rowid}) { + return CloudAuthProjectsCompanion( + projectId: projectId ?? this.projectId, + version: version ?? this.version, + resolvedAst: resolvedAst ?? this.resolvedAst, + etag: etag ?? this.etag, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (projectId.present) { + map['project_id'] = Variable(projectId.value); + } + if (version.present) { + map['version'] = Variable(version.value); + } + if (resolvedAst.present) { + map['resolved_ast'] = Variable(resolvedAst.value); + } + if (etag.present) { + map['etag'] = Variable(etag.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthProjectsCompanion(') + ..write('projectId: $projectId, ') + ..write('version: $version, ') + ..write('resolvedAst: $resolvedAst, ') + ..write('etag: $etag, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CloudAuthApis extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthApis(this.attachedDatabase, [this._alias]); + late final GeneratedColumn apiId = GeneratedColumn( + 'api_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + late final GeneratedColumn projectId = GeneratedColumn( + 'project_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn resolvedAst = + GeneratedColumn('resolved_ast', aliasedName, false, + type: DriftSqlType.blob, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn etag = GeneratedColumn( + 'etag', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + @override + List get $columns => [apiId, projectId, resolvedAst, etag]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_apis'; + @override + Set get $primaryKey => {apiId}; + @override + CloudAuthApisData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthApisData( + apiId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}api_id'])!, + projectId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}project_id'])!, + resolvedAst: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}resolved_ast'])!, + etag: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}etag'])!, + ); + } + + @override + CloudAuthApis createAlias(String alias) { + return CloudAuthApis(attachedDatabase, alias); + } + + @override + List get customConstraints => const [ + 'CONSTRAINT cloud_auth_apis_project_fk FOREIGN KEY(project_id)REFERENCES cloud_auth_projects(project_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthApisData extends DataClass + implements Insertable { + final String apiId; + final String projectId; + final Uint8List resolvedAst; + final String etag; + const CloudAuthApisData( + {required this.apiId, + required this.projectId, + required this.resolvedAst, + required this.etag}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['api_id'] = Variable(apiId); + map['project_id'] = Variable(projectId); + map['resolved_ast'] = Variable(resolvedAst); + map['etag'] = Variable(etag); + return map; + } + + factory CloudAuthApisData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthApisData( + apiId: serializer.fromJson(json['apiId']), + projectId: serializer.fromJson(json['projectId']), + resolvedAst: serializer.fromJson(json['resolvedAst']), + etag: serializer.fromJson(json['etag']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'apiId': serializer.toJson(apiId), + 'projectId': serializer.toJson(projectId), + 'resolvedAst': serializer.toJson(resolvedAst), + 'etag': serializer.toJson(etag), + }; + } + + CloudAuthApisData copyWith( + {String? apiId, + String? projectId, + Uint8List? resolvedAst, + String? etag}) => + CloudAuthApisData( + apiId: apiId ?? this.apiId, + projectId: projectId ?? this.projectId, + resolvedAst: resolvedAst ?? this.resolvedAst, + etag: etag ?? this.etag, + ); + CloudAuthApisData copyWithCompanion(CloudAuthApisCompanion data) { + return CloudAuthApisData( + apiId: data.apiId.present ? data.apiId.value : this.apiId, + projectId: data.projectId.present ? data.projectId.value : this.projectId, + resolvedAst: + data.resolvedAst.present ? data.resolvedAst.value : this.resolvedAst, + etag: data.etag.present ? data.etag.value : this.etag, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthApisData(') + ..write('apiId: $apiId, ') + ..write('projectId: $projectId, ') + ..write('resolvedAst: $resolvedAst, ') + ..write('etag: $etag') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(apiId, projectId, $driftBlobEquality.hash(resolvedAst), etag); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthApisData && + other.apiId == this.apiId && + other.projectId == this.projectId && + $driftBlobEquality.equals(other.resolvedAst, this.resolvedAst) && + other.etag == this.etag); +} + +class CloudAuthApisCompanion extends UpdateCompanion { + final Value apiId; + final Value projectId; + final Value resolvedAst; + final Value etag; + final Value rowid; + const CloudAuthApisCompanion({ + this.apiId = const Value.absent(), + this.projectId = const Value.absent(), + this.resolvedAst = const Value.absent(), + this.etag = const Value.absent(), + this.rowid = const Value.absent(), + }); + CloudAuthApisCompanion.insert({ + required String apiId, + required String projectId, + required Uint8List resolvedAst, + required String etag, + this.rowid = const Value.absent(), + }) : apiId = Value(apiId), + projectId = Value(projectId), + resolvedAst = Value(resolvedAst), + etag = Value(etag); + static Insertable custom({ + Expression? apiId, + Expression? projectId, + Expression? resolvedAst, + Expression? etag, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (apiId != null) 'api_id': apiId, + if (projectId != null) 'project_id': projectId, + if (resolvedAst != null) 'resolved_ast': resolvedAst, + if (etag != null) 'etag': etag, + if (rowid != null) 'rowid': rowid, + }); + } + + CloudAuthApisCompanion copyWith( + {Value? apiId, + Value? projectId, + Value? resolvedAst, + Value? etag, + Value? rowid}) { + return CloudAuthApisCompanion( + apiId: apiId ?? this.apiId, + projectId: projectId ?? this.projectId, + resolvedAst: resolvedAst ?? this.resolvedAst, + etag: etag ?? this.etag, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (apiId.present) { + map['api_id'] = Variable(apiId.value); + } + if (projectId.present) { + map['project_id'] = Variable(projectId.value); + } + if (resolvedAst.present) { + map['resolved_ast'] = Variable(resolvedAst.value); + } + if (etag.present) { + map['etag'] = Variable(etag.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthApisCompanion(') + ..write('apiId: $apiId, ') + ..write('projectId: $projectId, ') + ..write('resolvedAst: $resolvedAst, ') + ..write('etag: $etag, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CloudAuthFunctions extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthFunctions(this.attachedDatabase, [this._alias]); + late final GeneratedColumn functionId = GeneratedColumn( + 'function_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + late final GeneratedColumn apiId = GeneratedColumn( + 'api_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn resolvedAst = + GeneratedColumn('resolved_ast', aliasedName, false, + type: DriftSqlType.blob, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn etag = GeneratedColumn( + 'etag', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + @override + List get $columns => [functionId, apiId, resolvedAst, etag]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_functions'; + @override + Set get $primaryKey => {functionId}; + @override + CloudAuthFunctionsData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthFunctionsData( + functionId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}function_id'])!, + apiId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}api_id'])!, + resolvedAst: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}resolved_ast'])!, + etag: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}etag'])!, + ); + } + + @override + CloudAuthFunctions createAlias(String alias) { + return CloudAuthFunctions(attachedDatabase, alias); + } + + @override + List get customConstraints => const [ + 'CONSTRAINT cloud_auth_functions_api_fk FOREIGN KEY(api_id)REFERENCES cloud_auth_apis(api_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthFunctionsData extends DataClass + implements Insertable { + final String functionId; + final String apiId; + final Uint8List resolvedAst; + final String etag; + const CloudAuthFunctionsData( + {required this.functionId, + required this.apiId, + required this.resolvedAst, + required this.etag}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['function_id'] = Variable(functionId); + map['api_id'] = Variable(apiId); + map['resolved_ast'] = Variable(resolvedAst); + map['etag'] = Variable(etag); + return map; + } + + factory CloudAuthFunctionsData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthFunctionsData( + functionId: serializer.fromJson(json['functionId']), + apiId: serializer.fromJson(json['apiId']), + resolvedAst: serializer.fromJson(json['resolvedAst']), + etag: serializer.fromJson(json['etag']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'functionId': serializer.toJson(functionId), + 'apiId': serializer.toJson(apiId), + 'resolvedAst': serializer.toJson(resolvedAst), + 'etag': serializer.toJson(etag), + }; + } + + CloudAuthFunctionsData copyWith( + {String? functionId, + String? apiId, + Uint8List? resolvedAst, + String? etag}) => + CloudAuthFunctionsData( + functionId: functionId ?? this.functionId, + apiId: apiId ?? this.apiId, + resolvedAst: resolvedAst ?? this.resolvedAst, + etag: etag ?? this.etag, + ); + CloudAuthFunctionsData copyWithCompanion(CloudAuthFunctionsCompanion data) { + return CloudAuthFunctionsData( + functionId: + data.functionId.present ? data.functionId.value : this.functionId, + apiId: data.apiId.present ? data.apiId.value : this.apiId, + resolvedAst: + data.resolvedAst.present ? data.resolvedAst.value : this.resolvedAst, + etag: data.etag.present ? data.etag.value : this.etag, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthFunctionsData(') + ..write('functionId: $functionId, ') + ..write('apiId: $apiId, ') + ..write('resolvedAst: $resolvedAst, ') + ..write('etag: $etag') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash( + functionId, apiId, $driftBlobEquality.hash(resolvedAst), etag); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthFunctionsData && + other.functionId == this.functionId && + other.apiId == this.apiId && + $driftBlobEquality.equals(other.resolvedAst, this.resolvedAst) && + other.etag == this.etag); +} + +class CloudAuthFunctionsCompanion + extends UpdateCompanion { + final Value functionId; + final Value apiId; + final Value resolvedAst; + final Value etag; + final Value rowid; + const CloudAuthFunctionsCompanion({ + this.functionId = const Value.absent(), + this.apiId = const Value.absent(), + this.resolvedAst = const Value.absent(), + this.etag = const Value.absent(), + this.rowid = const Value.absent(), + }); + CloudAuthFunctionsCompanion.insert({ + required String functionId, + required String apiId, + required Uint8List resolvedAst, + required String etag, + this.rowid = const Value.absent(), + }) : functionId = Value(functionId), + apiId = Value(apiId), + resolvedAst = Value(resolvedAst), + etag = Value(etag); + static Insertable custom({ + Expression? functionId, + Expression? apiId, + Expression? resolvedAst, + Expression? etag, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (functionId != null) 'function_id': functionId, + if (apiId != null) 'api_id': apiId, + if (resolvedAst != null) 'resolved_ast': resolvedAst, + if (etag != null) 'etag': etag, + if (rowid != null) 'rowid': rowid, + }); + } + + CloudAuthFunctionsCompanion copyWith( + {Value? functionId, + Value? apiId, + Value? resolvedAst, + Value? etag, + Value? rowid}) { + return CloudAuthFunctionsCompanion( + functionId: functionId ?? this.functionId, + apiId: apiId ?? this.apiId, + resolvedAst: resolvedAst ?? this.resolvedAst, + etag: etag ?? this.etag, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (functionId.present) { + map['function_id'] = Variable(functionId.value); + } + if (apiId.present) { + map['api_id'] = Variable(apiId.value); + } + if (resolvedAst.present) { + map['resolved_ast'] = Variable(resolvedAst.value); + } + if (etag.present) { + map['etag'] = Variable(etag.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthFunctionsCompanion(') + ..write('functionId: $functionId, ') + ..write('apiId: $apiId, ') + ..write('resolvedAst: $resolvedAst, ') + ..write('etag: $etag, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CloudAuthMeta extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthMeta(this.attachedDatabase, [this._alias]); + late final GeneratedColumn schemaVersion = GeneratedColumn( + 'schema_version', aliasedName, false, + type: DriftSqlType.int, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL PRIMARY KEY'); + @override + List get $columns => [schemaVersion]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_meta'; + @override + Set get $primaryKey => {schemaVersion}; + @override + CloudAuthMetaData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthMetaData( + schemaVersion: attachedDatabase.typeMapping + .read(DriftSqlType.int, data['${effectivePrefix}schema_version'])!, + ); + } + + @override + CloudAuthMeta createAlias(String alias) { + return CloudAuthMeta(attachedDatabase, alias); + } + + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthMetaData extends DataClass + implements Insertable { + final int schemaVersion; + const CloudAuthMetaData({required this.schemaVersion}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['schema_version'] = Variable(schemaVersion); + return map; + } + + factory CloudAuthMetaData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthMetaData( + schemaVersion: serializer.fromJson(json['schemaVersion']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'schemaVersion': serializer.toJson(schemaVersion), + }; + } + + CloudAuthMetaData copyWith({int? schemaVersion}) => CloudAuthMetaData( + schemaVersion: schemaVersion ?? this.schemaVersion, + ); + CloudAuthMetaData copyWithCompanion(CloudAuthMetaCompanion data) { + return CloudAuthMetaData( + schemaVersion: data.schemaVersion.present + ? data.schemaVersion.value + : this.schemaVersion, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthMetaData(') + ..write('schemaVersion: $schemaVersion') + ..write(')')) + .toString(); + } + + @override + int get hashCode => schemaVersion.hashCode; + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthMetaData && other.schemaVersion == this.schemaVersion); +} + +class CloudAuthMetaCompanion extends UpdateCompanion { + final Value schemaVersion; + const CloudAuthMetaCompanion({ + this.schemaVersion = const Value.absent(), + }); + CloudAuthMetaCompanion.insert({ + this.schemaVersion = const Value.absent(), + }); + static Insertable custom({ + Expression? schemaVersion, + }) { + return RawValuesInsertable({ + if (schemaVersion != null) 'schema_version': schemaVersion, + }); + } + + CloudAuthMetaCompanion copyWith({Value? schemaVersion}) { + return CloudAuthMetaCompanion( + schemaVersion: schemaVersion ?? this.schemaVersion, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (schemaVersion.present) { + map['schema_version'] = Variable(schemaVersion.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthMetaCompanion(') + ..write('schemaVersion: $schemaVersion') + ..write(')')) + .toString(); + } +} + +class CloudAuthCryptoKeys extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthCryptoKeys(this.attachedDatabase, [this._alias]); + late final GeneratedColumn cryptoKeyId = + GeneratedColumn('crypto_key_id', aliasedName, false, + type: DriftSqlType.blob, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + late final GeneratedColumn keyPurpose = GeneratedColumn( + 'key_purpose', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn keyAlgorithm = GeneratedColumn( + 'key_algorithm', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn keyMaterial = + GeneratedColumn('key_material', aliasedName, true, + type: DriftSqlType.blob, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn externalCryptoKeyId = + GeneratedColumn('external_crypto_key_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: 'UNIQUE'); + @override + List get $columns => + [cryptoKeyId, keyPurpose, keyAlgorithm, keyMaterial, externalCryptoKeyId]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_crypto_keys'; + @override + Set get $primaryKey => {cryptoKeyId}; + @override + CloudAuthCryptoKeysData map(Map data, + {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthCryptoKeysData( + cryptoKeyId: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}crypto_key_id'])!, + keyPurpose: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}key_purpose'])!, + keyAlgorithm: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}key_algorithm'])!, + keyMaterial: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}key_material']), + externalCryptoKeyId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}external_crypto_key_id']), + ); + } + + @override + CloudAuthCryptoKeys createAlias(String alias) { + return CloudAuthCryptoKeys(attachedDatabase, alias); + } + + @override + List get customConstraints => const [ + 'CHECK(key_material IS NOT NULL OR external_crypto_key_id IS NOT NULL)' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthCryptoKeysData extends DataClass + implements Insertable { + final Uint8List cryptoKeyId; + final String keyPurpose; + final String keyAlgorithm; + final Uint8List? keyMaterial; + final String? externalCryptoKeyId; + const CloudAuthCryptoKeysData( + {required this.cryptoKeyId, + required this.keyPurpose, + required this.keyAlgorithm, + this.keyMaterial, + this.externalCryptoKeyId}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['crypto_key_id'] = Variable(cryptoKeyId); + map['key_purpose'] = Variable(keyPurpose); + map['key_algorithm'] = Variable(keyAlgorithm); + if (!nullToAbsent || keyMaterial != null) { + map['key_material'] = Variable(keyMaterial); + } + if (!nullToAbsent || externalCryptoKeyId != null) { + map['external_crypto_key_id'] = Variable(externalCryptoKeyId); + } + return map; + } + + factory CloudAuthCryptoKeysData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthCryptoKeysData( + cryptoKeyId: serializer.fromJson(json['cryptoKeyId']), + keyPurpose: serializer.fromJson(json['keyPurpose']), + keyAlgorithm: serializer.fromJson(json['keyAlgorithm']), + keyMaterial: serializer.fromJson(json['keyMaterial']), + externalCryptoKeyId: + serializer.fromJson(json['externalCryptoKeyId']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'cryptoKeyId': serializer.toJson(cryptoKeyId), + 'keyPurpose': serializer.toJson(keyPurpose), + 'keyAlgorithm': serializer.toJson(keyAlgorithm), + 'keyMaterial': serializer.toJson(keyMaterial), + 'externalCryptoKeyId': serializer.toJson(externalCryptoKeyId), + }; + } + + CloudAuthCryptoKeysData copyWith( + {Uint8List? cryptoKeyId, + String? keyPurpose, + String? keyAlgorithm, + Value keyMaterial = const Value.absent(), + Value externalCryptoKeyId = const Value.absent()}) => + CloudAuthCryptoKeysData( + cryptoKeyId: cryptoKeyId ?? this.cryptoKeyId, + keyPurpose: keyPurpose ?? this.keyPurpose, + keyAlgorithm: keyAlgorithm ?? this.keyAlgorithm, + keyMaterial: keyMaterial.present ? keyMaterial.value : this.keyMaterial, + externalCryptoKeyId: externalCryptoKeyId.present + ? externalCryptoKeyId.value + : this.externalCryptoKeyId, + ); + CloudAuthCryptoKeysData copyWithCompanion(CloudAuthCryptoKeysCompanion data) { + return CloudAuthCryptoKeysData( + cryptoKeyId: + data.cryptoKeyId.present ? data.cryptoKeyId.value : this.cryptoKeyId, + keyPurpose: + data.keyPurpose.present ? data.keyPurpose.value : this.keyPurpose, + keyAlgorithm: data.keyAlgorithm.present + ? data.keyAlgorithm.value + : this.keyAlgorithm, + keyMaterial: + data.keyMaterial.present ? data.keyMaterial.value : this.keyMaterial, + externalCryptoKeyId: data.externalCryptoKeyId.present + ? data.externalCryptoKeyId.value + : this.externalCryptoKeyId, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthCryptoKeysData(') + ..write('cryptoKeyId: $cryptoKeyId, ') + ..write('keyPurpose: $keyPurpose, ') + ..write('keyAlgorithm: $keyAlgorithm, ') + ..write('keyMaterial: $keyMaterial, ') + ..write('externalCryptoKeyId: $externalCryptoKeyId') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash( + $driftBlobEquality.hash(cryptoKeyId), + keyPurpose, + keyAlgorithm, + $driftBlobEquality.hash(keyMaterial), + externalCryptoKeyId); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthCryptoKeysData && + $driftBlobEquality.equals(other.cryptoKeyId, this.cryptoKeyId) && + other.keyPurpose == this.keyPurpose && + other.keyAlgorithm == this.keyAlgorithm && + $driftBlobEquality.equals(other.keyMaterial, this.keyMaterial) && + other.externalCryptoKeyId == this.externalCryptoKeyId); +} + +class CloudAuthCryptoKeysCompanion + extends UpdateCompanion { + final Value cryptoKeyId; + final Value keyPurpose; + final Value keyAlgorithm; + final Value keyMaterial; + final Value externalCryptoKeyId; + final Value rowid; + const CloudAuthCryptoKeysCompanion({ + this.cryptoKeyId = const Value.absent(), + this.keyPurpose = const Value.absent(), + this.keyAlgorithm = const Value.absent(), + this.keyMaterial = const Value.absent(), + this.externalCryptoKeyId = const Value.absent(), + this.rowid = const Value.absent(), + }); + CloudAuthCryptoKeysCompanion.insert({ + required Uint8List cryptoKeyId, + required String keyPurpose, + required String keyAlgorithm, + this.keyMaterial = const Value.absent(), + this.externalCryptoKeyId = const Value.absent(), + this.rowid = const Value.absent(), + }) : cryptoKeyId = Value(cryptoKeyId), + keyPurpose = Value(keyPurpose), + keyAlgorithm = Value(keyAlgorithm); + static Insertable custom({ + Expression? cryptoKeyId, + Expression? keyPurpose, + Expression? keyAlgorithm, + Expression? keyMaterial, + Expression? externalCryptoKeyId, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (cryptoKeyId != null) 'crypto_key_id': cryptoKeyId, + if (keyPurpose != null) 'key_purpose': keyPurpose, + if (keyAlgorithm != null) 'key_algorithm': keyAlgorithm, + if (keyMaterial != null) 'key_material': keyMaterial, + if (externalCryptoKeyId != null) + 'external_crypto_key_id': externalCryptoKeyId, + if (rowid != null) 'rowid': rowid, + }); + } + + CloudAuthCryptoKeysCompanion copyWith( + {Value? cryptoKeyId, + Value? keyPurpose, + Value? keyAlgorithm, + Value? keyMaterial, + Value? externalCryptoKeyId, + Value? rowid}) { + return CloudAuthCryptoKeysCompanion( + cryptoKeyId: cryptoKeyId ?? this.cryptoKeyId, + keyPurpose: keyPurpose ?? this.keyPurpose, + keyAlgorithm: keyAlgorithm ?? this.keyAlgorithm, + keyMaterial: keyMaterial ?? this.keyMaterial, + externalCryptoKeyId: externalCryptoKeyId ?? this.externalCryptoKeyId, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (cryptoKeyId.present) { + map['crypto_key_id'] = Variable(cryptoKeyId.value); + } + if (keyPurpose.present) { + map['key_purpose'] = Variable(keyPurpose.value); + } + if (keyAlgorithm.present) { + map['key_algorithm'] = Variable(keyAlgorithm.value); + } + if (keyMaterial.present) { + map['key_material'] = Variable(keyMaterial.value); + } + if (externalCryptoKeyId.present) { + map['external_crypto_key_id'] = + Variable(externalCryptoKeyId.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthCryptoKeysCompanion(') + ..write('cryptoKeyId: $cryptoKeyId, ') + ..write('keyPurpose: $keyPurpose, ') + ..write('keyAlgorithm: $keyAlgorithm, ') + ..write('keyMaterial: $keyMaterial, ') + ..write('externalCryptoKeyId: $externalCryptoKeyId, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CloudAuthSessions extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthSessions(this.attachedDatabase, [this._alias]); + late final GeneratedColumn rowid = GeneratedColumn( + 'rowid', aliasedName, false, + hasAutoIncrement: true, + type: DriftSqlType.int, + requiredDuringInsert: false, + $customConstraints: 'PRIMARY KEY AUTOINCREMENT'); + late final GeneratedColumn sessionId = GeneratedColumn( + 'session_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL UNIQUE'); + late final GeneratedColumn cryptoKeyId = + GeneratedColumn('crypto_key_id', aliasedName, false, + type: DriftSqlType.blob, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn userId = GeneratedColumn( + 'user_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn clientInfo = GeneratedColumn( + 'client_info', aliasedName, true, + type: DriftSqlType.blob, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn authenticationFactor = + GeneratedColumn('authentication_factor', aliasedName, false, + type: DriftSqlType.blob, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn state = GeneratedColumn( + 'state', aliasedName, true, + type: DriftSqlType.blob, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn ipAddress = GeneratedColumn( + 'ip_address', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn externalSessionId = + GeneratedColumn('external_session_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn createTime = GeneratedColumn( + 'create_time', aliasedName, false, + type: DriftSqlType.double, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT (unixepoch(\'now\', \'subsec\'))', + defaultValue: const CustomExpression('unixepoch(\'now\', \'subsec\')')); + late final GeneratedColumn updateTime = GeneratedColumn( + 'update_time', aliasedName, true, + type: DriftSqlType.double, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn expireTime = GeneratedColumn( + 'expire_time', aliasedName, false, + type: DriftSqlType.double, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + @override + List get $columns => [ + rowid, + sessionId, + cryptoKeyId, + userId, + clientInfo, + authenticationFactor, + state, + ipAddress, + externalSessionId, + createTime, + updateTime, + expireTime + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_sessions'; + @override + Set get $primaryKey => {rowid}; + @override + CloudAuthSessionsData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthSessionsData( + rowid: attachedDatabase.typeMapping + .read(DriftSqlType.int, data['${effectivePrefix}rowid'])!, + sessionId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}session_id'])!, + cryptoKeyId: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}crypto_key_id'])!, + userId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}user_id'])!, + clientInfo: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}client_info']), + authenticationFactor: attachedDatabase.typeMapping.read( + DriftSqlType.blob, data['${effectivePrefix}authentication_factor'])!, + state: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}state']), + ipAddress: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}ip_address']), + externalSessionId: attachedDatabase.typeMapping.read( + DriftSqlType.string, data['${effectivePrefix}external_session_id']), + createTime: attachedDatabase.typeMapping + .read(DriftSqlType.double, data['${effectivePrefix}create_time'])!, + updateTime: attachedDatabase.typeMapping + .read(DriftSqlType.double, data['${effectivePrefix}update_time']), + expireTime: attachedDatabase.typeMapping + .read(DriftSqlType.double, data['${effectivePrefix}expire_time'])!, + ); + } + + @override + CloudAuthSessions createAlias(String alias) { + return CloudAuthSessions(attachedDatabase, alias); + } + + @override + List get customConstraints => const [ + 'CONSTRAINT cloud_auth_sessions_user_fk FOREIGN KEY(user_id)REFERENCES cloud_auth_users(user_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + 'CONSTRAINT cloud_auth_sessions_key_fk FOREIGN KEY(crypto_key_id)REFERENCES cloud_auth_crypto_keys(crypto_key_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthSessionsData extends DataClass + implements Insertable { + final int rowid; + final String sessionId; + final Uint8List cryptoKeyId; + final String userId; + final Uint8List? clientInfo; + final Uint8List authenticationFactor; + final Uint8List? state; + final String? ipAddress; + final String? externalSessionId; + final double createTime; + final double? updateTime; + final double expireTime; + const CloudAuthSessionsData( + {required this.rowid, + required this.sessionId, + required this.cryptoKeyId, + required this.userId, + this.clientInfo, + required this.authenticationFactor, + this.state, + this.ipAddress, + this.externalSessionId, + required this.createTime, + this.updateTime, + required this.expireTime}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['rowid'] = Variable(rowid); + map['session_id'] = Variable(sessionId); + map['crypto_key_id'] = Variable(cryptoKeyId); + map['user_id'] = Variable(userId); + if (!nullToAbsent || clientInfo != null) { + map['client_info'] = Variable(clientInfo); + } + map['authentication_factor'] = Variable(authenticationFactor); + if (!nullToAbsent || state != null) { + map['state'] = Variable(state); + } + if (!nullToAbsent || ipAddress != null) { + map['ip_address'] = Variable(ipAddress); + } + if (!nullToAbsent || externalSessionId != null) { + map['external_session_id'] = Variable(externalSessionId); + } + map['create_time'] = Variable(createTime); + if (!nullToAbsent || updateTime != null) { + map['update_time'] = Variable(updateTime); + } + map['expire_time'] = Variable(expireTime); + return map; + } + + factory CloudAuthSessionsData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthSessionsData( + rowid: serializer.fromJson(json['rowid']), + sessionId: serializer.fromJson(json['sessionId']), + cryptoKeyId: serializer.fromJson(json['cryptoKeyId']), + userId: serializer.fromJson(json['userId']), + clientInfo: serializer.fromJson(json['clientInfo']), + authenticationFactor: + serializer.fromJson(json['authenticationFactor']), + state: serializer.fromJson(json['state']), + ipAddress: serializer.fromJson(json['ipAddress']), + externalSessionId: + serializer.fromJson(json['externalSessionId']), + createTime: serializer.fromJson(json['createTime']), + updateTime: serializer.fromJson(json['updateTime']), + expireTime: serializer.fromJson(json['expireTime']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'rowid': serializer.toJson(rowid), + 'sessionId': serializer.toJson(sessionId), + 'cryptoKeyId': serializer.toJson(cryptoKeyId), + 'userId': serializer.toJson(userId), + 'clientInfo': serializer.toJson(clientInfo), + 'authenticationFactor': + serializer.toJson(authenticationFactor), + 'state': serializer.toJson(state), + 'ipAddress': serializer.toJson(ipAddress), + 'externalSessionId': serializer.toJson(externalSessionId), + 'createTime': serializer.toJson(createTime), + 'updateTime': serializer.toJson(updateTime), + 'expireTime': serializer.toJson(expireTime), + }; + } + + CloudAuthSessionsData copyWith( + {int? rowid, + String? sessionId, + Uint8List? cryptoKeyId, + String? userId, + Value clientInfo = const Value.absent(), + Uint8List? authenticationFactor, + Value state = const Value.absent(), + Value ipAddress = const Value.absent(), + Value externalSessionId = const Value.absent(), + double? createTime, + Value updateTime = const Value.absent(), + double? expireTime}) => + CloudAuthSessionsData( + rowid: rowid ?? this.rowid, + sessionId: sessionId ?? this.sessionId, + cryptoKeyId: cryptoKeyId ?? this.cryptoKeyId, + userId: userId ?? this.userId, + clientInfo: clientInfo.present ? clientInfo.value : this.clientInfo, + authenticationFactor: authenticationFactor ?? this.authenticationFactor, + state: state.present ? state.value : this.state, + ipAddress: ipAddress.present ? ipAddress.value : this.ipAddress, + externalSessionId: externalSessionId.present + ? externalSessionId.value + : this.externalSessionId, + createTime: createTime ?? this.createTime, + updateTime: updateTime.present ? updateTime.value : this.updateTime, + expireTime: expireTime ?? this.expireTime, + ); + CloudAuthSessionsData copyWithCompanion(CloudAuthSessionsCompanion data) { + return CloudAuthSessionsData( + rowid: data.rowid.present ? data.rowid.value : this.rowid, + sessionId: data.sessionId.present ? data.sessionId.value : this.sessionId, + cryptoKeyId: + data.cryptoKeyId.present ? data.cryptoKeyId.value : this.cryptoKeyId, + userId: data.userId.present ? data.userId.value : this.userId, + clientInfo: + data.clientInfo.present ? data.clientInfo.value : this.clientInfo, + authenticationFactor: data.authenticationFactor.present + ? data.authenticationFactor.value + : this.authenticationFactor, + state: data.state.present ? data.state.value : this.state, + ipAddress: data.ipAddress.present ? data.ipAddress.value : this.ipAddress, + externalSessionId: data.externalSessionId.present + ? data.externalSessionId.value + : this.externalSessionId, + createTime: + data.createTime.present ? data.createTime.value : this.createTime, + updateTime: + data.updateTime.present ? data.updateTime.value : this.updateTime, + expireTime: + data.expireTime.present ? data.expireTime.value : this.expireTime, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthSessionsData(') + ..write('rowid: $rowid, ') + ..write('sessionId: $sessionId, ') + ..write('cryptoKeyId: $cryptoKeyId, ') + ..write('userId: $userId, ') + ..write('clientInfo: $clientInfo, ') + ..write('authenticationFactor: $authenticationFactor, ') + ..write('state: $state, ') + ..write('ipAddress: $ipAddress, ') + ..write('externalSessionId: $externalSessionId, ') + ..write('createTime: $createTime, ') + ..write('updateTime: $updateTime, ') + ..write('expireTime: $expireTime') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash( + rowid, + sessionId, + $driftBlobEquality.hash(cryptoKeyId), + userId, + $driftBlobEquality.hash(clientInfo), + $driftBlobEquality.hash(authenticationFactor), + $driftBlobEquality.hash(state), + ipAddress, + externalSessionId, + createTime, + updateTime, + expireTime); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthSessionsData && + other.rowid == this.rowid && + other.sessionId == this.sessionId && + $driftBlobEquality.equals(other.cryptoKeyId, this.cryptoKeyId) && + other.userId == this.userId && + $driftBlobEquality.equals(other.clientInfo, this.clientInfo) && + $driftBlobEquality.equals( + other.authenticationFactor, this.authenticationFactor) && + $driftBlobEquality.equals(other.state, this.state) && + other.ipAddress == this.ipAddress && + other.externalSessionId == this.externalSessionId && + other.createTime == this.createTime && + other.updateTime == this.updateTime && + other.expireTime == this.expireTime); +} + +class CloudAuthSessionsCompanion + extends UpdateCompanion { + final Value rowid; + final Value sessionId; + final Value cryptoKeyId; + final Value userId; + final Value clientInfo; + final Value authenticationFactor; + final Value state; + final Value ipAddress; + final Value externalSessionId; + final Value createTime; + final Value updateTime; + final Value expireTime; + const CloudAuthSessionsCompanion({ + this.rowid = const Value.absent(), + this.sessionId = const Value.absent(), + this.cryptoKeyId = const Value.absent(), + this.userId = const Value.absent(), + this.clientInfo = const Value.absent(), + this.authenticationFactor = const Value.absent(), + this.state = const Value.absent(), + this.ipAddress = const Value.absent(), + this.externalSessionId = const Value.absent(), + this.createTime = const Value.absent(), + this.updateTime = const Value.absent(), + this.expireTime = const Value.absent(), + }); + CloudAuthSessionsCompanion.insert({ + this.rowid = const Value.absent(), + required String sessionId, + required Uint8List cryptoKeyId, + required String userId, + this.clientInfo = const Value.absent(), + required Uint8List authenticationFactor, + this.state = const Value.absent(), + this.ipAddress = const Value.absent(), + this.externalSessionId = const Value.absent(), + this.createTime = const Value.absent(), + this.updateTime = const Value.absent(), + required double expireTime, + }) : sessionId = Value(sessionId), + cryptoKeyId = Value(cryptoKeyId), + userId = Value(userId), + authenticationFactor = Value(authenticationFactor), + expireTime = Value(expireTime); + static Insertable custom({ + Expression? rowid, + Expression? sessionId, + Expression? cryptoKeyId, + Expression? userId, + Expression? clientInfo, + Expression? authenticationFactor, + Expression? state, + Expression? ipAddress, + Expression? externalSessionId, + Expression? createTime, + Expression? updateTime, + Expression? expireTime, + }) { + return RawValuesInsertable({ + if (rowid != null) 'rowid': rowid, + if (sessionId != null) 'session_id': sessionId, + if (cryptoKeyId != null) 'crypto_key_id': cryptoKeyId, + if (userId != null) 'user_id': userId, + if (clientInfo != null) 'client_info': clientInfo, + if (authenticationFactor != null) + 'authentication_factor': authenticationFactor, + if (state != null) 'state': state, + if (ipAddress != null) 'ip_address': ipAddress, + if (externalSessionId != null) 'external_session_id': externalSessionId, + if (createTime != null) 'create_time': createTime, + if (updateTime != null) 'update_time': updateTime, + if (expireTime != null) 'expire_time': expireTime, + }); + } + + CloudAuthSessionsCompanion copyWith( + {Value? rowid, + Value? sessionId, + Value? cryptoKeyId, + Value? userId, + Value? clientInfo, + Value? authenticationFactor, + Value? state, + Value? ipAddress, + Value? externalSessionId, + Value? createTime, + Value? updateTime, + Value? expireTime}) { + return CloudAuthSessionsCompanion( + rowid: rowid ?? this.rowid, + sessionId: sessionId ?? this.sessionId, + cryptoKeyId: cryptoKeyId ?? this.cryptoKeyId, + userId: userId ?? this.userId, + clientInfo: clientInfo ?? this.clientInfo, + authenticationFactor: authenticationFactor ?? this.authenticationFactor, + state: state ?? this.state, + ipAddress: ipAddress ?? this.ipAddress, + externalSessionId: externalSessionId ?? this.externalSessionId, + createTime: createTime ?? this.createTime, + updateTime: updateTime ?? this.updateTime, + expireTime: expireTime ?? this.expireTime, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + if (sessionId.present) { + map['session_id'] = Variable(sessionId.value); + } + if (cryptoKeyId.present) { + map['crypto_key_id'] = Variable(cryptoKeyId.value); + } + if (userId.present) { + map['user_id'] = Variable(userId.value); + } + if (clientInfo.present) { + map['client_info'] = Variable(clientInfo.value); + } + if (authenticationFactor.present) { + map['authentication_factor'] = + Variable(authenticationFactor.value); + } + if (state.present) { + map['state'] = Variable(state.value); + } + if (ipAddress.present) { + map['ip_address'] = Variable(ipAddress.value); + } + if (externalSessionId.present) { + map['external_session_id'] = Variable(externalSessionId.value); + } + if (createTime.present) { + map['create_time'] = Variable(createTime.value); + } + if (updateTime.present) { + map['update_time'] = Variable(updateTime.value); + } + if (expireTime.present) { + map['expire_time'] = Variable(expireTime.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthSessionsCompanion(') + ..write('rowid: $rowid, ') + ..write('sessionId: $sessionId, ') + ..write('cryptoKeyId: $cryptoKeyId, ') + ..write('userId: $userId, ') + ..write('clientInfo: $clientInfo, ') + ..write('authenticationFactor: $authenticationFactor, ') + ..write('state: $state, ') + ..write('ipAddress: $ipAddress, ') + ..write('externalSessionId: $externalSessionId, ') + ..write('createTime: $createTime, ') + ..write('updateTime: $updateTime, ') + ..write('expireTime: $expireTime') + ..write(')')) + .toString(); + } +} + +class CloudAuthOtpCodes extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthOtpCodes(this.attachedDatabase, [this._alias]); + late final GeneratedColumn rowid = GeneratedColumn( + 'rowid', aliasedName, false, + hasAutoIncrement: true, + type: DriftSqlType.int, + requiredDuringInsert: false, + $customConstraints: 'PRIMARY KEY AUTOINCREMENT'); + late final GeneratedColumn sessionId = GeneratedColumn( + 'session_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL UNIQUE'); + late final GeneratedColumn resendAttempt = GeneratedColumn( + 'resend_attempt', aliasedName, false, + type: DriftSqlType.int, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT 0', + defaultValue: const CustomExpression('0')); + late final GeneratedColumn verifyAttempt = GeneratedColumn( + 'verify_attempt', aliasedName, false, + type: DriftSqlType.int, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT 0', + defaultValue: const CustomExpression('0')); + late final GeneratedColumn updateTime = GeneratedColumn( + 'update_time', aliasedName, false, + type: DriftSqlType.double, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT (unixepoch(\'now\', \'subsec\'))', + defaultValue: const CustomExpression('unixepoch(\'now\', \'subsec\')')); + @override + List get $columns => + [rowid, sessionId, resendAttempt, verifyAttempt, updateTime]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_otp_codes'; + @override + Set get $primaryKey => {rowid}; + @override + CloudAuthOtpCodesData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthOtpCodesData( + rowid: attachedDatabase.typeMapping + .read(DriftSqlType.int, data['${effectivePrefix}rowid'])!, + sessionId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}session_id'])!, + resendAttempt: attachedDatabase.typeMapping + .read(DriftSqlType.int, data['${effectivePrefix}resend_attempt'])!, + verifyAttempt: attachedDatabase.typeMapping + .read(DriftSqlType.int, data['${effectivePrefix}verify_attempt'])!, + updateTime: attachedDatabase.typeMapping + .read(DriftSqlType.double, data['${effectivePrefix}update_time'])!, + ); + } + + @override + CloudAuthOtpCodes createAlias(String alias) { + return CloudAuthOtpCodes(attachedDatabase, alias); + } + + @override + List get customConstraints => const [ + 'CONSTRAINT cloud_auth_otp_codes_session_id_fk FOREIGN KEY(session_id)REFERENCES cloud_auth_sessions(session_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthOtpCodesData extends DataClass + implements Insertable { + final int rowid; + final String sessionId; + final int resendAttempt; + final int verifyAttempt; + final double updateTime; + const CloudAuthOtpCodesData( + {required this.rowid, + required this.sessionId, + required this.resendAttempt, + required this.verifyAttempt, + required this.updateTime}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['rowid'] = Variable(rowid); + map['session_id'] = Variable(sessionId); + map['resend_attempt'] = Variable(resendAttempt); + map['verify_attempt'] = Variable(verifyAttempt); + map['update_time'] = Variable(updateTime); + return map; + } + + factory CloudAuthOtpCodesData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthOtpCodesData( + rowid: serializer.fromJson(json['rowid']), + sessionId: serializer.fromJson(json['sessionId']), + resendAttempt: serializer.fromJson(json['resendAttempt']), + verifyAttempt: serializer.fromJson(json['verifyAttempt']), + updateTime: serializer.fromJson(json['updateTime']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'rowid': serializer.toJson(rowid), + 'sessionId': serializer.toJson(sessionId), + 'resendAttempt': serializer.toJson(resendAttempt), + 'verifyAttempt': serializer.toJson(verifyAttempt), + 'updateTime': serializer.toJson(updateTime), + }; + } + + CloudAuthOtpCodesData copyWith( + {int? rowid, + String? sessionId, + int? resendAttempt, + int? verifyAttempt, + double? updateTime}) => + CloudAuthOtpCodesData( + rowid: rowid ?? this.rowid, + sessionId: sessionId ?? this.sessionId, + resendAttempt: resendAttempt ?? this.resendAttempt, + verifyAttempt: verifyAttempt ?? this.verifyAttempt, + updateTime: updateTime ?? this.updateTime, + ); + CloudAuthOtpCodesData copyWithCompanion(CloudAuthOtpCodesCompanion data) { + return CloudAuthOtpCodesData( + rowid: data.rowid.present ? data.rowid.value : this.rowid, + sessionId: data.sessionId.present ? data.sessionId.value : this.sessionId, + resendAttempt: data.resendAttempt.present + ? data.resendAttempt.value + : this.resendAttempt, + verifyAttempt: data.verifyAttempt.present + ? data.verifyAttempt.value + : this.verifyAttempt, + updateTime: + data.updateTime.present ? data.updateTime.value : this.updateTime, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthOtpCodesData(') + ..write('rowid: $rowid, ') + ..write('sessionId: $sessionId, ') + ..write('resendAttempt: $resendAttempt, ') + ..write('verifyAttempt: $verifyAttempt, ') + ..write('updateTime: $updateTime') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(rowid, sessionId, resendAttempt, verifyAttempt, updateTime); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthOtpCodesData && + other.rowid == this.rowid && + other.sessionId == this.sessionId && + other.resendAttempt == this.resendAttempt && + other.verifyAttempt == this.verifyAttempt && + other.updateTime == this.updateTime); +} + +class CloudAuthOtpCodesCompanion + extends UpdateCompanion { + final Value rowid; + final Value sessionId; + final Value resendAttempt; + final Value verifyAttempt; + final Value updateTime; + const CloudAuthOtpCodesCompanion({ + this.rowid = const Value.absent(), + this.sessionId = const Value.absent(), + this.resendAttempt = const Value.absent(), + this.verifyAttempt = const Value.absent(), + this.updateTime = const Value.absent(), + }); + CloudAuthOtpCodesCompanion.insert({ + this.rowid = const Value.absent(), + required String sessionId, + this.resendAttempt = const Value.absent(), + this.verifyAttempt = const Value.absent(), + this.updateTime = const Value.absent(), + }) : sessionId = Value(sessionId); + static Insertable custom({ + Expression? rowid, + Expression? sessionId, + Expression? resendAttempt, + Expression? verifyAttempt, + Expression? updateTime, + }) { + return RawValuesInsertable({ + if (rowid != null) 'rowid': rowid, + if (sessionId != null) 'session_id': sessionId, + if (resendAttempt != null) 'resend_attempt': resendAttempt, + if (verifyAttempt != null) 'verify_attempt': verifyAttempt, + if (updateTime != null) 'update_time': updateTime, + }); + } + + CloudAuthOtpCodesCompanion copyWith( + {Value? rowid, + Value? sessionId, + Value? resendAttempt, + Value? verifyAttempt, + Value? updateTime}) { + return CloudAuthOtpCodesCompanion( + rowid: rowid ?? this.rowid, + sessionId: sessionId ?? this.sessionId, + resendAttempt: resendAttempt ?? this.resendAttempt, + verifyAttempt: verifyAttempt ?? this.verifyAttempt, + updateTime: updateTime ?? this.updateTime, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + if (sessionId.present) { + map['session_id'] = Variable(sessionId.value); + } + if (resendAttempt.present) { + map['resend_attempt'] = Variable(resendAttempt.value); + } + if (verifyAttempt.present) { + map['verify_attempt'] = Variable(verifyAttempt.value); + } + if (updateTime.present) { + map['update_time'] = Variable(updateTime.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthOtpCodesCompanion(') + ..write('rowid: $rowid, ') + ..write('sessionId: $sessionId, ') + ..write('resendAttempt: $resendAttempt, ') + ..write('verifyAttempt: $verifyAttempt, ') + ..write('updateTime: $updateTime') + ..write(')')) + .toString(); + } +} + +class CloudAuthCorks extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CloudAuthCorks(this.attachedDatabase, [this._alias]); + late final GeneratedColumn corkId = GeneratedColumn( + 'cork_id', aliasedName, false, + type: DriftSqlType.blob, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + late final GeneratedColumn cryptoKeyId = + GeneratedColumn('crypto_key_id', aliasedName, false, + type: DriftSqlType.blob, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn bearerType = GeneratedColumn( + 'bearer_type', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn bearerId = GeneratedColumn( + 'bearer_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn audienceType = GeneratedColumn( + 'audience_type', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn audienceId = GeneratedColumn( + 'audience_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn issuerType = GeneratedColumn( + 'issuer_type', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn issuerId = GeneratedColumn( + 'issuer_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn createTime = GeneratedColumn( + 'create_time', aliasedName, false, + type: DriftSqlType.double, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT (unixepoch(\'now\', \'subsec\'))', + defaultValue: const CustomExpression('unixepoch(\'now\', \'subsec\')')); + late final GeneratedColumn expireTime = GeneratedColumn( + 'expire_time', aliasedName, true, + type: DriftSqlType.double, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn lastUseTime = GeneratedColumn( + 'last_use_time', aliasedName, true, + type: DriftSqlType.double, + requiredDuringInsert: false, + $customConstraints: ''); + @override + List get $columns => [ + corkId, + cryptoKeyId, + bearerType, + bearerId, + audienceType, + audienceId, + issuerType, + issuerId, + createTime, + expireTime, + lastUseTime + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cloud_auth_corks'; + @override + Set get $primaryKey => {corkId}; + @override + CloudAuthCorksData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CloudAuthCorksData( + corkId: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}cork_id'])!, + cryptoKeyId: attachedDatabase.typeMapping + .read(DriftSqlType.blob, data['${effectivePrefix}crypto_key_id'])!, + bearerType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}bearer_type']), + bearerId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}bearer_id']), + audienceType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}audience_type']), + audienceId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}audience_id']), + issuerType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}issuer_type']), + issuerId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}issuer_id']), + createTime: attachedDatabase.typeMapping + .read(DriftSqlType.double, data['${effectivePrefix}create_time'])!, + expireTime: attachedDatabase.typeMapping + .read(DriftSqlType.double, data['${effectivePrefix}expire_time']), + lastUseTime: attachedDatabase.typeMapping + .read(DriftSqlType.double, data['${effectivePrefix}last_use_time']), + ); + } + + @override + CloudAuthCorks createAlias(String alias) { + return CloudAuthCorks(attachedDatabase, alias); + } + + @override + List get customConstraints => const [ + 'CONSTRAINT cloud_auth_corks_crypto_key_fk FOREIGN KEY(crypto_key_id)REFERENCES cloud_auth_crypto_keys(crypto_key_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + 'CONSTRAINT cloud_auth_corks_bearer_fk FOREIGN KEY(bearer_type, bearer_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + 'CONSTRAINT cloud_auth_corks_audience_fk FOREIGN KEY(audience_type, audience_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED', + 'CONSTRAINT cloud_auth_corks_issuer_fk FOREIGN KEY(issuer_type, issuer_id)REFERENCES cedar_entities(entity_type, entity_id)ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CloudAuthCorksData extends DataClass + implements Insertable { + final Uint8List corkId; + final Uint8List cryptoKeyId; + final String? bearerType; + final String? bearerId; + final String? audienceType; + final String? audienceId; + final String? issuerType; + final String? issuerId; + final double createTime; + final double? expireTime; + final double? lastUseTime; + const CloudAuthCorksData( + {required this.corkId, + required this.cryptoKeyId, + this.bearerType, + this.bearerId, + this.audienceType, + this.audienceId, + this.issuerType, + this.issuerId, + required this.createTime, + this.expireTime, + this.lastUseTime}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['cork_id'] = Variable(corkId); + map['crypto_key_id'] = Variable(cryptoKeyId); + if (!nullToAbsent || bearerType != null) { + map['bearer_type'] = Variable(bearerType); + } + if (!nullToAbsent || bearerId != null) { + map['bearer_id'] = Variable(bearerId); + } + if (!nullToAbsent || audienceType != null) { + map['audience_type'] = Variable(audienceType); + } + if (!nullToAbsent || audienceId != null) { + map['audience_id'] = Variable(audienceId); + } + if (!nullToAbsent || issuerType != null) { + map['issuer_type'] = Variable(issuerType); + } + if (!nullToAbsent || issuerId != null) { + map['issuer_id'] = Variable(issuerId); + } + map['create_time'] = Variable(createTime); + if (!nullToAbsent || expireTime != null) { + map['expire_time'] = Variable(expireTime); + } + if (!nullToAbsent || lastUseTime != null) { + map['last_use_time'] = Variable(lastUseTime); + } + return map; + } + + factory CloudAuthCorksData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CloudAuthCorksData( + corkId: serializer.fromJson(json['corkId']), + cryptoKeyId: serializer.fromJson(json['cryptoKeyId']), + bearerType: serializer.fromJson(json['bearerType']), + bearerId: serializer.fromJson(json['bearerId']), + audienceType: serializer.fromJson(json['audienceType']), + audienceId: serializer.fromJson(json['audienceId']), + issuerType: serializer.fromJson(json['issuerType']), + issuerId: serializer.fromJson(json['issuerId']), + createTime: serializer.fromJson(json['createTime']), + expireTime: serializer.fromJson(json['expireTime']), + lastUseTime: serializer.fromJson(json['lastUseTime']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'corkId': serializer.toJson(corkId), + 'cryptoKeyId': serializer.toJson(cryptoKeyId), + 'bearerType': serializer.toJson(bearerType), + 'bearerId': serializer.toJson(bearerId), + 'audienceType': serializer.toJson(audienceType), + 'audienceId': serializer.toJson(audienceId), + 'issuerType': serializer.toJson(issuerType), + 'issuerId': serializer.toJson(issuerId), + 'createTime': serializer.toJson(createTime), + 'expireTime': serializer.toJson(expireTime), + 'lastUseTime': serializer.toJson(lastUseTime), + }; + } + + CloudAuthCorksData copyWith( + {Uint8List? corkId, + Uint8List? cryptoKeyId, + Value bearerType = const Value.absent(), + Value bearerId = const Value.absent(), + Value audienceType = const Value.absent(), + Value audienceId = const Value.absent(), + Value issuerType = const Value.absent(), + Value issuerId = const Value.absent(), + double? createTime, + Value expireTime = const Value.absent(), + Value lastUseTime = const Value.absent()}) => + CloudAuthCorksData( + corkId: corkId ?? this.corkId, + cryptoKeyId: cryptoKeyId ?? this.cryptoKeyId, + bearerType: bearerType.present ? bearerType.value : this.bearerType, + bearerId: bearerId.present ? bearerId.value : this.bearerId, + audienceType: + audienceType.present ? audienceType.value : this.audienceType, + audienceId: audienceId.present ? audienceId.value : this.audienceId, + issuerType: issuerType.present ? issuerType.value : this.issuerType, + issuerId: issuerId.present ? issuerId.value : this.issuerId, + createTime: createTime ?? this.createTime, + expireTime: expireTime.present ? expireTime.value : this.expireTime, + lastUseTime: lastUseTime.present ? lastUseTime.value : this.lastUseTime, + ); + CloudAuthCorksData copyWithCompanion(CloudAuthCorksCompanion data) { + return CloudAuthCorksData( + corkId: data.corkId.present ? data.corkId.value : this.corkId, + cryptoKeyId: + data.cryptoKeyId.present ? data.cryptoKeyId.value : this.cryptoKeyId, + bearerType: + data.bearerType.present ? data.bearerType.value : this.bearerType, + bearerId: data.bearerId.present ? data.bearerId.value : this.bearerId, + audienceType: data.audienceType.present + ? data.audienceType.value + : this.audienceType, + audienceId: + data.audienceId.present ? data.audienceId.value : this.audienceId, + issuerType: + data.issuerType.present ? data.issuerType.value : this.issuerType, + issuerId: data.issuerId.present ? data.issuerId.value : this.issuerId, + createTime: + data.createTime.present ? data.createTime.value : this.createTime, + expireTime: + data.expireTime.present ? data.expireTime.value : this.expireTime, + lastUseTime: + data.lastUseTime.present ? data.lastUseTime.value : this.lastUseTime, + ); + } + + @override + String toString() { + return (StringBuffer('CloudAuthCorksData(') + ..write('corkId: $corkId, ') + ..write('cryptoKeyId: $cryptoKeyId, ') + ..write('bearerType: $bearerType, ') + ..write('bearerId: $bearerId, ') + ..write('audienceType: $audienceType, ') + ..write('audienceId: $audienceId, ') + ..write('issuerType: $issuerType, ') + ..write('issuerId: $issuerId, ') + ..write('createTime: $createTime, ') + ..write('expireTime: $expireTime, ') + ..write('lastUseTime: $lastUseTime') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash( + $driftBlobEquality.hash(corkId), + $driftBlobEquality.hash(cryptoKeyId), + bearerType, + bearerId, + audienceType, + audienceId, + issuerType, + issuerId, + createTime, + expireTime, + lastUseTime); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CloudAuthCorksData && + $driftBlobEquality.equals(other.corkId, this.corkId) && + $driftBlobEquality.equals(other.cryptoKeyId, this.cryptoKeyId) && + other.bearerType == this.bearerType && + other.bearerId == this.bearerId && + other.audienceType == this.audienceType && + other.audienceId == this.audienceId && + other.issuerType == this.issuerType && + other.issuerId == this.issuerId && + other.createTime == this.createTime && + other.expireTime == this.expireTime && + other.lastUseTime == this.lastUseTime); +} + +class CloudAuthCorksCompanion extends UpdateCompanion { + final Value corkId; + final Value cryptoKeyId; + final Value bearerType; + final Value bearerId; + final Value audienceType; + final Value audienceId; + final Value issuerType; + final Value issuerId; + final Value createTime; + final Value expireTime; + final Value lastUseTime; + final Value rowid; + const CloudAuthCorksCompanion({ + this.corkId = const Value.absent(), + this.cryptoKeyId = const Value.absent(), + this.bearerType = const Value.absent(), + this.bearerId = const Value.absent(), + this.audienceType = const Value.absent(), + this.audienceId = const Value.absent(), + this.issuerType = const Value.absent(), + this.issuerId = const Value.absent(), + this.createTime = const Value.absent(), + this.expireTime = const Value.absent(), + this.lastUseTime = const Value.absent(), + this.rowid = const Value.absent(), + }); + CloudAuthCorksCompanion.insert({ + required Uint8List corkId, + required Uint8List cryptoKeyId, + this.bearerType = const Value.absent(), + this.bearerId = const Value.absent(), + this.audienceType = const Value.absent(), + this.audienceId = const Value.absent(), + this.issuerType = const Value.absent(), + this.issuerId = const Value.absent(), + this.createTime = const Value.absent(), + this.expireTime = const Value.absent(), + this.lastUseTime = const Value.absent(), + this.rowid = const Value.absent(), + }) : corkId = Value(corkId), + cryptoKeyId = Value(cryptoKeyId); + static Insertable custom({ + Expression? corkId, + Expression? cryptoKeyId, + Expression? bearerType, + Expression? bearerId, + Expression? audienceType, + Expression? audienceId, + Expression? issuerType, + Expression? issuerId, + Expression? createTime, + Expression? expireTime, + Expression? lastUseTime, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (corkId != null) 'cork_id': corkId, + if (cryptoKeyId != null) 'crypto_key_id': cryptoKeyId, + if (bearerType != null) 'bearer_type': bearerType, + if (bearerId != null) 'bearer_id': bearerId, + if (audienceType != null) 'audience_type': audienceType, + if (audienceId != null) 'audience_id': audienceId, + if (issuerType != null) 'issuer_type': issuerType, + if (issuerId != null) 'issuer_id': issuerId, + if (createTime != null) 'create_time': createTime, + if (expireTime != null) 'expire_time': expireTime, + if (lastUseTime != null) 'last_use_time': lastUseTime, + if (rowid != null) 'rowid': rowid, + }); + } + + CloudAuthCorksCompanion copyWith( + {Value? corkId, + Value? cryptoKeyId, + Value? bearerType, + Value? bearerId, + Value? audienceType, + Value? audienceId, + Value? issuerType, + Value? issuerId, + Value? createTime, + Value? expireTime, + Value? lastUseTime, + Value? rowid}) { + return CloudAuthCorksCompanion( + corkId: corkId ?? this.corkId, + cryptoKeyId: cryptoKeyId ?? this.cryptoKeyId, + bearerType: bearerType ?? this.bearerType, + bearerId: bearerId ?? this.bearerId, + audienceType: audienceType ?? this.audienceType, + audienceId: audienceId ?? this.audienceId, + issuerType: issuerType ?? this.issuerType, + issuerId: issuerId ?? this.issuerId, + createTime: createTime ?? this.createTime, + expireTime: expireTime ?? this.expireTime, + lastUseTime: lastUseTime ?? this.lastUseTime, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (corkId.present) { + map['cork_id'] = Variable(corkId.value); + } + if (cryptoKeyId.present) { + map['crypto_key_id'] = Variable(cryptoKeyId.value); + } + if (bearerType.present) { + map['bearer_type'] = Variable(bearerType.value); + } + if (bearerId.present) { + map['bearer_id'] = Variable(bearerId.value); + } + if (audienceType.present) { + map['audience_type'] = Variable(audienceType.value); + } + if (audienceId.present) { + map['audience_id'] = Variable(audienceId.value); + } + if (issuerType.present) { + map['issuer_type'] = Variable(issuerType.value); + } + if (issuerId.present) { + map['issuer_id'] = Variable(issuerId.value); + } + if (createTime.present) { + map['create_time'] = Variable(createTime.value); + } + if (expireTime.present) { + map['expire_time'] = Variable(expireTime.value); + } + if (lastUseTime.present) { + map['last_use_time'] = Variable(lastUseTime.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CloudAuthCorksCompanion(') + ..write('corkId: $corkId, ') + ..write('cryptoKeyId: $cryptoKeyId, ') + ..write('bearerType: $bearerType, ') + ..write('bearerId: $bearerId, ') + ..write('audienceType: $audienceType, ') + ..write('audienceId: $audienceId, ') + ..write('issuerType: $issuerType, ') + ..write('issuerId: $issuerId, ') + ..write('createTime: $createTime, ') + ..write('expireTime: $expireTime, ') + ..write('lastUseTime: $lastUseTime, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CedarPolicies extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CedarPolicies(this.attachedDatabase, [this._alias]); + late final GeneratedColumn id = GeneratedColumn( + 'id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + late final GeneratedColumn policyId = GeneratedColumn( + 'policy_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL UNIQUE'); + late final GeneratedColumn policy = GeneratedColumn( + 'policy', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn enforcementLevel = GeneratedColumn( + 'enforcement_level', aliasedName, false, + type: DriftSqlType.int, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT 1', + defaultValue: const CustomExpression('1')); + @override + List get $columns => + [id, policyId, policy, enforcementLevel]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cedar_policies'; + @override + Set get $primaryKey => {id}; + @override + CedarPoliciesData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CedarPoliciesData( + id: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}id'])!, + policyId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}policy_id'])!, + policy: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}policy'])!, + enforcementLevel: attachedDatabase.typeMapping + .read(DriftSqlType.int, data['${effectivePrefix}enforcement_level'])!, + ); + } + + @override + CedarPolicies createAlias(String alias) { + return CedarPolicies(attachedDatabase, alias); + } + + @override + List get customConstraints => + const ['CHECK(enforcement_level IN (0, 1))']; + @override + bool get dontWriteConstraints => true; +} + +class CedarPoliciesData extends DataClass + implements Insertable { + final String id; + final String policyId; + final String policy; + final int enforcementLevel; + const CedarPoliciesData( + {required this.id, + required this.policyId, + required this.policy, + required this.enforcementLevel}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['policy_id'] = Variable(policyId); + map['policy'] = Variable(policy); + map['enforcement_level'] = Variable(enforcementLevel); + return map; + } + + factory CedarPoliciesData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CedarPoliciesData( + id: serializer.fromJson(json['id']), + policyId: serializer.fromJson(json['policyId']), + policy: serializer.fromJson(json['policy']), + enforcementLevel: serializer.fromJson(json['enforcementLevel']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'policyId': serializer.toJson(policyId), + 'policy': serializer.toJson(policy), + 'enforcementLevel': serializer.toJson(enforcementLevel), + }; + } + + CedarPoliciesData copyWith( + {String? id, + String? policyId, + String? policy, + int? enforcementLevel}) => + CedarPoliciesData( + id: id ?? this.id, + policyId: policyId ?? this.policyId, + policy: policy ?? this.policy, + enforcementLevel: enforcementLevel ?? this.enforcementLevel, + ); + CedarPoliciesData copyWithCompanion(CedarPoliciesCompanion data) { + return CedarPoliciesData( + id: data.id.present ? data.id.value : this.id, + policyId: data.policyId.present ? data.policyId.value : this.policyId, + policy: data.policy.present ? data.policy.value : this.policy, + enforcementLevel: data.enforcementLevel.present + ? data.enforcementLevel.value + : this.enforcementLevel, + ); + } + + @override + String toString() { + return (StringBuffer('CedarPoliciesData(') + ..write('id: $id, ') + ..write('policyId: $policyId, ') + ..write('policy: $policy, ') + ..write('enforcementLevel: $enforcementLevel') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, policyId, policy, enforcementLevel); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CedarPoliciesData && + other.id == this.id && + other.policyId == this.policyId && + other.policy == this.policy && + other.enforcementLevel == this.enforcementLevel); +} + +class CedarPoliciesCompanion extends UpdateCompanion { + final Value id; + final Value policyId; + final Value policy; + final Value enforcementLevel; + final Value rowid; + const CedarPoliciesCompanion({ + this.id = const Value.absent(), + this.policyId = const Value.absent(), + this.policy = const Value.absent(), + this.enforcementLevel = const Value.absent(), + this.rowid = const Value.absent(), + }); + CedarPoliciesCompanion.insert({ + required String id, + required String policyId, + required String policy, + this.enforcementLevel = const Value.absent(), + this.rowid = const Value.absent(), + }) : id = Value(id), + policyId = Value(policyId), + policy = Value(policy); + static Insertable custom({ + Expression? id, + Expression? policyId, + Expression? policy, + Expression? enforcementLevel, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (policyId != null) 'policy_id': policyId, + if (policy != null) 'policy': policy, + if (enforcementLevel != null) 'enforcement_level': enforcementLevel, + if (rowid != null) 'rowid': rowid, + }); + } + + CedarPoliciesCompanion copyWith( + {Value? id, + Value? policyId, + Value? policy, + Value? enforcementLevel, + Value? rowid}) { + return CedarPoliciesCompanion( + id: id ?? this.id, + policyId: policyId ?? this.policyId, + policy: policy ?? this.policy, + enforcementLevel: enforcementLevel ?? this.enforcementLevel, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (policyId.present) { + map['policy_id'] = Variable(policyId.value); + } + if (policy.present) { + map['policy'] = Variable(policy.value); + } + if (enforcementLevel.present) { + map['enforcement_level'] = Variable(enforcementLevel.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CedarPoliciesCompanion(') + ..write('id: $id, ') + ..write('policyId: $policyId, ') + ..write('policy: $policy, ') + ..write('enforcementLevel: $enforcementLevel, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CedarPolicyTemplates extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CedarPolicyTemplates(this.attachedDatabase, [this._alias]); + late final GeneratedColumn id = GeneratedColumn( + 'id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + late final GeneratedColumn templateId = GeneratedColumn( + 'template_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL UNIQUE'); + late final GeneratedColumn template = GeneratedColumn( + 'template', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + @override + List get $columns => [id, templateId, template]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cedar_policy_templates'; + @override + Set get $primaryKey => {id}; + @override + CedarPolicyTemplatesData map(Map data, + {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CedarPolicyTemplatesData( + id: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}id'])!, + templateId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}template_id'])!, + template: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}template'])!, + ); + } + + @override + CedarPolicyTemplates createAlias(String alias) { + return CedarPolicyTemplates(attachedDatabase, alias); + } + + @override + List get customConstraints => + const ['CHECK(template IS NOT NULL OR template IS NOT NULL)']; + @override + bool get dontWriteConstraints => true; +} + +class CedarPolicyTemplatesData extends DataClass + implements Insertable { + final String id; + final String templateId; + final String template; + const CedarPolicyTemplatesData( + {required this.id, required this.templateId, required this.template}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['template_id'] = Variable(templateId); + map['template'] = Variable(template); + return map; + } + + factory CedarPolicyTemplatesData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CedarPolicyTemplatesData( + id: serializer.fromJson(json['id']), + templateId: serializer.fromJson(json['templateId']), + template: serializer.fromJson(json['template']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'templateId': serializer.toJson(templateId), + 'template': serializer.toJson(template), + }; + } + + CedarPolicyTemplatesData copyWith( + {String? id, String? templateId, String? template}) => + CedarPolicyTemplatesData( + id: id ?? this.id, + templateId: templateId ?? this.templateId, + template: template ?? this.template, + ); + CedarPolicyTemplatesData copyWithCompanion( + CedarPolicyTemplatesCompanion data) { + return CedarPolicyTemplatesData( + id: data.id.present ? data.id.value : this.id, + templateId: + data.templateId.present ? data.templateId.value : this.templateId, + template: data.template.present ? data.template.value : this.template, + ); + } + + @override + String toString() { + return (StringBuffer('CedarPolicyTemplatesData(') + ..write('id: $id, ') + ..write('templateId: $templateId, ') + ..write('template: $template') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, templateId, template); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CedarPolicyTemplatesData && + other.id == this.id && + other.templateId == this.templateId && + other.template == this.template); +} + +class CedarPolicyTemplatesCompanion + extends UpdateCompanion { + final Value id; + final Value templateId; + final Value template; + final Value rowid; + const CedarPolicyTemplatesCompanion({ + this.id = const Value.absent(), + this.templateId = const Value.absent(), + this.template = const Value.absent(), + this.rowid = const Value.absent(), + }); + CedarPolicyTemplatesCompanion.insert({ + required String id, + required String templateId, + required String template, + this.rowid = const Value.absent(), + }) : id = Value(id), + templateId = Value(templateId), + template = Value(template); + static Insertable custom({ + Expression? id, + Expression? templateId, + Expression? template, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (templateId != null) 'template_id': templateId, + if (template != null) 'template': template, + if (rowid != null) 'rowid': rowid, + }); + } + + CedarPolicyTemplatesCompanion copyWith( + {Value? id, + Value? templateId, + Value? template, + Value? rowid}) { + return CedarPolicyTemplatesCompanion( + id: id ?? this.id, + templateId: templateId ?? this.templateId, + template: template ?? this.template, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (templateId.present) { + map['template_id'] = Variable(templateId.value); + } + if (template.present) { + map['template'] = Variable(template.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CedarPolicyTemplatesCompanion(') + ..write('id: $id, ') + ..write('templateId: $templateId, ') + ..write('template: $template, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CedarPolicyTemplateLinks extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CedarPolicyTemplateLinks(this.attachedDatabase, [this._alias]); + late final GeneratedColumn id = GeneratedColumn( + 'id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL PRIMARY KEY'); + late final GeneratedColumn policyId = GeneratedColumn( + 'policy_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL UNIQUE'); + late final GeneratedColumn templateId = GeneratedColumn( + 'template_id', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn principalType = GeneratedColumn( + 'principal_type', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn principalId = GeneratedColumn( + 'principal_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn resourceType = GeneratedColumn( + 'resource_type', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn resourceId = GeneratedColumn( + 'resource_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn enforcementLevel = GeneratedColumn( + 'enforcement_level', aliasedName, false, + type: DriftSqlType.int, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT 1', + defaultValue: const CustomExpression('1')); + @override + List get $columns => [ + id, + policyId, + templateId, + principalType, + principalId, + resourceType, + resourceId, + enforcementLevel + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cedar_policy_template_links'; + @override + Set get $primaryKey => {id}; + @override + CedarPolicyTemplateLinksData map(Map data, + {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CedarPolicyTemplateLinksData( + id: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}id'])!, + policyId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}policy_id'])!, + templateId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}template_id'])!, + principalType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}principal_type']), + principalId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}principal_id']), + resourceType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}resource_type']), + resourceId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}resource_id']), + enforcementLevel: attachedDatabase.typeMapping + .read(DriftSqlType.int, data['${effectivePrefix}enforcement_level'])!, + ); + } + + @override + CedarPolicyTemplateLinks createAlias(String alias) { + return CedarPolicyTemplateLinks(attachedDatabase, alias); + } + + @override + List get customConstraints => const [ + 'CHECK(principal_type IS NOT NULL AND principal_id IS NOT NULL OR resource_type IS NOT NULL AND resource_id IS NOT NULL)', + 'CHECK(enforcement_level IN (0, 1))', + 'CONSTRAINT cedar_policy_template_links_fk_template_id FOREIGN KEY(template_id)REFERENCES cedar_policy_templates(template_id)ON UPDATE CASCADE ON DELETE CASCADE', + 'CONSTRAINT cedar_policy_template_links_fk_principal FOREIGN KEY(principal_type, principal_id)REFERENCES cedar_entities(entity_type, entity_id)ON DELETE CASCADE', + 'CONSTRAINT cedar_policy_template_links_fk_resource FOREIGN KEY(resource_type, resource_id)REFERENCES cedar_entities(entity_type, entity_id)ON DELETE CASCADE' + ]; + @override + bool get dontWriteConstraints => true; +} + +class CedarPolicyTemplateLinksData extends DataClass + implements Insertable { + final String id; + final String policyId; + final String templateId; + final String? principalType; + final String? principalId; + final String? resourceType; + final String? resourceId; + final int enforcementLevel; + const CedarPolicyTemplateLinksData( + {required this.id, + required this.policyId, + required this.templateId, + this.principalType, + this.principalId, + this.resourceType, + this.resourceId, + required this.enforcementLevel}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['policy_id'] = Variable(policyId); + map['template_id'] = Variable(templateId); + if (!nullToAbsent || principalType != null) { + map['principal_type'] = Variable(principalType); + } + if (!nullToAbsent || principalId != null) { + map['principal_id'] = Variable(principalId); + } + if (!nullToAbsent || resourceType != null) { + map['resource_type'] = Variable(resourceType); + } + if (!nullToAbsent || resourceId != null) { + map['resource_id'] = Variable(resourceId); + } + map['enforcement_level'] = Variable(enforcementLevel); + return map; + } + + factory CedarPolicyTemplateLinksData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CedarPolicyTemplateLinksData( + id: serializer.fromJson(json['id']), + policyId: serializer.fromJson(json['policyId']), + templateId: serializer.fromJson(json['templateId']), + principalType: serializer.fromJson(json['principalType']), + principalId: serializer.fromJson(json['principalId']), + resourceType: serializer.fromJson(json['resourceType']), + resourceId: serializer.fromJson(json['resourceId']), + enforcementLevel: serializer.fromJson(json['enforcementLevel']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'policyId': serializer.toJson(policyId), + 'templateId': serializer.toJson(templateId), + 'principalType': serializer.toJson(principalType), + 'principalId': serializer.toJson(principalId), + 'resourceType': serializer.toJson(resourceType), + 'resourceId': serializer.toJson(resourceId), + 'enforcementLevel': serializer.toJson(enforcementLevel), + }; + } + + CedarPolicyTemplateLinksData copyWith( + {String? id, + String? policyId, + String? templateId, + Value principalType = const Value.absent(), + Value principalId = const Value.absent(), + Value resourceType = const Value.absent(), + Value resourceId = const Value.absent(), + int? enforcementLevel}) => + CedarPolicyTemplateLinksData( + id: id ?? this.id, + policyId: policyId ?? this.policyId, + templateId: templateId ?? this.templateId, + principalType: + principalType.present ? principalType.value : this.principalType, + principalId: principalId.present ? principalId.value : this.principalId, + resourceType: + resourceType.present ? resourceType.value : this.resourceType, + resourceId: resourceId.present ? resourceId.value : this.resourceId, + enforcementLevel: enforcementLevel ?? this.enforcementLevel, + ); + CedarPolicyTemplateLinksData copyWithCompanion( + CedarPolicyTemplateLinksCompanion data) { + return CedarPolicyTemplateLinksData( + id: data.id.present ? data.id.value : this.id, + policyId: data.policyId.present ? data.policyId.value : this.policyId, + templateId: + data.templateId.present ? data.templateId.value : this.templateId, + principalType: data.principalType.present + ? data.principalType.value + : this.principalType, + principalId: + data.principalId.present ? data.principalId.value : this.principalId, + resourceType: data.resourceType.present + ? data.resourceType.value + : this.resourceType, + resourceId: + data.resourceId.present ? data.resourceId.value : this.resourceId, + enforcementLevel: data.enforcementLevel.present + ? data.enforcementLevel.value + : this.enforcementLevel, + ); + } + + @override + String toString() { + return (StringBuffer('CedarPolicyTemplateLinksData(') + ..write('id: $id, ') + ..write('policyId: $policyId, ') + ..write('templateId: $templateId, ') + ..write('principalType: $principalType, ') + ..write('principalId: $principalId, ') + ..write('resourceType: $resourceType, ') + ..write('resourceId: $resourceId, ') + ..write('enforcementLevel: $enforcementLevel') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, policyId, templateId, principalType, + principalId, resourceType, resourceId, enforcementLevel); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CedarPolicyTemplateLinksData && + other.id == this.id && + other.policyId == this.policyId && + other.templateId == this.templateId && + other.principalType == this.principalType && + other.principalId == this.principalId && + other.resourceType == this.resourceType && + other.resourceId == this.resourceId && + other.enforcementLevel == this.enforcementLevel); +} + +class CedarPolicyTemplateLinksCompanion + extends UpdateCompanion { + final Value id; + final Value policyId; + final Value templateId; + final Value principalType; + final Value principalId; + final Value resourceType; + final Value resourceId; + final Value enforcementLevel; + final Value rowid; + const CedarPolicyTemplateLinksCompanion({ + this.id = const Value.absent(), + this.policyId = const Value.absent(), + this.templateId = const Value.absent(), + this.principalType = const Value.absent(), + this.principalId = const Value.absent(), + this.resourceType = const Value.absent(), + this.resourceId = const Value.absent(), + this.enforcementLevel = const Value.absent(), + this.rowid = const Value.absent(), + }); + CedarPolicyTemplateLinksCompanion.insert({ + required String id, + required String policyId, + required String templateId, + this.principalType = const Value.absent(), + this.principalId = const Value.absent(), + this.resourceType = const Value.absent(), + this.resourceId = const Value.absent(), + this.enforcementLevel = const Value.absent(), + this.rowid = const Value.absent(), + }) : id = Value(id), + policyId = Value(policyId), + templateId = Value(templateId); + static Insertable custom({ + Expression? id, + Expression? policyId, + Expression? templateId, + Expression? principalType, + Expression? principalId, + Expression? resourceType, + Expression? resourceId, + Expression? enforcementLevel, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (policyId != null) 'policy_id': policyId, + if (templateId != null) 'template_id': templateId, + if (principalType != null) 'principal_type': principalType, + if (principalId != null) 'principal_id': principalId, + if (resourceType != null) 'resource_type': resourceType, + if (resourceId != null) 'resource_id': resourceId, + if (enforcementLevel != null) 'enforcement_level': enforcementLevel, + if (rowid != null) 'rowid': rowid, + }); + } + + CedarPolicyTemplateLinksCompanion copyWith( + {Value? id, + Value? policyId, + Value? templateId, + Value? principalType, + Value? principalId, + Value? resourceType, + Value? resourceId, + Value? enforcementLevel, + Value? rowid}) { + return CedarPolicyTemplateLinksCompanion( + id: id ?? this.id, + policyId: policyId ?? this.policyId, + templateId: templateId ?? this.templateId, + principalType: principalType ?? this.principalType, + principalId: principalId ?? this.principalId, + resourceType: resourceType ?? this.resourceType, + resourceId: resourceId ?? this.resourceId, + enforcementLevel: enforcementLevel ?? this.enforcementLevel, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (policyId.present) { + map['policy_id'] = Variable(policyId.value); + } + if (templateId.present) { + map['template_id'] = Variable(templateId.value); + } + if (principalType.present) { + map['principal_type'] = Variable(principalType.value); + } + if (principalId.present) { + map['principal_id'] = Variable(principalId.value); + } + if (resourceType.present) { + map['resource_type'] = Variable(resourceType.value); + } + if (resourceId.present) { + map['resource_id'] = Variable(resourceId.value); + } + if (enforcementLevel.present) { + map['enforcement_level'] = Variable(enforcementLevel.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CedarPolicyTemplateLinksCompanion(') + ..write('id: $id, ') + ..write('policyId: $policyId, ') + ..write('templateId: $templateId, ') + ..write('principalType: $principalType, ') + ..write('principalId: $principalId, ') + ..write('resourceType: $resourceType, ') + ..write('resourceId: $resourceId, ') + ..write('enforcementLevel: $enforcementLevel, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class CedarAuthorizationLogs extends Table + with TableInfo { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + CedarAuthorizationLogs(this.attachedDatabase, [this._alias]); + late final GeneratedColumn rowid = GeneratedColumn( + 'rowid', aliasedName, false, + hasAutoIncrement: true, + type: DriftSqlType.int, + requiredDuringInsert: false, + $customConstraints: 'PRIMARY KEY AUTOINCREMENT'); + late final GeneratedColumn createTime = GeneratedColumn( + 'create_time', aliasedName, false, + type: DriftSqlType.dateTime, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT (unixepoch(\'now\', \'subsec\'))', + defaultValue: const CustomExpression('unixepoch(\'now\', \'subsec\')')); + late final GeneratedColumn expireTime = GeneratedColumn( + 'expire_time', aliasedName, true, + type: DriftSqlType.dateTime, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn principalType = GeneratedColumn( + 'principal_type', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn principalId = GeneratedColumn( + 'principal_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn actionType = GeneratedColumn( + 'action_type', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn actionId = GeneratedColumn( + 'action_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn resourceType = GeneratedColumn( + 'resource_type', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn resourceId = GeneratedColumn( + 'resource_id', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: ''); + late final GeneratedColumn contextJson = GeneratedColumn( + 'context_json', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT \'{}\'', + defaultValue: const CustomExpression('\'{}\'')); + late final GeneratedColumn decision = GeneratedColumn( + 'decision', aliasedName, false, + type: DriftSqlType.bool, + requiredDuringInsert: true, + $customConstraints: 'NOT NULL'); + late final GeneratedColumn reasonsJson = GeneratedColumn( + 'reasons_json', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT \'[]\'', + defaultValue: const CustomExpression('\'[]\'')); + late final GeneratedColumn errorsJson = GeneratedColumn( + 'errors_json', aliasedName, false, + type: DriftSqlType.string, + requiredDuringInsert: false, + $customConstraints: 'NOT NULL DEFAULT \'[]\'', + defaultValue: const CustomExpression('\'[]\'')); + @override + List get $columns => [ + rowid, + createTime, + expireTime, + principalType, + principalId, + actionType, + actionId, + resourceType, + resourceId, + contextJson, + decision, + reasonsJson, + errorsJson + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'cedar_authorization_logs'; + @override + Set get $primaryKey => {rowid}; + @override + CedarAuthorizationLogsData map(Map data, + {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CedarAuthorizationLogsData( + rowid: attachedDatabase.typeMapping + .read(DriftSqlType.int, data['${effectivePrefix}rowid'])!, + createTime: attachedDatabase.typeMapping + .read(DriftSqlType.dateTime, data['${effectivePrefix}create_time'])!, + expireTime: attachedDatabase.typeMapping + .read(DriftSqlType.dateTime, data['${effectivePrefix}expire_time']), + principalType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}principal_type']), + principalId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}principal_id']), + actionType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}action_type']), + actionId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}action_id']), + resourceType: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}resource_type']), + resourceId: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}resource_id']), + contextJson: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}context_json'])!, + decision: attachedDatabase.typeMapping + .read(DriftSqlType.bool, data['${effectivePrefix}decision'])!, + reasonsJson: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}reasons_json'])!, + errorsJson: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}errors_json'])!, + ); + } + + @override + CedarAuthorizationLogs createAlias(String alias) { + return CedarAuthorizationLogs(attachedDatabase, alias); + } + + @override + bool get dontWriteConstraints => true; +} + +class CedarAuthorizationLogsData extends DataClass + implements Insertable { + final int rowid; + final DateTime createTime; + final DateTime? expireTime; + final String? principalType; + final String? principalId; + final String? actionType; + final String? actionId; + final String? resourceType; + final String? resourceId; + final String contextJson; + final bool decision; + final String reasonsJson; + final String errorsJson; + const CedarAuthorizationLogsData( + {required this.rowid, + required this.createTime, + this.expireTime, + this.principalType, + this.principalId, + this.actionType, + this.actionId, + this.resourceType, + this.resourceId, + required this.contextJson, + required this.decision, + required this.reasonsJson, + required this.errorsJson}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['rowid'] = Variable(rowid); + map['create_time'] = Variable(createTime); + if (!nullToAbsent || expireTime != null) { + map['expire_time'] = Variable(expireTime); + } + if (!nullToAbsent || principalType != null) { + map['principal_type'] = Variable(principalType); + } + if (!nullToAbsent || principalId != null) { + map['principal_id'] = Variable(principalId); + } + if (!nullToAbsent || actionType != null) { + map['action_type'] = Variable(actionType); + } + if (!nullToAbsent || actionId != null) { + map['action_id'] = Variable(actionId); + } + if (!nullToAbsent || resourceType != null) { + map['resource_type'] = Variable(resourceType); + } + if (!nullToAbsent || resourceId != null) { + map['resource_id'] = Variable(resourceId); + } + map['context_json'] = Variable(contextJson); + map['decision'] = Variable(decision); + map['reasons_json'] = Variable(reasonsJson); + map['errors_json'] = Variable(errorsJson); + return map; + } + + factory CedarAuthorizationLogsData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CedarAuthorizationLogsData( + rowid: serializer.fromJson(json['rowid']), + createTime: serializer.fromJson(json['createTime']), + expireTime: serializer.fromJson(json['expireTime']), + principalType: serializer.fromJson(json['principalType']), + principalId: serializer.fromJson(json['principalId']), + actionType: serializer.fromJson(json['actionType']), + actionId: serializer.fromJson(json['actionId']), + resourceType: serializer.fromJson(json['resourceType']), + resourceId: serializer.fromJson(json['resourceId']), + contextJson: serializer.fromJson(json['contextJson']), + decision: serializer.fromJson(json['decision']), + reasonsJson: serializer.fromJson(json['reasonsJson']), + errorsJson: serializer.fromJson(json['errorsJson']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'rowid': serializer.toJson(rowid), + 'createTime': serializer.toJson(createTime), + 'expireTime': serializer.toJson(expireTime), + 'principalType': serializer.toJson(principalType), + 'principalId': serializer.toJson(principalId), + 'actionType': serializer.toJson(actionType), + 'actionId': serializer.toJson(actionId), + 'resourceType': serializer.toJson(resourceType), + 'resourceId': serializer.toJson(resourceId), + 'contextJson': serializer.toJson(contextJson), + 'decision': serializer.toJson(decision), + 'reasonsJson': serializer.toJson(reasonsJson), + 'errorsJson': serializer.toJson(errorsJson), + }; + } + + CedarAuthorizationLogsData copyWith( + {int? rowid, + DateTime? createTime, + Value expireTime = const Value.absent(), + Value principalType = const Value.absent(), + Value principalId = const Value.absent(), + Value actionType = const Value.absent(), + Value actionId = const Value.absent(), + Value resourceType = const Value.absent(), + Value resourceId = const Value.absent(), + String? contextJson, + bool? decision, + String? reasonsJson, + String? errorsJson}) => + CedarAuthorizationLogsData( + rowid: rowid ?? this.rowid, + createTime: createTime ?? this.createTime, + expireTime: expireTime.present ? expireTime.value : this.expireTime, + principalType: + principalType.present ? principalType.value : this.principalType, + principalId: principalId.present ? principalId.value : this.principalId, + actionType: actionType.present ? actionType.value : this.actionType, + actionId: actionId.present ? actionId.value : this.actionId, + resourceType: + resourceType.present ? resourceType.value : this.resourceType, + resourceId: resourceId.present ? resourceId.value : this.resourceId, + contextJson: contextJson ?? this.contextJson, + decision: decision ?? this.decision, + reasonsJson: reasonsJson ?? this.reasonsJson, + errorsJson: errorsJson ?? this.errorsJson, + ); + CedarAuthorizationLogsData copyWithCompanion( + CedarAuthorizationLogsCompanion data) { + return CedarAuthorizationLogsData( + rowid: data.rowid.present ? data.rowid.value : this.rowid, + createTime: + data.createTime.present ? data.createTime.value : this.createTime, + expireTime: + data.expireTime.present ? data.expireTime.value : this.expireTime, + principalType: data.principalType.present + ? data.principalType.value + : this.principalType, + principalId: + data.principalId.present ? data.principalId.value : this.principalId, + actionType: + data.actionType.present ? data.actionType.value : this.actionType, + actionId: data.actionId.present ? data.actionId.value : this.actionId, + resourceType: data.resourceType.present + ? data.resourceType.value + : this.resourceType, + resourceId: + data.resourceId.present ? data.resourceId.value : this.resourceId, + contextJson: + data.contextJson.present ? data.contextJson.value : this.contextJson, + decision: data.decision.present ? data.decision.value : this.decision, + reasonsJson: + data.reasonsJson.present ? data.reasonsJson.value : this.reasonsJson, + errorsJson: + data.errorsJson.present ? data.errorsJson.value : this.errorsJson, + ); + } + + @override + String toString() { + return (StringBuffer('CedarAuthorizationLogsData(') + ..write('rowid: $rowid, ') + ..write('createTime: $createTime, ') + ..write('expireTime: $expireTime, ') + ..write('principalType: $principalType, ') + ..write('principalId: $principalId, ') + ..write('actionType: $actionType, ') + ..write('actionId: $actionId, ') + ..write('resourceType: $resourceType, ') + ..write('resourceId: $resourceId, ') + ..write('contextJson: $contextJson, ') + ..write('decision: $decision, ') + ..write('reasonsJson: $reasonsJson, ') + ..write('errorsJson: $errorsJson') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash( + rowid, + createTime, + expireTime, + principalType, + principalId, + actionType, + actionId, + resourceType, + resourceId, + contextJson, + decision, + reasonsJson, + errorsJson); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CedarAuthorizationLogsData && + other.rowid == this.rowid && + other.createTime == this.createTime && + other.expireTime == this.expireTime && + other.principalType == this.principalType && + other.principalId == this.principalId && + other.actionType == this.actionType && + other.actionId == this.actionId && + other.resourceType == this.resourceType && + other.resourceId == this.resourceId && + other.contextJson == this.contextJson && + other.decision == this.decision && + other.reasonsJson == this.reasonsJson && + other.errorsJson == this.errorsJson); +} + +class CedarAuthorizationLogsCompanion + extends UpdateCompanion { + final Value rowid; + final Value createTime; + final Value expireTime; + final Value principalType; + final Value principalId; + final Value actionType; + final Value actionId; + final Value resourceType; + final Value resourceId; + final Value contextJson; + final Value decision; + final Value reasonsJson; + final Value errorsJson; + const CedarAuthorizationLogsCompanion({ + this.rowid = const Value.absent(), + this.createTime = const Value.absent(), + this.expireTime = const Value.absent(), + this.principalType = const Value.absent(), + this.principalId = const Value.absent(), + this.actionType = const Value.absent(), + this.actionId = const Value.absent(), + this.resourceType = const Value.absent(), + this.resourceId = const Value.absent(), + this.contextJson = const Value.absent(), + this.decision = const Value.absent(), + this.reasonsJson = const Value.absent(), + this.errorsJson = const Value.absent(), + }); + CedarAuthorizationLogsCompanion.insert({ + this.rowid = const Value.absent(), + this.createTime = const Value.absent(), + this.expireTime = const Value.absent(), + this.principalType = const Value.absent(), + this.principalId = const Value.absent(), + this.actionType = const Value.absent(), + this.actionId = const Value.absent(), + this.resourceType = const Value.absent(), + this.resourceId = const Value.absent(), + this.contextJson = const Value.absent(), + required bool decision, + this.reasonsJson = const Value.absent(), + this.errorsJson = const Value.absent(), + }) : decision = Value(decision); + static Insertable custom({ + Expression? rowid, + Expression? createTime, + Expression? expireTime, + Expression? principalType, + Expression? principalId, + Expression? actionType, + Expression? actionId, + Expression? resourceType, + Expression? resourceId, + Expression? contextJson, + Expression? decision, + Expression? reasonsJson, + Expression? errorsJson, + }) { + return RawValuesInsertable({ + if (rowid != null) 'rowid': rowid, + if (createTime != null) 'create_time': createTime, + if (expireTime != null) 'expire_time': expireTime, + if (principalType != null) 'principal_type': principalType, + if (principalId != null) 'principal_id': principalId, + if (actionType != null) 'action_type': actionType, + if (actionId != null) 'action_id': actionId, + if (resourceType != null) 'resource_type': resourceType, + if (resourceId != null) 'resource_id': resourceId, + if (contextJson != null) 'context_json': contextJson, + if (decision != null) 'decision': decision, + if (reasonsJson != null) 'reasons_json': reasonsJson, + if (errorsJson != null) 'errors_json': errorsJson, + }); + } + + CedarAuthorizationLogsCompanion copyWith( + {Value? rowid, + Value? createTime, + Value? expireTime, + Value? principalType, + Value? principalId, + Value? actionType, + Value? actionId, + Value? resourceType, + Value? resourceId, + Value? contextJson, + Value? decision, + Value? reasonsJson, + Value? errorsJson}) { + return CedarAuthorizationLogsCompanion( + rowid: rowid ?? this.rowid, + createTime: createTime ?? this.createTime, + expireTime: expireTime ?? this.expireTime, + principalType: principalType ?? this.principalType, + principalId: principalId ?? this.principalId, + actionType: actionType ?? this.actionType, + actionId: actionId ?? this.actionId, + resourceType: resourceType ?? this.resourceType, + resourceId: resourceId ?? this.resourceId, + contextJson: contextJson ?? this.contextJson, + decision: decision ?? this.decision, + reasonsJson: reasonsJson ?? this.reasonsJson, + errorsJson: errorsJson ?? this.errorsJson, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + if (createTime.present) { + map['create_time'] = Variable(createTime.value); + } + if (expireTime.present) { + map['expire_time'] = Variable(expireTime.value); + } + if (principalType.present) { + map['principal_type'] = Variable(principalType.value); + } + if (principalId.present) { + map['principal_id'] = Variable(principalId.value); + } + if (actionType.present) { + map['action_type'] = Variable(actionType.value); + } + if (actionId.present) { + map['action_id'] = Variable(actionId.value); + } + if (resourceType.present) { + map['resource_type'] = Variable(resourceType.value); + } + if (resourceId.present) { + map['resource_id'] = Variable(resourceId.value); + } + if (contextJson.present) { + map['context_json'] = Variable(contextJson.value); + } + if (decision.present) { + map['decision'] = Variable(decision.value); + } + if (reasonsJson.present) { + map['reasons_json'] = Variable(reasonsJson.value); + } + if (errorsJson.present) { + map['errors_json'] = Variable(errorsJson.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CedarAuthorizationLogsCompanion(') + ..write('rowid: $rowid, ') + ..write('createTime: $createTime, ') + ..write('expireTime: $expireTime, ') + ..write('principalType: $principalType, ') + ..write('principalId: $principalId, ') + ..write('actionType: $actionType, ') + ..write('actionId: $actionId, ') + ..write('resourceType: $resourceType, ') + ..write('resourceId: $resourceId, ') + ..write('contextJson: $contextJson, ') + ..write('decision: $decision, ') + ..write('reasonsJson: $reasonsJson, ') + ..write('errorsJson: $errorsJson') + ..write(')')) + .toString(); + } +} + +class DatabaseAtV5 extends GeneratedDatabase { + DatabaseAtV5(QueryExecutor e) : super(e); + late final CloudAuthUsers cloudAuthUsers = CloudAuthUsers(this); + late final CedarTypes cedarTypes = CedarTypes(this); + late final CedarEntities cedarEntities = CedarEntities(this); + late final Trigger cloudAuthUsersCreateTrg = Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_users_create_trg BEFORE INSERT ON cloud_auth_users BEGIN INSERT INTO cedar_entities (entity_type, entity_id) VALUES (\'Celest::User\', NEW.user_id);END', + 'cloud_auth_users_create_trg'); + late final CedarRelationships cedarRelationships = CedarRelationships(this); + late final Trigger cloudAuthUsersDeleteTrg = Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_users_delete_trg AFTER DELETE ON cloud_auth_users BEGIN DELETE FROM cedar_relationships WHERE(entity_type = \'Celest::User\' AND entity_id = OLD.user_id)OR(parent_type = \'Celest::User\' AND parent_id = OLD.user_id);DELETE FROM cedar_entities WHERE entity_id = OLD.user_id AND entity_type = \'Celest::User\';END', + 'cloud_auth_users_delete_trg'); + late final CloudAuthUserEmails cloudAuthUserEmails = + CloudAuthUserEmails(this); + late final CloudAuthUserPhoneNumbers cloudAuthUserPhoneNumbers = + CloudAuthUserPhoneNumbers(this); + late final CloudAuthProjects cloudAuthProjects = CloudAuthProjects(this); + late final CloudAuthApis cloudAuthApis = CloudAuthApis(this); + late final Index cloudAuthApisProjectIdx = Index( + 'cloud_auth_apis_project_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_apis_project_idx ON cloud_auth_apis (project_id)'); + late final Trigger cloudAuthApisCreateTrg = Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_apis_create_trg BEFORE INSERT ON cloud_auth_apis BEGIN INSERT INTO cedar_entities (entity_type, entity_id) VALUES (\'Celest::Api\', NEW.api_id);END', + 'cloud_auth_apis_create_trg'); + late final Trigger cloudAuthApisDeleteTrg = Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_apis_delete_trg AFTER DELETE ON cloud_auth_apis BEGIN DELETE FROM cedar_relationships WHERE entity_type = \'Celest::Api\' AND entity_id = OLD.api_id;DELETE FROM cedar_relationships WHERE parent_type = \'Celest::Api\' AND parent_id = OLD.api_id;DELETE FROM cedar_entities WHERE entity_type = \'Celest::Api\' AND entity_id = OLD.api_id;END', + 'cloud_auth_apis_delete_trg'); + late final CloudAuthFunctions cloudAuthFunctions = CloudAuthFunctions(this); + late final Index cloudAuthFunctionsApiIdx = Index( + 'cloud_auth_functions_api_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_functions_api_idx ON cloud_auth_functions (api_id)'); + late final Trigger cloudAuthFunctionsCreateTrg = Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_functions_create_trg BEFORE INSERT ON cloud_auth_functions BEGIN INSERT INTO cedar_entities (entity_type, entity_id) VALUES (\'Celest::Function\', NEW.function_id);INSERT INTO cedar_relationships (entity_type, entity_id, parent_type, parent_id) VALUES (\'Celest::Function\', NEW.function_id, \'Celest::Api\', NEW.api_id);END', + 'cloud_auth_functions_create_trg'); + late final Trigger cloudAuthFunctionsDeleteTrg = Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_functions_delete_trg AFTER DELETE ON cloud_auth_functions BEGIN DELETE FROM cedar_relationships WHERE entity_type = \'Celest::Function\' AND entity_id = OLD.function_id;DELETE FROM cedar_relationships WHERE parent_type = \'Celest::Function\' AND parent_id = OLD.function_id;DELETE FROM cedar_entities WHERE entity_type = \'Celest::Function\' AND entity_id = OLD.function_id;END', + 'cloud_auth_functions_delete_trg'); + late final CloudAuthMeta cloudAuthMeta = CloudAuthMeta(this); + late final CloudAuthCryptoKeys cloudAuthCryptoKeys = + CloudAuthCryptoKeys(this); + late final Index cloudAuthCryptoKeysExternalCryptoKeyIdIdx = Index( + 'cloud_auth_crypto_keys_external_crypto_key_id_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_crypto_keys_external_crypto_key_id_idx ON cloud_auth_crypto_keys (external_crypto_key_id)'); + late final CloudAuthSessions cloudAuthSessions = CloudAuthSessions(this); + late final Index cloudAuthSessionsUserIdx = Index( + 'cloud_auth_sessions_user_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_sessions_user_idx ON cloud_auth_sessions (user_id)'); + late final Index cloudAuthSessionsCryptoKeyIdx = Index( + 'cloud_auth_sessions_crypto_key_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_sessions_crypto_key_idx ON cloud_auth_sessions (crypto_key_id)'); + late final Index cloudAuthSessionsExternalSessionIdIdx = Index( + 'cloud_auth_sessions_external_session_id_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_sessions_external_session_id_idx ON cloud_auth_sessions (external_session_id)'); + late final Trigger cloudAuthSessionsUpdateTimeTrg = Trigger( + 'CREATE TRIGGER IF NOT EXISTS cloud_auth_sessions_update_time_trg AFTER UPDATE ON cloud_auth_sessions BEGIN UPDATE cloud_auth_sessions SET update_time = unixepoch(\'now\', \'subsec\') WHERE "rowid" = OLD."rowid";END', + 'cloud_auth_sessions_update_time_trg'); + late final CloudAuthOtpCodes cloudAuthOtpCodes = CloudAuthOtpCodes(this); + late final Index cloudAuthOtpCodesSessionIdIdx = Index( + 'cloud_auth_otp_codes_session_id_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_otp_codes_session_id_idx ON cloud_auth_otp_codes (session_id)'); + late final CloudAuthCorks cloudAuthCorks = CloudAuthCorks(this); + late final Index cloudAuthCorksCryptoKeyIdx = Index( + 'cloud_auth_corks_crypto_key_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_corks_crypto_key_idx ON cloud_auth_corks (crypto_key_id)'); + late final Index cloudAuthCorksBearerIdx = Index( + 'cloud_auth_corks_bearer_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_corks_bearer_idx ON cloud_auth_corks (bearer_type, bearer_id)'); + late final Index cloudAuthCorksAudienceIdx = Index( + 'cloud_auth_corks_audience_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_corks_audience_idx ON cloud_auth_corks (audience_type, audience_id)'); + late final Index cloudAuthCorksIssuerIdx = Index( + 'cloud_auth_corks_issuer_idx', + 'CREATE INDEX IF NOT EXISTS cloud_auth_corks_issuer_idx ON cloud_auth_corks (issuer_type, issuer_id)'); + late final Index cedarRelationshipsFkEntityIdx = Index( + 'cedar_relationships_fk_entity_idx', + 'CREATE INDEX IF NOT EXISTS cedar_relationships_fk_entity_idx ON cedar_relationships (entity_type, entity_id)'); + late final Index cedarRelationshipsFkParentIdx = Index( + 'cedar_relationships_fk_parent_idx', + 'CREATE INDEX IF NOT EXISTS cedar_relationships_fk_parent_idx ON cedar_relationships (parent_type, parent_id)'); + late final CedarPolicies cedarPolicies = CedarPolicies(this); + late final CedarPolicyTemplates cedarPolicyTemplates = + CedarPolicyTemplates(this); + late final CedarPolicyTemplateLinks cedarPolicyTemplateLinks = + CedarPolicyTemplateLinks(this); + late final Index cedarPolicyTemplateLinksFkTemplateIdIdx = Index( + 'cedar_policy_template_links_fk_template_id_idx', + 'CREATE INDEX IF NOT EXISTS cedar_policy_template_links_fk_template_id_idx ON cedar_policy_template_links (template_id)'); + late final Index cedarPolicyTemplateLinksFkPrincipalIdx = Index( + 'cedar_policy_template_links_fk_principal_idx', + 'CREATE INDEX IF NOT EXISTS cedar_policy_template_links_fk_principal_idx ON cedar_policy_template_links (principal_type, principal_id)'); + late final Index cedarPolicyTemplateLinksFkResourceIdx = Index( + 'cedar_policy_template_links_fk_resource_idx', + 'CREATE INDEX IF NOT EXISTS cedar_policy_template_links_fk_resource_idx ON cedar_policy_template_links (resource_type, resource_id)'); + late final CedarAuthorizationLogs cedarAuthorizationLogs = + CedarAuthorizationLogs(this); + @override + Iterable> get allTables => + allSchemaEntities.whereType>(); + @override + List get allSchemaEntities => [ + cloudAuthUsers, + cedarTypes, + cedarEntities, + cloudAuthUsersCreateTrg, + cedarRelationships, + cloudAuthUsersDeleteTrg, + cloudAuthUserEmails, + cloudAuthUserPhoneNumbers, + cloudAuthProjects, + cloudAuthApis, + cloudAuthApisProjectIdx, + cloudAuthApisCreateTrg, + cloudAuthApisDeleteTrg, + cloudAuthFunctions, + cloudAuthFunctionsApiIdx, + cloudAuthFunctionsCreateTrg, + cloudAuthFunctionsDeleteTrg, + cloudAuthMeta, + cloudAuthCryptoKeys, + cloudAuthCryptoKeysExternalCryptoKeyIdIdx, + cloudAuthSessions, + cloudAuthSessionsUserIdx, + cloudAuthSessionsCryptoKeyIdx, + cloudAuthSessionsExternalSessionIdIdx, + cloudAuthSessionsUpdateTimeTrg, + cloudAuthOtpCodes, + cloudAuthOtpCodesSessionIdIdx, + cloudAuthCorks, + cloudAuthCorksCryptoKeyIdx, + cloudAuthCorksBearerIdx, + cloudAuthCorksAudienceIdx, + cloudAuthCorksIssuerIdx, + cedarRelationshipsFkEntityIdx, + cedarRelationshipsFkParentIdx, + cedarPolicies, + cedarPolicyTemplates, + cedarPolicyTemplateLinks, + cedarPolicyTemplateLinksFkTemplateIdIdx, + cedarPolicyTemplateLinksFkPrincipalIdx, + cedarPolicyTemplateLinksFkResourceIdx, + cedarAuthorizationLogs + ]; + @override + StreamQueryUpdateRules get streamUpdateRules => const StreamQueryUpdateRules( + [ + WritePropagation( + on: TableUpdateQuery.onTableName('cloud_auth_users', + limitUpdateKind: UpdateKind.delete), + result: [], + ), + WritePropagation( + on: TableUpdateQuery.onTableName('cloud_auth_users', + limitUpdateKind: UpdateKind.delete), + result: [], + ), + WritePropagation( + on: TableUpdateQuery.onTableName('cloud_auth_apis', + limitUpdateKind: UpdateKind.delete), + result: [], + ), + WritePropagation( + on: TableUpdateQuery.onTableName('cloud_auth_apis', + limitUpdateKind: UpdateKind.delete), + result: [], + ), + WritePropagation( + on: TableUpdateQuery.onTableName('cloud_auth_functions', + limitUpdateKind: UpdateKind.delete), + result: [], + ), + WritePropagation( + on: TableUpdateQuery.onTableName('cloud_auth_functions', + limitUpdateKind: UpdateKind.delete), + result: [], + ), + WritePropagation( + on: TableUpdateQuery.onTableName('cloud_auth_sessions', + limitUpdateKind: UpdateKind.delete), + result: [], + ), + ], + ); + @override + int get schemaVersion => 5; +} diff --git a/services/celest_cloud_auth/test/sessions/sessions_repository_test.dart b/services/celest_cloud_auth/test/sessions/sessions_repository_test.dart new file mode 100644 index 000000000..459032bd8 --- /dev/null +++ b/services/celest_cloud_auth/test/sessions/sessions_repository_test.dart @@ -0,0 +1,56 @@ +import 'package:celest_cloud_auth/celest_cloud_auth.dart'; +import 'package:celest_cloud_auth/src/sessions/sessions_repository.dart'; +import 'package:checks/checks.dart'; +import 'package:clock/clock.dart'; +import 'package:test/test.dart'; + +import '../tester.dart'; + +void main() { + final tester = AuthorizationTester(persistData: false); + + group('SessionsRepository', () { + tester.setUp(); + + test('sessionDuration', () async { + final session = await tester.sessions.createSession( + userId: null, + factor: AuthenticationFactorEmailOtp(email: 'test@celest.dev'), + sessionDuration: SessionsRepository.preAuthSessionDuration, + ); + await check(tester.sessions.getSession(sessionId: session.sessionId)) + .completes((it) => it.isNotNull()); + await withClock( + Clock.fixed( + clock + .now() + .add(SessionsRepository.preAuthSessionDuration) + .add(const Duration(seconds: 1)), + ), + () async { + await check(tester.sessions.getSession(sessionId: session.sessionId)) + .completes((it) => it.isNull()); + }, + ); + + await tester.sessions.updateSession( + session: session, + sessionDuration: SessionsRepository.preAuthSessionDuration, + ); + await check(tester.sessions.getSession(sessionId: session.sessionId)) + .completes((it) => it.isNotNull()); + await withClock( + Clock.fixed( + clock + .now() + .add(SessionsRepository.preAuthSessionDuration) + .add(const Duration(seconds: 1)), + ), + () async { + await check(tester.sessions.getSession(sessionId: session.sessionId)) + .completes((it) => it.isNull()); + }, + ); + }); + }); +} diff --git a/services/celest_cloud_auth/test/tester.dart b/services/celest_cloud_auth/test/tester.dart index a7c57c10f..e3eeb1344 100644 --- a/services/celest_cloud_auth/test/tester.dart +++ b/services/celest_cloud_auth/test/tester.dart @@ -306,6 +306,7 @@ final class AuthorizationTester { final session = await sessions.createSession( userId: userId, factor: AuthenticationFactorEmailOtp(email: email), + sessionDuration: SessionsRepository.postAuthSessionDuration, ); final cork = await corks.createCork( user: user, diff --git a/services/celest_cloud_hub/bin/cloud_hub.dart b/services/celest_cloud_hub/bin/cloud_hub.dart index e63edfe4d..7960994dd 100644 --- a/services/celest_cloud_hub/bin/cloud_hub.dart +++ b/services/celest_cloud_hub/bin/cloud_hub.dart @@ -10,6 +10,8 @@ import 'package:celest_cloud_auth/celest_cloud_auth.dart'; import 'package:celest_cloud_auth/src/authorization/authorizer.dart'; import 'package:celest_cloud_auth/src/authorization/corks_repository.dart'; import 'package:celest_cloud_auth/src/crypto/crypto_key_repository.dart'; +import 'package:celest_cloud_auth/src/sessions/sessions_repository.dart'; +import 'package:celest_cloud_auth/src/users/users_repository.dart'; import 'package:celest_cloud_hub/src/auth/auth_interceptor.dart'; import 'package:celest_cloud_hub/src/database/cloud_hub_database.dart'; import 'package:celest_cloud_hub/src/database/db_functions.dart'; @@ -103,6 +105,12 @@ Future _run() async { final authMiddleware = AuthorizationMiddleware( corks: CorksRepository(issuer: issuer, db: db, cryptoKeys: cryptoKeys), + sessions: SessionsRepository( + corks: CorksRepository(issuer: issuer, db: db, cryptoKeys: cryptoKeys), + cryptoKeys: cryptoKeys, + db: db, + users: UsersRepository(db: db), + ), db: db.cloudAuth, ); diff --git a/services/celest_cloud_hub/lib/src/auth/auth_interceptor.dart b/services/celest_cloud_hub/lib/src/auth/auth_interceptor.dart index dbc1cfe30..841050450 100644 --- a/services/celest_cloud_hub/lib/src/auth/auth_interceptor.dart +++ b/services/celest_cloud_hub/lib/src/auth/auth_interceptor.dart @@ -3,6 +3,8 @@ import 'package:celest_cloud_auth/src/authorization/corks_repository.dart'; import 'package:celest_cloud_auth/src/context.dart'; import 'package:celest_cloud_auth/src/model/cookie.dart'; import 'package:celest_cloud_auth/src/model/interop.dart'; +import 'package:celest_cloud_auth/src/sessions/sessions_repository.dart'; +import 'package:celest_cloud_hub/src/services/service_mixin.dart'; import 'package:celest_core/celest_core.dart' as core; import 'package:celest_core/celest_core.dart'; import 'package:collection/collection.dart'; @@ -10,7 +12,12 @@ import 'package:corks_cedar/corks_cedar.dart'; import 'package:grpc/grpc.dart'; import 'package:meta/meta.dart'; -typedef _Deps = ({CorksRepository corks, CloudAuthDatabaseAccessors db}); +typedef _Deps = + ({ + CorksRepository corks, + SessionsRepository sessions, + CloudAuthDatabaseAccessors db, + }); /// {@template celest_cloud_auth.request_authorizer} /// A middleware that authorizes requests based on the current policy set. @@ -19,11 +26,13 @@ extension type AuthorizationMiddleware._(_Deps _deps) implements Object { /// {@macro celest_cloud_auth.request_authorizer} AuthorizationMiddleware({ required CorksRepository corks, + required SessionsRepository sessions, required CloudAuthDatabaseAccessors db, - }) : this._((corks: corks, db: db)); + }) : this._((corks: corks, sessions: sessions, db: db)); CorksRepository get _corks => _deps.corks; CloudAuthDatabaseAccessors get _db => _deps.db; + SessionsRepository get _sessions => _deps.sessions; /// Authenticates the request and returns the user if the request is /// authorized. @@ -73,13 +82,18 @@ extension type AuthorizationMiddleware._(_Deps _deps) implements Object { request.cork = cork; switch (cork.bearer) { case EntityUid(type: 'Celest::Session', id: final sessionId): - final session = await _db.getSession(sessionId: sessionId); + final sessionTid = TypeId.tryDecode(sessionId); + if (sessionTid == null) { + context.logger.severe('Invalid session ID: $sessionId'); + throw const UnauthorizedException('Invalid session ID'); + } + final session = await _sessions.getSession(sessionId: sessionTid); if (session == null) { - throw const UnauthorizedException('Invalid session'); + throw UnauthorizedException('Invalid session: $sessionId'); } final user = await _db.getUser(userId: session.userId); if (user == null) { - throw const UnauthorizedException('Invalid user'); + throw UnauthorizedException('Invalid user: ${session.userId}'); } context.logger.finest('Found user for cork: $user'); return (user, user.toEntity());