Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DataStore and GraphQL API Cognito Public Request #1736

Closed
4 of 9 tasks
MarlonJD opened this issue Jun 14, 2022 · 14 comments
Closed
4 of 9 tasks

DataStore and GraphQL API Cognito Public Request #1736

MarlonJD opened this issue Jun 14, 2022 · 14 comments
Assignees
Labels
datastore Issues related to the DataStore Category duplicate This issue or pull request already exists pending-triage This issue is in the backlog of issues to triage

Comments

@MarlonJD
Copy link
Contributor

MarlonJD commented Jun 14, 2022

Description

Hello. I created graphql based api with amplify.
Cognito is the default auth for api.
I updated auth with unauthorized user to user.
My models have public accesses like public for read. When i'm trying to access anything from related model without user signed. It gives me error that i didnt sign in with cognito.
I tried public with provider: iam not works.
I tried public with provider: apiKey not works.
It always gave me to there is no token for signed cognito user.
When i add multiple api configuration. Datastore starting to give me error for giving apiName for this, but datastore doesnt have apiName parameter I think. And Amplify.API.* not run without huge configrations.
I think it should work without any configuration more like this. How can i achieve this ?
I cannot access anything without user signed in.
I need help.

Categories

  • Analytics
  • API (REST)
  • API (GraphQL)
  • Auth
  • Authenticator
  • DataStore
  • Storage

Steps to Reproduce

Cognito Based GraphQL API.
I cannot access any model that public read access (not signed user)

Screenshots

No response

Platforms

  • iOS
  • Android

Android Device/Emulator API Level

API 21

Environment

[✓] Flutter (Channel stable, 3.0.1, on macOS 12.4 21F79 darwin-x64, locale tr)
    • Flutter version 3.0.1 at /Users/marlonjd/flutter/flutter2
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision fb57da5f94 (4 weeks ago), 2022-05-19 15:50:29 -0700
    • Engine revision caaafc5604
    • Dart version 2.17.1
    • DevTools version 2.12.2

[✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
    • Android SDK at /Users/marlonjd/Library/Android/sdk
    • Platform android-32, build-tools 32.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)

[✓] VS Code (version 1.67.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.42.0

[✓] Connected device (3 available)
    • FF iPod touch (mobile) • be3091413ece7869d08367bf2985276a1e125390 • ios            • iOS 15.5 19F77
    • macOS (desktop)        • macos                                    • darwin-x64     • macOS 12.4 21F79 darwin-x64
    • Chrome (web)           • chrome                                   • web-javascript • Google Chrome 102.0.5005.115

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

Dependencies

Dart SDK 2.17.1
Flutter SDK 3.0.1
monolibmobile 1.0.0+1

dependencies:
- amplify_analytics_pinpoint 0.5.1 [amplify_analytics_pinpoint_android amplify_analytics_pinpoint_ios amplify_analytics_plugin_interface amplify_core flutter plugin_platform_interface]
- amplify_api 0.5.1 [amplify_api_plugin_interface amplify_core amplify_api_android amplify_api_ios collection flutter meta plugin_platform_interface]
- amplify_auth_cognito 0.5.1 [amplify_auth_cognito_android amplify_auth_cognito_ios amplify_auth_plugin_interface amplify_core collection flutter plugin_platform_interface]
- amplify_datastore 0.5.1 [flutter amplify_datastore_plugin_interface amplify_core plugin_platform_interface meta collection async]
- amplify_flutter 0.5.1 [amplify_analytics_plugin_interface amplify_api_plugin_interface amplify_auth_plugin_interface amplify_core amplify_datastore_plugin_interface amplify_flutter_android amplify_flutter_ios amplify_storage_plugin_interface collection flutter json_annotation meta plugin_platform_interface]
- amplify_storage_s3 0.5.1 [flutter amplify_storage_plugin_interface plugin_platform_interface amplify_storage_s3_android amplify_storage_s3_ios amplify_core]
- cached_network_image 3.2.1 [flutter flutter_cache_manager octo_image cached_network_image_platform_interface cached_network_image_web]
- card_swiper 2.0.4 [flutter]
- cloud_firestore 3.1.17 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta]
- cupertino_icons 1.0.4
- file_picker 3.0.4 [flutter flutter_web_plugins flutter_plugin_android_lifecycle plugin_platform_interface]
- firebase_analytics 9.1.9 [firebase_analytics_platform_interface firebase_analytics_web firebase_core firebase_core_platform_interface flutter]
- firebase_auth 3.3.19 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta]
- firebase_core 1.17.1 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_messaging 11.4.1 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- firebase_storage 10.2.17 [firebase_core firebase_core_platform_interface firebase_storage_platform_interface firebase_storage_web flutter]
- flutter 0.0.0 [characters collection material_color_utilities meta vector_math sky_engine]
- flutter_cache_manager 3.3.0 [clock collection file flutter http path path_provider pedantic rxdart sqflite uuid]
- flutter_chat_types 3.3.4 [equatable json_annotation meta]
- flutter_chat_ui 1.5.8 [flutter diffutil_dart equatable flutter_chat_types flutter_link_previewer flutter_parsed_text intl meta photo_view url_launcher visibility_detector]
- flutter_custom_carousel_slider 1.2.0 [flutter]
- flutter_firebase_chat_core 1.5.4 [flutter cloud_firestore firebase_auth firebase_core flutter_chat_types meta]
- flutter_local_notifications 9.5.3+1 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone]
- flutter_localizations 0.0.0 [flutter intl characters clock collection material_color_utilities meta path vector_math]
- flutter_mailer 2.0.1 [flutter]
- geo 0.3.0 [meta]
- get 4.6.5 [flutter]
- get_storage 2.0.3 [flutter get path_provider]
- getwidget 3.0.1 [flutter]
- http 0.13.4 [async http_parser meta path]
- image_picker 0.8.5+3 [flutter image_picker_android image_picker_for_web image_picker_ios image_picker_platform_interface]
- intl 0.17.0 [clock path]
- location 4.4.0 [flutter location_platform_interface location_web]
- material_design_icons_flutter 5.0.6595 [flutter]
- mime 1.0.2
- open_file 3.2.1 [flutter ffi]
- path_provider 2.0.10 [flutter path_provider_android path_provider_ios path_provider_linux path_provider_macos path_provider_platform_interface path_provider_windows]
- qr_flutter 4.0.0 [flutter qr]
- rive 0.8.4 [collection flutter graphs http meta]
- stories_for_flutter 1.2.0 [flutter flutter_web_plugins]

transitive dependencies:
- amplify_analytics_pinpoint_android 0.5.1 [flutter]
- amplify_analytics_pinpoint_ios 0.5.1 [flutter]
- amplify_analytics_plugin_interface 0.5.1 [amplify_core flutter meta]
- amplify_api_android 0.5.1 [flutter]
- amplify_api_ios 0.5.1 [amplify_core flutter]
- amplify_api_plugin_interface 0.5.1 [amplify_core collection flutter json_annotation meta]
- amplify_auth_cognito_android 0.5.1 [flutter]
- amplify_auth_cognito_ios 0.5.1 [amplify_core flutter]
- amplify_auth_plugin_interface 0.5.1 [amplify_core flutter meta]
- amplify_core 0.5.1 [collection date_time_format flutter meta plugin_platform_interface uuid]
- amplify_datastore_plugin_interface 0.5.1 [flutter meta collection amplify_core]
- amplify_flutter_android 0.5.1 [flutter]
- amplify_flutter_ios 0.5.1 [amplify_core flutter]
- amplify_storage_plugin_interface 0.5.1 [flutter meta amplify_core]
- amplify_storage_s3_android 0.5.1 [flutter]
- amplify_storage_s3_ios 0.5.1 [flutter]
- args 2.3.1
- async 2.8.2 [collection meta]
- cached_network_image_platform_interface 1.0.0 [flutter flutter_cache_manager]
- cached_network_image_web 1.0.1 [flutter flutter_cache_manager cached_network_image_platform_interface]
- characters 1.2.0
- charcode 1.3.1
- clock 1.1.0
- cloud_firestore_platform_interface 5.5.7 [collection firebase_core flutter meta plugin_platform_interface]
- cloud_firestore_web 2.6.16 [cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins js]
- collection 1.16.0
- cross_file 0.3.3+1 [js meta]
- crypto 3.0.2 [typed_data]
- csslib 0.17.2 [source_span]
- date_time_format 2.0.1
- dbus 0.7.4 [args ffi meta xml]
- diffutil_dart 3.0.0
- equatable 2.0.3 [collection meta]
- ffi 1.2.1
- file 6.1.2 [meta path]
- firebase_analytics_platform_interface 3.1.7 [firebase_core flutter meta plugin_platform_interface]
- firebase_analytics_web 0.4.0+14 [firebase_analytics_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js]
- firebase_auth_platform_interface 6.2.7 [firebase_core flutter meta plugin_platform_interface]
- firebase_auth_web 3.3.16 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser intl js meta]
- firebase_core_platform_interface 4.4.0 [collection flutter meta plugin_platform_interface]
- firebase_core_web 1.6.4 [firebase_core_platform_interface flutter flutter_web_plugins js meta]
- firebase_messaging_platform_interface 3.5.1 [firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 2.4.1 [firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta]
- firebase_storage_platform_interface 4.1.7 [collection firebase_core flutter meta plugin_platform_interface]
- firebase_storage_web 3.2.16 [async firebase_core firebase_core_web firebase_storage_platform_interface flutter flutter_web_plugins http js meta]
- flutter_blurhash 0.7.0 [flutter]
- flutter_link_previewer 2.6.6 [flutter flutter_chat_types flutter_linkify html http linkify meta url_launcher]
- flutter_linkify 5.0.2 [flutter linkify]
- flutter_local_notifications_linux 0.4.2 [flutter flutter_local_notifications_platform_interface dbus path xdg_directories]
- flutter_local_notifications_platform_interface 5.0.0 [flutter plugin_platform_interface]
- flutter_parsed_text 2.2.1 [flutter]
- flutter_plugin_android_lifecycle 2.0.6 [flutter]
- flutter_web_plugins 0.0.0 [flutter js characters collection material_color_utilities meta vector_math]
- graphs 2.1.0 [collection]
- html 0.15.0 [csslib source_span]
- http_parser 4.0.1 [collection source_span string_scanner typed_data]
- image_picker_android 0.8.5 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface]
- image_picker_for_web 2.1.8 [flutter flutter_web_plugins image_picker_platform_interface]
- image_picker_ios 0.8.5+5 [flutter image_picker_platform_interface]
- image_picker_platform_interface 2.5.0 [cross_file flutter http plugin_platform_interface]
- js 0.6.4
- json_annotation 4.5.0 [meta]
- linkify 4.1.0
- location_platform_interface 2.3.0 [flutter meta plugin_platform_interface]
- location_web 3.1.1 [flutter flutter_web_plugins http_parser js location_platform_interface meta]
- material_color_utilities 0.1.4
- meta 1.7.0
- octo_image 1.0.2 [flutter flutter_blurhash]
- path 1.8.1
- path_provider_android 2.0.14 [flutter path_provider_platform_interface]
- path_provider_ios 2.0.9 [flutter path_provider_platform_interface]
- path_provider_linux 2.1.7 [ffi flutter path path_provider_platform_interface xdg_directories]
- path_provider_macos 2.0.6 [flutter path_provider_platform_interface]
- path_provider_platform_interface 2.0.4 [flutter platform plugin_platform_interface]
- path_provider_windows 2.0.7 [ffi flutter path path_provider_platform_interface win32]
- pedantic 1.11.1
- petitparser 5.0.0 [meta]
- photo_view 0.13.0 [flutter]
- platform 3.1.0
- plugin_platform_interface 2.1.2 [meta]
- process 4.2.4 [file path platform]
- qr 2.1.0 [meta]
- rxdart 0.27.4
- sky_engine 0.0.99
- source_span 1.8.2 [collection path term_glyph]
- sqflite 2.0.2+1 [flutter sqflite_common path]
- sqflite_common 2.2.1+1 [synchronized path meta]
- string_scanner 1.1.0 [charcode source_span]
- synchronized 3.0.0+2
- term_glyph 1.2.0
- timezone 0.8.0 [path]
- typed_data 1.3.1 [collection]
- url_launcher 6.1.2 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows]
- url_launcher_android 6.0.17 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.0.17 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.0.1 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.0.1 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.0.5 [flutter plugin_platform_interface]
- url_launcher_web 2.0.11 [flutter flutter_web_plugins url_launcher_platform_interface]
- url_launcher_windows 3.0.1 [flutter url_launcher_platform_interface]
- uuid 3.0.6 [crypto]
- vector_math 2.1.2
- visibility_detector 0.2.2 [flutter]
- win32 2.6.1 [ffi]
- xdg_directories 0.2.0+1 [meta path process]
- xml 6.1.0 [collection meta petitparser]

Device

iPod 7

OS

iOS 15.5

CLI Version

7.6.21

Additional Context

No response

@dnys1
Copy link
Contributor

dnys1 commented Jun 14, 2022

Hi @MarlonJD - please provide your GraphQL schema, and the error being shown in the console when you get a chance. Thanks, and sorry you are experiencing this issue.

@dnys1 dnys1 added datastore Issues related to the DataStore Category pending-triage This issue is in the backlog of issues to triage labels Jun 14, 2022
@MarlonJD
Copy link
Contributor Author

GraphQL Schema:

type Internship @model @auth(rules: [{allow: private, operations: [create, read, update]}, {allow: owner}]) {
  id: ID!
  transactions: [Transaction] @hasMany(indexName: "byInternship", fields: ["id"])
  company: Company @belongsTo(fields: ["companyID"])
  companyID: ID! @index(name: "byCompany")
  student: Student @belongsTo(fields: ["studentID"])
  studentID: ID! @index(name: "byStudent")
}

type Manager @model @auth(rules: [{allow: private, operations: [read]}, {allow: owner}]) {
  id: ID!
  cognitoId: ID
  company: Company @belongsTo(fields: ["companyID"])
  companyID: ID! @index(name: "byCompany")
  university: University @belongsTo(fields: ["universityID"])
  universityID: ID! @index(name: "byUniversity")
}

type CompanySettings @model @auth(rules: [{allow: private}]) {
  id: ID!
  company: Company @hasOne
  coordinate: String!
  distance_limit: String!
  isLunchOut: Boolean!
  isLunchIn: Boolean!
  isHolidayIn: Boolean!
  isHolidayOut: Boolean!
  isDismissal: Boolean!
  logCoordinates: Boolean!
}

type Company @model @auth(rules: [{allow: private, operations: [read, create]}, {allow: owner, ownerField: "managerIds", operations: [update, delete]}]) {
  id: ID!
  internships: [Internship] @hasMany(indexName: "byCompany", fields: ["id"])
  managers: [Manager] @hasMany(indexName: "byCompany", fields: ["id"])
  managerIds: [String]
  name: String!
  countryCode: String!
  isConfirmed: Boolean!
  settings: CompanySettings @belongsTo(fields: ["settingsID"])
  settingsID: ID! @index(name: "bySettings")
}


enum TransactionType {
  IN
  OUT
  LUNCH_EXIT
  LUNCH_ARRIVAL
  HOLIDAY_EXIT
  HOLIDAY_ARRIVE
  DISMISSAL
}

type Transaction @model @auth(rules: [{allow: private, operations: [create, read, update]}, {allow: owner}]) {
  id: ID!
  type: TransactionType
  datetime: AWSDateTime
  internshipID: ID! @index(name: "byInternship")
  internship: Internship @belongsTo(fields: ["internshipID"])
  studentID: ID! @index(name: "byStudent")
  student: Student @belongsTo(fields: ["studentID"])
}

type DepartmentOrigin @model @auth(
  rules: [
    {allow: private, operations: [read]}, {allow: groups, groups: ["admin"], operations: [create, update, delete]}]) {
  id: ID!
  nameEn: String!
  nameTr: String!
}

type Department @model @auth(rules: [{allow: public, operations: [read], provider: iam}, {allow: private}]) {
  id: ID!
  nameEn: String!
  nameTr: String!
  university: University @belongsTo(fields: ["universityID"])
  universityID: ID! @index(name: "byUniversity")
  mainStudents: [Student] @hasMany(indexName: "byDepartmentMainStudents", fields: ["id"])
  students: [Student] @manyToMany(relationName: "DepartmentStudents")
  teachers: [Teacher] @manyToMany(relationName: "DepartmentTeachers")
}

enum Gender {
  MALE,
  FEMALE,
  NOT_SPECIFIED
}

enum UniversityClass {
  PREPERATION,
  FIRST,
  SECOND,
  THIRD,
  FOURTH,
  FIFTH,
  SIXTH
}

enum UniversityLevel {
  ASSOCIATE,
  BARCHELOR,
  MASTER,
  PHD,
}

type Student @model @auth(rules: [{allow: private, operations: [read, create]}, {allow: owner, ownerField: "cognitoId", operations: [update, delete]}]) {
  id: ID!
  photo: String!
  universityNumber: String!
  email: String!
  phone: String!
  birthday: AWSDate!
  gender: Gender!
  cognitoId: ID!
  transactions: [Transaction] @hasMany(indexName: "byStudent", fields: ["id"])
  internship: Internship @hasOne
  universityClass: UniversityClass!
  universityLevel: UniversityLevel!
  department: Department @belongsTo(fields: ["departmentID"])
  departmentID: ID! @index(name: "byDepartmentMainStudents")
  departments: [Department] @manyToMany(relationName: "DepartmentStudents")
}

enum TeacherTitle {
  RTA,
  IN,
  L,
  AP,
  FP,
  HRP
}

type Teacher @model @auth(rules: [{allow: private, operations: [read, create]}, {allow: owner, ownerField: "cognitoId", operations: [update, delete]}]) {
  id: ID!
  photo: String!
  university: University @belongsTo(fields: ["universityID"])
  universityNumber: String!
  email: String!
  phone: String!
  areas: String!
  title: TeacherTitle!
  cognitoId: ID!
  departments: [Department] @manyToMany(relationName: "DepartmentTeachers")
  universityID: ID! @index(name: "byUniversity")
}

type University @model @auth(rules: [{allow: public, operations: [read]}, {allow: private, operations: [create, read]}, {allow: owner, ownerField: "managerIds", operations: [update, delete, update, delete]}]) {
  id: ID!
  nameEn: String!
  nameTr: String!
  departments: [Department] @hasMany(indexName: "byUniversity", fields: ["id"])
  supportMail: String!
  logo: String!
  teacherCount: Int!
  studentCount: Int!
  managers: [Manager] @hasMany(indexName: "byUniversity", fields: ["id"])
  managerIds: [String]
  teachers: [Teacher] @hasMany(indexName: "byUniversity", fields: ["id"])
}

I'm trying to access Universities without cognito user as public. like this:

try {
      var universityRequest = ModelQueries.list(University.classType);

      final universityResponse = await Amplify.API
          .query(
            request: universityRequest,
          )
          .response;

      universities = universityResponse.data?.items;
      update();
      await Amplify.DataStore.stop();
      await Amplify.DataStore.start();
    } on ApiException catch (e) {
      debugPrint('Query failed: $e');
    }

and it's giving me this error:

flutter: Trying to get universities
GraphQL query operation failed: APIError: Failed to retrieve authorization token.
Caused by:
AuthError: There is no user signed in to retreive cognito tokens
Recovery suggestion: Call Auth.signIn to sign in a user and then call Auth.fetchSession
flutter: Query failed: ApiException(message: Failed to retrieve authorization token., recoverySuggestion: , underlyingException: The operation couldn’t be completed. (Amplify.AuthError error 6.))
flutter: Trying to get universities
GraphQL query operation failed: APIError: Failed to retrieve authorization token.
Caused by:
AuthError: There is no user signed in to retreive cognito tokens
Recovery suggestion: Call Auth.signIn to sign in a user and then call Auth.fetchSession
flutter: Query failed: ApiException(message: Failed to retrieve authorization token., recoverySuggestion: , underlyingException: The operation couldn’t be completed. (Amplify.AuthError error 6.))

@dnys1
Copy link
Contributor

dnys1 commented Jun 15, 2022

Hi @MarlonJD - can you confirm you are passing authModeStrategy: AuthModeStrategy.multiAuth to the DataStore plugin constructor as outlined here? Can you also confirm that when using Amplify.API methods, you are using the apiName parameter for all non-default auth modes? That is, when using API Key/IAM/any secondary auth mode with Amplify.API, you'll need to set up additional APIs as you mentioned and pass in the name to the apiName parameter as outlined here.

@MarlonJD
Copy link
Contributor Author

Yes here's my amplify init code:

  final AmplifyAPI _apiPlugin = AmplifyAPI(
    modelProvider: ModelProvider.instance,
  );
  final AmplifyAuthCognito _authPlugin = AmplifyAuthCognito();
  final AmplifyDataStore _dataStorePlugin =
      AmplifyDataStore(modelProvider: ModelProvider.instance,
      authModeStrategy: AuthModeStrategy.multiAuth);
  final AmplifyAnalyticsPinpoint _analyticsPlugin = AmplifyAnalyticsPinpoint();
  final AmplifyStorageS3 _storagePlugin = AmplifyStorageS3();

try {
    // add Amplify plugins
    await _amplify.addPlugins([
      _authPlugin,
      _apiPlugin,
      _dataStorePlugin,
      _analyticsPlugin,
      _storagePlugin
    ]);
    // configure Amplify
    // note that Amplify cannot be configured more than once!
    await _amplify.configure(amplifyconfig).then((_) {
      isAmlifyConfigured(true);
      debugPrint("Amplify Configured.");
    });

    // ask permission for pinpoint push notifications

  } on AmplifyAlreadyConfiguredException {
    debugPrint(
        "Tried to reconfigure Amplify; this error occur when the app hot-reload");
  } catch (e) {
    // error handling can be improved for sure!
    // but this will be sufficient for the purposes of this tutorial
    debugPrint('An error occurred while configuring Amplify: $e');
  }

And yes I tried apiName and it's running when I'm trying Amplify.API.* but I cannot run with DataStore anymore if I add multi auth to amplifyconfiguration.dart, It gaves me to give me apiName but there's no configuration for DataStore.* like apiName parameter.

@HuiSF
Copy link
Member

HuiSF commented Jul 14, 2022

but I cannot run with DataStore anymore if I add multi auth to amplifyconfiguration.dart

We've identified the cause for this one due to a lack of support for this kind of use case (multi-auth for API + multi-auth for DataStore in the same App).

Can you paste modelSchemaDefinition.authRules info in the generated models? (for the models that represent the intermediate models of many-to-many).

@MarlonJD
Copy link
Contributor Author

Thanks for the reply, but i didn't understand that where can I found modelSchemaDefinition.authRules ?

@Jordan-Nelson
Copy link
Member

@MarlonJD - This would be found in the generated files for some of the models (Company, Teacher, Student)

@Jordan-Nelson Jordan-Nelson added the pending-community-response Pending response from the issue opener or other community members label Jul 27, 2022
@MarlonJD
Copy link
Contributor Author

@MarlonJD - This would be found in the generated files for some of the models (Company, Teacher, Student)

Okay but which file? Should i add all generated file to here?

@Jordan-Nelson Jordan-Nelson added pending-triage This issue is in the backlog of issues to triage and removed pending-triage This issue is in the backlog of issues to triage pending-community-response Pending response from the issue opener or other community members labels Aug 1, 2022
@HuiSF
Copy link
Member

HuiSF commented Aug 1, 2022

@MarlonJD take a look at lib/models you should be able to find

  • DepartmentTeachers
  • DepartmentStudents

Look into this file, you should be able to find modelSchemaDefinition.authRules please paste the info here. thanks

@MarlonJD
Copy link
Contributor Author

MarlonJD commented Aug 1, 2022

There is authRules in Department but not in DepartmentStudent and DepartmentTeacher
on Department there is something like this.
I changed some permissions after I created this issue. So I does not matter it's private or public.
It seems like there is auth rules on main model but not in its nested manytomany model.

In department

...
modelSchemaDefinition.authRules = [
      AuthRule(
        authStrategy: AuthStrategy.PUBLIC,
        provider: AuthRuleProvider.IAM,
        operations: [
          ModelOperation.READ
        ]),
      AuthRule(
        authStrategy: AuthStrategy.PRIVATE,
        operations: [
          ModelOperation.CREATE,
          ModelOperation.UPDATE,
          ModelOperation.DELETE,
          ModelOperation.READ
        ])
    ];
...

on Teacher:

...
modelSchemaDefinition.authRules = [
      AuthRule(
        authStrategy: AuthStrategy.PRIVATE,
        operations: [
          ModelOperation.READ,
          ModelOperation.CREATE
        ]),
      AuthRule(
        authStrategy: AuthStrategy.OWNER,
        ownerField: "cognitoId",
        identityClaim: "cognito:username",
        provider: AuthRuleProvider.USERPOOLS,
        operations: [
          ModelOperation.UPDATE,
          ModelOperation.DELETE
        ])
    ];
...

DepartmentStudents:

/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
*  http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// NOTE: This file is generated and may not follow lint rules defined in your app
// Generated files can be excluded from analysis in analysis_options.yaml
// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis

// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously

import 'ModelProvider.dart';
import 'package:amplify_core/amplify_core.dart';
import 'package:flutter/foundation.dart';


/** This is an auto generated class representing the DepartmentStudents type in your schema. */
@immutable
class DepartmentStudents extends Model {
  static const classType = const _DepartmentStudentsModelType();
  final String id;
  final Student? _student;
  final Department? _department;
  final TemporalDateTime? _createdAt;
  final TemporalDateTime? _updatedAt;

  @override
  getInstanceType() => classType;
  
  @override
  String getId() {
    return id;
  }
  
  Student get student {
    try {
      return _student!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  Department get department {
    try {
      return _department!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  TemporalDateTime? get createdAt {
    return _createdAt;
  }
  
  TemporalDateTime? get updatedAt {
    return _updatedAt;
  }
  
  const DepartmentStudents._internal({required this.id, required student, required department, createdAt, updatedAt}): _student = student, _department = department, _createdAt = createdAt, _updatedAt = updatedAt;
  
  factory DepartmentStudents({String? id, required Student student, required Department department}) {
    return DepartmentStudents._internal(
      id: id == null ? UUID.getUUID() : id,
      student: student,
      department: department);
  }
  
  bool equals(Object other) {
    return this == other;
  }
  
  @override
  bool operator ==(Object other) {
    if (identical(other, this)) return true;
    return other is DepartmentStudents &&
      id == other.id &&
      _student == other._student &&
      _department == other._department;
  }
  
  @override
  int get hashCode => toString().hashCode;
  
  @override
  String toString() {
    var buffer = new StringBuffer();
    
    buffer.write("DepartmentStudents {");
    buffer.write("id=" + "$id" + ", ");
    buffer.write("student=" + (_student != null ? _student!.toString() : "null") + ", ");
    buffer.write("department=" + (_department != null ? _department!.toString() : "null") + ", ");
    buffer.write("createdAt=" + (_createdAt != null ? _createdAt!.format() : "null") + ", ");
    buffer.write("updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null"));
    buffer.write("}");
    
    return buffer.toString();
  }
  
  DepartmentStudents copyWith({String? id, Student? student, Department? department}) {
    return DepartmentStudents._internal(
      id: id ?? this.id,
      student: student ?? this.student,
      department: department ?? this.department);
  }
  
  DepartmentStudents.fromJson(Map<String, dynamic> json)  
    : id = json['id'],
      _student = json['student']?['serializedData'] != null
        ? Student.fromJson(new Map<String, dynamic>.from(json['student']['serializedData']))
        : null,
      _department = json['department']?['serializedData'] != null
        ? Department.fromJson(new Map<String, dynamic>.from(json['department']['serializedData']))
        : null,
      _createdAt = json['createdAt'] != null ? TemporalDateTime.fromString(json['createdAt']) : null,
      _updatedAt = json['updatedAt'] != null ? TemporalDateTime.fromString(json['updatedAt']) : null;
  
  Map<String, dynamic> toJson() => {
    'id': id, 'student': _student?.toJson(), 'department': _department?.toJson(), 'createdAt': _createdAt?.format(), 'updatedAt': _updatedAt?.format()
  };

  static final QueryField ID = QueryField(fieldName: "departmentStudents.id");
  static final QueryField STUDENT = QueryField(
    fieldName: "student",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Student).toString()));
  static final QueryField DEPARTMENT = QueryField(
    fieldName: "department",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Department).toString()));
  static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) {
    modelSchemaDefinition.name = "DepartmentStudents";
    modelSchemaDefinition.pluralName = "DepartmentStudents";
    
    modelSchemaDefinition.addField(ModelFieldDefinition.id());
    
    modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo(
      key: DepartmentStudents.STUDENT,
      isRequired: true,
      targetName: "studentID",
      ofModelName: (Student).toString()
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo(
      key: DepartmentStudents.DEPARTMENT,
      isRequired: true,
      targetName: "departmentID",
      ofModelName: (Department).toString()
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField(
      fieldName: 'createdAt',
      isRequired: false,
      isReadOnly: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.dateTime)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField(
      fieldName: 'updatedAt',
      isRequired: false,
      isReadOnly: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.dateTime)
    ));
  });
}

class _DepartmentStudentsModelType extends ModelType<DepartmentStudents> {
  const _DepartmentStudentsModelType();
  
  @override
  DepartmentStudents fromJson(Map<String, dynamic> jsonData) {
    return DepartmentStudents.fromJson(jsonData);
  }
}

DepartmentTeachers:

/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
*  http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// NOTE: This file is generated and may not follow lint rules defined in your app
// Generated files can be excluded from analysis in analysis_options.yaml
// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis

// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously

import 'ModelProvider.dart';
import 'package:amplify_core/amplify_core.dart';
import 'package:flutter/foundation.dart';


/** This is an auto generated class representing the DepartmentTeachers type in your schema. */
@immutable
class DepartmentTeachers extends Model {
  static const classType = const _DepartmentTeachersModelType();
  final String id;
  final Department? _department;
  final Teacher? _teacher;
  final TemporalDateTime? _createdAt;
  final TemporalDateTime? _updatedAt;

  @override
  getInstanceType() => classType;
  
  @override
  String getId() {
    return id;
  }
  
  Department get department {
    try {
      return _department!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  Teacher get teacher {
    try {
      return _teacher!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  TemporalDateTime? get createdAt {
    return _createdAt;
  }
  
  TemporalDateTime? get updatedAt {
    return _updatedAt;
  }
  
  const DepartmentTeachers._internal({required this.id, required department, required teacher, createdAt, updatedAt}): _department = department, _teacher = teacher, _createdAt = createdAt, _updatedAt = updatedAt;
  
  factory DepartmentTeachers({String? id, required Department department, required Teacher teacher}) {
    return DepartmentTeachers._internal(
      id: id == null ? UUID.getUUID() : id,
      department: department,
      teacher: teacher);
  }
  
  bool equals(Object other) {
    return this == other;
  }
  
  @override
  bool operator ==(Object other) {
    if (identical(other, this)) return true;
    return other is DepartmentTeachers &&
      id == other.id &&
      _department == other._department &&
      _teacher == other._teacher;
  }
  
  @override
  int get hashCode => toString().hashCode;
  
  @override
  String toString() {
    var buffer = new StringBuffer();
    
    buffer.write("DepartmentTeachers {");
    buffer.write("id=" + "$id" + ", ");
    buffer.write("department=" + (_department != null ? _department!.toString() : "null") + ", ");
    buffer.write("teacher=" + (_teacher != null ? _teacher!.toString() : "null") + ", ");
    buffer.write("createdAt=" + (_createdAt != null ? _createdAt!.format() : "null") + ", ");
    buffer.write("updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null"));
    buffer.write("}");
    
    return buffer.toString();
  }
  
  DepartmentTeachers copyWith({String? id, Department? department, Teacher? teacher}) {
    return DepartmentTeachers._internal(
      id: id ?? this.id,
      department: department ?? this.department,
      teacher: teacher ?? this.teacher);
  }
  
  DepartmentTeachers.fromJson(Map<String, dynamic> json)  
    : id = json['id'],
      _department = json['department']?['serializedData'] != null
        ? Department.fromJson(new Map<String, dynamic>.from(json['department']['serializedData']))
        : null,
      _teacher = json['teacher']?['serializedData'] != null
        ? Teacher.fromJson(new Map<String, dynamic>.from(json['teacher']['serializedData']))
        : null,
      _createdAt = json['createdAt'] != null ? TemporalDateTime.fromString(json['createdAt']) : null,
      _updatedAt = json['updatedAt'] != null ? TemporalDateTime.fromString(json['updatedAt']) : null;
  
  Map<String, dynamic> toJson() => {
    'id': id, 'department': _department?.toJson(), 'teacher': _teacher?.toJson(), 'createdAt': _createdAt?.format(), 'updatedAt': _updatedAt?.format()
  };

  static final QueryField ID = QueryField(fieldName: "departmentTeachers.id");
  static final QueryField DEPARTMENT = QueryField(
    fieldName: "department",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Department).toString()));
  static final QueryField TEACHER = QueryField(
    fieldName: "teacher",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Teacher).toString()));
  static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) {
    modelSchemaDefinition.name = "DepartmentTeachers";
    modelSchemaDefinition.pluralName = "DepartmentTeachers";
    
    modelSchemaDefinition.addField(ModelFieldDefinition.id());
    
    modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo(
      key: DepartmentTeachers.DEPARTMENT,
      isRequired: true,
      targetName: "departmentID",
      ofModelName: (Department).toString()
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo(
      key: DepartmentTeachers.TEACHER,
      isRequired: true,
      targetName: "teacherID",
      ofModelName: (Teacher).toString()
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField(
      fieldName: 'createdAt',
      isRequired: false,
      isReadOnly: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.dateTime)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField(
      fieldName: 'updatedAt',
      isRequired: false,
      isReadOnly: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.dateTime)
    ));
  });
}

class _DepartmentTeachersModelType extends ModelType<DepartmentTeachers> {
  const _DepartmentTeachersModelType();
  
  @override
  DepartmentTeachers fromJson(Map<String, dynamic> jsonData) {
    return DepartmentTeachers.fromJson(jsonData);
  }
}

Department:

/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
*  http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// NOTE: This file is generated and may not follow lint rules defined in your app
// Generated files can be excluded from analysis in analysis_options.yaml
// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis

// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously

import 'ModelProvider.dart';
import 'package:amplify_core/amplify_core.dart';
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';


/** This is an auto generated class representing the Department type in your schema. */
@immutable
class Department extends Model {
  static const classType = const _DepartmentModelType();
  final String id;
  final String? _nameEn;
  final String? _nameTr;
  final University? _university;
  final List<MainDepartmentStudent>? _mainStudents;
  final List<DepartmentStudents>? _students;
  final List<MainDepartmentTeachers>? _mainTeachers;
  final List<DepartmentTeachers>? _teachers;
  final List<DepartmentManager>? _managers;
  final List<Notice>? _notices;
  final TemporalDateTime? _createdAt;
  final TemporalDateTime? _updatedAt;

  @override
  getInstanceType() => classType;
  
  @override
  String getId() {
    return id;
  }
  
  String get nameEn {
    try {
      return _nameEn!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  String get nameTr {
    try {
      return _nameTr!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  University? get university {
    return _university;
  }
  
  List<MainDepartmentStudent>? get mainStudents {
    return _mainStudents;
  }
  
  List<DepartmentStudents>? get students {
    return _students;
  }
  
  List<MainDepartmentTeachers>? get mainTeachers {
    return _mainTeachers;
  }
  
  List<DepartmentTeachers>? get teachers {
    return _teachers;
  }
  
  List<DepartmentManager>? get managers {
    return _managers;
  }
  
  List<Notice>? get notices {
    return _notices;
  }
  
  TemporalDateTime? get createdAt {
    return _createdAt;
  }
  
  TemporalDateTime? get updatedAt {
    return _updatedAt;
  }
  
  const Department._internal({required this.id, required nameEn, required nameTr, university, mainStudents, students, mainTeachers, teachers, managers, notices, createdAt, updatedAt}): _nameEn = nameEn, _nameTr = nameTr, _university = university, _mainStudents = mainStudents, _students = students, _mainTeachers = mainTeachers, _teachers = teachers, _managers = managers, _notices = notices, _createdAt = createdAt, _updatedAt = updatedAt;
  
  factory Department({String? id, required String nameEn, required String nameTr, University? university, List<MainDepartmentStudent>? mainStudents, List<DepartmentStudents>? students, List<MainDepartmentTeachers>? mainTeachers, List<DepartmentTeachers>? teachers, List<DepartmentManager>? managers, List<Notice>? notices}) {
    return Department._internal(
      id: id == null ? UUID.getUUID() : id,
      nameEn: nameEn,
      nameTr: nameTr,
      university: university,
      mainStudents: mainStudents != null ? List<MainDepartmentStudent>.unmodifiable(mainStudents) : mainStudents,
      students: students != null ? List<DepartmentStudents>.unmodifiable(students) : students,
      mainTeachers: mainTeachers != null ? List<MainDepartmentTeachers>.unmodifiable(mainTeachers) : mainTeachers,
      teachers: teachers != null ? List<DepartmentTeachers>.unmodifiable(teachers) : teachers,
      managers: managers != null ? List<DepartmentManager>.unmodifiable(managers) : managers,
      notices: notices != null ? List<Notice>.unmodifiable(notices) : notices);
  }
  
  bool equals(Object other) {
    return this == other;
  }
  
  @override
  bool operator ==(Object other) {
    if (identical(other, this)) return true;
    return other is Department &&
      id == other.id &&
      _nameEn == other._nameEn &&
      _nameTr == other._nameTr &&
      _university == other._university &&
      DeepCollectionEquality().equals(_mainStudents, other._mainStudents) &&
      DeepCollectionEquality().equals(_students, other._students) &&
      DeepCollectionEquality().equals(_mainTeachers, other._mainTeachers) &&
      DeepCollectionEquality().equals(_teachers, other._teachers) &&
      DeepCollectionEquality().equals(_managers, other._managers) &&
      DeepCollectionEquality().equals(_notices, other._notices);
  }
  
  @override
  int get hashCode => toString().hashCode;
  
  @override
  String toString() {
    var buffer = new StringBuffer();
    
    buffer.write("Department {");
    buffer.write("id=" + "$id" + ", ");
    buffer.write("nameEn=" + "$_nameEn" + ", ");
    buffer.write("nameTr=" + "$_nameTr" + ", ");
    buffer.write("university=" + (_university != null ? _university!.toString() : "null") + ", ");
    buffer.write("createdAt=" + (_createdAt != null ? _createdAt!.format() : "null") + ", ");
    buffer.write("updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null"));
    buffer.write("}");
    
    return buffer.toString();
  }
  
  Department copyWith({String? id, String? nameEn, String? nameTr, University? university, List<MainDepartmentStudent>? mainStudents, List<DepartmentStudents>? students, List<MainDepartmentTeachers>? mainTeachers, List<DepartmentTeachers>? teachers, List<DepartmentManager>? managers, List<Notice>? notices}) {
    return Department._internal(
      id: id ?? this.id,
      nameEn: nameEn ?? this.nameEn,
      nameTr: nameTr ?? this.nameTr,
      university: university ?? this.university,
      mainStudents: mainStudents ?? this.mainStudents,
      students: students ?? this.students,
      mainTeachers: mainTeachers ?? this.mainTeachers,
      teachers: teachers ?? this.teachers,
      managers: managers ?? this.managers,
      notices: notices ?? this.notices);
  }
  
  Department.fromJson(Map<String, dynamic> json)  
    : id = json['id'],
      _nameEn = json['nameEn'],
      _nameTr = json['nameTr'],
      _university = json['university']?['serializedData'] != null
        ? University.fromJson(new Map<String, dynamic>.from(json['university']['serializedData']))
        : null,
      _mainStudents = json['mainStudents'] is List
        ? (json['mainStudents'] as List)
          .where((e) => e?['serializedData'] != null)
          .map((e) => MainDepartmentStudent.fromJson(new Map<String, dynamic>.from(e['serializedData'])))
          .toList()
        : null,
      _students = json['students'] is List
        ? (json['students'] as List)
          .where((e) => e?['serializedData'] != null)
          .map((e) => DepartmentStudents.fromJson(new Map<String, dynamic>.from(e['serializedData'])))
          .toList()
        : null,
      _mainTeachers = json['mainTeachers'] is List
        ? (json['mainTeachers'] as List)
          .where((e) => e?['serializedData'] != null)
          .map((e) => MainDepartmentTeachers.fromJson(new Map<String, dynamic>.from(e['serializedData'])))
          .toList()
        : null,
      _teachers = json['teachers'] is List
        ? (json['teachers'] as List)
          .where((e) => e?['serializedData'] != null)
          .map((e) => DepartmentTeachers.fromJson(new Map<String, dynamic>.from(e['serializedData'])))
          .toList()
        : null,
      _managers = json['managers'] is List
        ? (json['managers'] as List)
          .where((e) => e?['serializedData'] != null)
          .map((e) => DepartmentManager.fromJson(new Map<String, dynamic>.from(e['serializedData'])))
          .toList()
        : null,
      _notices = json['notices'] is List
        ? (json['notices'] as List)
          .where((e) => e?['serializedData'] != null)
          .map((e) => Notice.fromJson(new Map<String, dynamic>.from(e['serializedData'])))
          .toList()
        : null,
      _createdAt = json['createdAt'] != null ? TemporalDateTime.fromString(json['createdAt']) : null,
      _updatedAt = json['updatedAt'] != null ? TemporalDateTime.fromString(json['updatedAt']) : null;
  
  Map<String, dynamic> toJson() => {
    'id': id, 'nameEn': _nameEn, 'nameTr': _nameTr, 'university': _university?.toJson(), 'mainStudents': _mainStudents?.map((MainDepartmentStudent? e) => e?.toJson()).toList(), 'students': _students?.map((DepartmentStudents? e) => e?.toJson()).toList(), 'mainTeachers': _mainTeachers?.map((MainDepartmentTeachers? e) => e?.toJson()).toList(), 'teachers': _teachers?.map((DepartmentTeachers? e) => e?.toJson()).toList(), 'managers': _managers?.map((DepartmentManager? e) => e?.toJson()).toList(), 'notices': _notices?.map((Notice? e) => e?.toJson()).toList(), 'createdAt': _createdAt?.format(), 'updatedAt': _updatedAt?.format()
  };

  static final QueryField ID = QueryField(fieldName: "department.id");
  static final QueryField NAMEEN = QueryField(fieldName: "nameEn");
  static final QueryField NAMETR = QueryField(fieldName: "nameTr");
  static final QueryField UNIVERSITY = QueryField(
    fieldName: "university",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (University).toString()));
  static final QueryField MAINSTUDENTS = QueryField(
    fieldName: "mainStudents",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (MainDepartmentStudent).toString()));
  static final QueryField STUDENTS = QueryField(
    fieldName: "students",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (DepartmentStudents).toString()));
  static final QueryField MAINTEACHERS = QueryField(
    fieldName: "mainTeachers",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (MainDepartmentTeachers).toString()));
  static final QueryField TEACHERS = QueryField(
    fieldName: "teachers",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (DepartmentTeachers).toString()));
  static final QueryField MANAGERS = QueryField(
    fieldName: "managers",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (DepartmentManager).toString()));
  static final QueryField NOTICES = QueryField(
    fieldName: "notices",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Notice).toString()));
  static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) {
    modelSchemaDefinition.name = "Department";
    modelSchemaDefinition.pluralName = "Departments";
    
    modelSchemaDefinition.authRules = [
      AuthRule(
        authStrategy: AuthStrategy.PUBLIC,
        provider: AuthRuleProvider.IAM,
        operations: [
          ModelOperation.READ
        ]),
      AuthRule(
        authStrategy: AuthStrategy.PRIVATE,
        operations: [
          ModelOperation.CREATE,
          ModelOperation.UPDATE,
          ModelOperation.DELETE,
          ModelOperation.READ
        ])
    ];
    
    modelSchemaDefinition.addField(ModelFieldDefinition.id());
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Department.NAMEEN,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.string)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Department.NAMETR,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.string)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo(
      key: Department.UNIVERSITY,
      isRequired: false,
      targetName: "universityDepartmentsId",
      ofModelName: (University).toString()
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.hasMany(
      key: Department.MAINSTUDENTS,
      isRequired: false,
      ofModelName: (MainDepartmentStudent).toString(),
      associatedKey: MainDepartmentStudent.DEPARTMENT
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.hasMany(
      key: Department.STUDENTS,
      isRequired: false,
      ofModelName: (DepartmentStudents).toString(),
      associatedKey: DepartmentStudents.DEPARTMENT
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.hasMany(
      key: Department.MAINTEACHERS,
      isRequired: false,
      ofModelName: (MainDepartmentTeachers).toString(),
      associatedKey: MainDepartmentTeachers.DEPARTMENT
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.hasMany(
      key: Department.TEACHERS,
      isRequired: false,
      ofModelName: (DepartmentTeachers).toString(),
      associatedKey: DepartmentTeachers.DEPARTMENT
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.hasMany(
      key: Department.MANAGERS,
      isRequired: false,
      ofModelName: (DepartmentManager).toString(),
      associatedKey: DepartmentManager.DEPARTMENT
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.hasMany(
      key: Department.NOTICES,
      isRequired: false,
      ofModelName: (Notice).toString(),
      associatedKey: Notice.DEPARTMENT
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField(
      fieldName: 'createdAt',
      isRequired: false,
      isReadOnly: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.dateTime)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField(
      fieldName: 'updatedAt',
      isRequired: false,
      isReadOnly: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.dateTime)
    ));
  });
}

class _DepartmentModelType extends ModelType<Department> {
  const _DepartmentModelType();
  
  @override
  Department fromJson(Map<String, dynamic> jsonData) {
    return Department.fromJson(jsonData);
  }
}

Teacher.dart:

/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
*  http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// NOTE: This file is generated and may not follow lint rules defined in your app
// Generated files can be excluded from analysis in analysis_options.yaml
// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis

// ignore_for_file: public_member_api_docs, annotate_overrides, dead_code, dead_codepublic_member_api_docs, depend_on_referenced_packages, file_names, library_private_types_in_public_api, no_leading_underscores_for_library_prefixes, no_leading_underscores_for_local_identifiers, non_constant_identifier_names, null_check_on_nullable_type_parameter, prefer_adjacent_string_concatenation, prefer_const_constructors, prefer_if_null_operators, prefer_interpolation_to_compose_strings, slash_for_doc_comments, sort_child_properties_last, unnecessary_const, unnecessary_constructor_name, unnecessary_late, unnecessary_new, unnecessary_null_aware_assignments, unnecessary_nullable_for_final_variable_declarations, unnecessary_string_interpolations, use_build_context_synchronously

import 'ModelProvider.dart';
import 'package:amplify_core/amplify_core.dart';
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';


/** This is an auto generated class representing the Teacher type in your schema. */
@immutable
class Teacher extends Model {
  static const classType = const _TeacherModelType();
  final String id;
  final String? _photo;
  final String? _phone;
  final University? _university;
  final String? _universityNumber;
  final String? _email;
  final String? _areasTr;
  final String? _areasEn;
  final TeacherTitle? _title;
  final String? _cognitoId;
  final TemporalDate? _birthday;
  final Gender? _gender;
  final List<DepartmentTeachers>? _departments;
  final List<MainDepartmentTeachers>? _department;
  final List<Notice>? _notices;
  final TemporalDateTime? _createdAt;
  final TemporalDateTime? _updatedAt;

  @override
  getInstanceType() => classType;
  
  @override
  String getId() {
    return id;
  }
  
  String? get photo {
    return _photo;
  }
  
  String? get phone {
    return _phone;
  }
  
  University? get university {
    return _university;
  }
  
  String get universityNumber {
    try {
      return _universityNumber!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  String get email {
    try {
      return _email!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  String get areasTr {
    try {
      return _areasTr!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  String get areasEn {
    try {
      return _areasEn!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  TeacherTitle get title {
    try {
      return _title!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  String get cognitoId {
    try {
      return _cognitoId!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  TemporalDate get birthday {
    try {
      return _birthday!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  Gender get gender {
    try {
      return _gender!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
  
  List<DepartmentTeachers>? get departments {
    return _departments;
  }
  
  List<MainDepartmentTeachers>? get department {
    return _department;
  }
  
  List<Notice>? get notices {
    return _notices;
  }
  
  TemporalDateTime? get createdAt {
    return _createdAt;
  }
  
  TemporalDateTime? get updatedAt {
    return _updatedAt;
  }
  
  const Teacher._internal({required this.id, photo, phone, university, required universityNumber, required email, required areasTr, required areasEn, required title, required cognitoId, required birthday, required gender, departments, department, notices, createdAt, updatedAt}): _photo = photo, _phone = phone, _university = university, _universityNumber = universityNumber, _email = email, _areasTr = areasTr, _areasEn = areasEn, _title = title, _cognitoId = cognitoId, _birthday = birthday, _gender = gender, _departments = departments, _department = department, _notices = notices, _createdAt = createdAt, _updatedAt = updatedAt;
  
  factory Teacher({String? id, String? photo, String? phone, University? university, required String universityNumber, required String email, required String areasTr, required String areasEn, required TeacherTitle title, required String cognitoId, required TemporalDate birthday, required Gender gender, List<DepartmentTeachers>? departments, List<MainDepartmentTeachers>? department, List<Notice>? notices}) {
    return Teacher._internal(
      id: id == null ? UUID.getUUID() : id,
      photo: photo,
      phone: phone,
      university: university,
      universityNumber: universityNumber,
      email: email,
      areasTr: areasTr,
      areasEn: areasEn,
      title: title,
      cognitoId: cognitoId,
      birthday: birthday,
      gender: gender,
      departments: departments != null ? List<DepartmentTeachers>.unmodifiable(departments) : departments,
      department: department != null ? List<MainDepartmentTeachers>.unmodifiable(department) : department,
      notices: notices != null ? List<Notice>.unmodifiable(notices) : notices);
  }
  
  bool equals(Object other) {
    return this == other;
  }
  
  @override
  bool operator ==(Object other) {
    if (identical(other, this)) return true;
    return other is Teacher &&
      id == other.id &&
      _photo == other._photo &&
      _phone == other._phone &&
      _university == other._university &&
      _universityNumber == other._universityNumber &&
      _email == other._email &&
      _areasTr == other._areasTr &&
      _areasEn == other._areasEn &&
      _title == other._title &&
      _cognitoId == other._cognitoId &&
      _birthday == other._birthday &&
      _gender == other._gender &&
      DeepCollectionEquality().equals(_departments, other._departments) &&
      DeepCollectionEquality().equals(_department, other._department) &&
      DeepCollectionEquality().equals(_notices, other._notices);
  }
  
  @override
  int get hashCode => toString().hashCode;
  
  @override
  String toString() {
    var buffer = new StringBuffer();
    
    buffer.write("Teacher {");
    buffer.write("id=" + "$id" + ", ");
    buffer.write("photo=" + "$_photo" + ", ");
    buffer.write("phone=" + "$_phone" + ", ");
    buffer.write("university=" + (_university != null ? _university!.toString() : "null") + ", ");
    buffer.write("universityNumber=" + "$_universityNumber" + ", ");
    buffer.write("email=" + "$_email" + ", ");
    buffer.write("areasTr=" + "$_areasTr" + ", ");
    buffer.write("areasEn=" + "$_areasEn" + ", ");
    buffer.write("title=" + (_title != null ? enumToString(_title)! : "null") + ", ");
    buffer.write("cognitoId=" + "$_cognitoId" + ", ");
    buffer.write("birthday=" + (_birthday != null ? _birthday!.format() : "null") + ", ");
    buffer.write("gender=" + (_gender != null ? enumToString(_gender)! : "null") + ", ");
    buffer.write("createdAt=" + (_createdAt != null ? _createdAt!.format() : "null") + ", ");
    buffer.write("updatedAt=" + (_updatedAt != null ? _updatedAt!.format() : "null"));
    buffer.write("}");
    
    return buffer.toString();
  }
  
  Teacher copyWith({String? id, String? photo, String? phone, University? university, String? universityNumber, String? email, String? areasTr, String? areasEn, TeacherTitle? title, String? cognitoId, TemporalDate? birthday, Gender? gender, List<DepartmentTeachers>? departments, List<MainDepartmentTeachers>? department, List<Notice>? notices}) {
    return Teacher._internal(
      id: id ?? this.id,
      photo: photo ?? this.photo,
      phone: phone ?? this.phone,
      university: university ?? this.university,
      universityNumber: universityNumber ?? this.universityNumber,
      email: email ?? this.email,
      areasTr: areasTr ?? this.areasTr,
      areasEn: areasEn ?? this.areasEn,
      title: title ?? this.title,
      cognitoId: cognitoId ?? this.cognitoId,
      birthday: birthday ?? this.birthday,
      gender: gender ?? this.gender,
      departments: departments ?? this.departments,
      department: department ?? this.department,
      notices: notices ?? this.notices);
  }
  
  Teacher.fromJson(Map<String, dynamic> json)  
    : id = json['id'],
      _photo = json['photo'],
      _phone = json['phone'],
      _university = json['university']?['serializedData'] != null
        ? University.fromJson(new Map<String, dynamic>.from(json['university']['serializedData']))
        : null,
      _universityNumber = json['universityNumber'],
      _email = json['email'],
      _areasTr = json['areasTr'],
      _areasEn = json['areasEn'],
      _title = enumFromString<TeacherTitle>(json['title'], TeacherTitle.values),
      _cognitoId = json['cognitoId'],
      _birthday = json['birthday'] != null ? TemporalDate.fromString(json['birthday']) : null,
      _gender = enumFromString<Gender>(json['gender'], Gender.values),
      _departments = json['departments'] is List
        ? (json['departments'] as List)
          .where((e) => e?['serializedData'] != null)
          .map((e) => DepartmentTeachers.fromJson(new Map<String, dynamic>.from(e['serializedData'])))
          .toList()
        : null,
      _department = json['department'] is List
        ? (json['department'] as List)
          .where((e) => e?['serializedData'] != null)
          .map((e) => MainDepartmentTeachers.fromJson(new Map<String, dynamic>.from(e['serializedData'])))
          .toList()
        : null,
      _notices = json['notices'] is List
        ? (json['notices'] as List)
          .where((e) => e?['serializedData'] != null)
          .map((e) => Notice.fromJson(new Map<String, dynamic>.from(e['serializedData'])))
          .toList()
        : null,
      _createdAt = json['createdAt'] != null ? TemporalDateTime.fromString(json['createdAt']) : null,
      _updatedAt = json['updatedAt'] != null ? TemporalDateTime.fromString(json['updatedAt']) : null;
  
  Map<String, dynamic> toJson() => {
    'id': id, 'photo': _photo, 'phone': _phone, 'university': _university?.toJson(), 'universityNumber': _universityNumber, 'email': _email, 'areasTr': _areasTr, 'areasEn': _areasEn, 'title': enumToString(_title), 'cognitoId': _cognitoId, 'birthday': _birthday?.format(), 'gender': enumToString(_gender), 'departments': _departments?.map((DepartmentTeachers? e) => e?.toJson()).toList(), 'department': _department?.map((MainDepartmentTeachers? e) => e?.toJson()).toList(), 'notices': _notices?.map((Notice? e) => e?.toJson()).toList(), 'createdAt': _createdAt?.format(), 'updatedAt': _updatedAt?.format()
  };

  static final QueryField ID = QueryField(fieldName: "teacher.id");
  static final QueryField PHOTO = QueryField(fieldName: "photo");
  static final QueryField PHONE = QueryField(fieldName: "phone");
  static final QueryField UNIVERSITY = QueryField(
    fieldName: "university",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (University).toString()));
  static final QueryField UNIVERSITYNUMBER = QueryField(fieldName: "universityNumber");
  static final QueryField EMAIL = QueryField(fieldName: "email");
  static final QueryField AREASTR = QueryField(fieldName: "areasTr");
  static final QueryField AREASEN = QueryField(fieldName: "areasEn");
  static final QueryField TITLE = QueryField(fieldName: "title");
  static final QueryField COGNITOID = QueryField(fieldName: "cognitoId");
  static final QueryField BIRTHDAY = QueryField(fieldName: "birthday");
  static final QueryField GENDER = QueryField(fieldName: "gender");
  static final QueryField DEPARTMENTS = QueryField(
    fieldName: "departments",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (DepartmentTeachers).toString()));
  static final QueryField DEPARTMENT = QueryField(
    fieldName: "department",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (MainDepartmentTeachers).toString()));
  static final QueryField NOTICES = QueryField(
    fieldName: "notices",
    fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Notice).toString()));
  static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) {
    modelSchemaDefinition.name = "Teacher";
    modelSchemaDefinition.pluralName = "Teachers";
    
    modelSchemaDefinition.authRules = [
      AuthRule(
        authStrategy: AuthStrategy.PRIVATE,
        operations: [
          ModelOperation.READ,
          ModelOperation.CREATE
        ]),
      AuthRule(
        authStrategy: AuthStrategy.OWNER,
        ownerField: "cognitoId",
        identityClaim: "cognito:username",
        provider: AuthRuleProvider.USERPOOLS,
        operations: [
          ModelOperation.UPDATE,
          ModelOperation.DELETE
        ])
    ];
    
    modelSchemaDefinition.addField(ModelFieldDefinition.id());
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.PHOTO,
      isRequired: false,
      ofType: ModelFieldType(ModelFieldTypeEnum.string)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.PHONE,
      isRequired: false,
      ofType: ModelFieldType(ModelFieldTypeEnum.string)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo(
      key: Teacher.UNIVERSITY,
      isRequired: false,
      targetName: "universityTeachersId",
      ofModelName: (University).toString()
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.UNIVERSITYNUMBER,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.string)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.EMAIL,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.string)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.AREASTR,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.string)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.AREASEN,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.string)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.TITLE,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.enumeration)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.COGNITOID,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.string)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.BIRTHDAY,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.date)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.field(
      key: Teacher.GENDER,
      isRequired: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.enumeration)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.hasMany(
      key: Teacher.DEPARTMENTS,
      isRequired: false,
      ofModelName: (DepartmentTeachers).toString(),
      associatedKey: DepartmentTeachers.TEACHER
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.hasMany(
      key: Teacher.DEPARTMENT,
      isRequired: false,
      ofModelName: (MainDepartmentTeachers).toString(),
      associatedKey: MainDepartmentTeachers.TEACHER
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.hasMany(
      key: Teacher.NOTICES,
      isRequired: false,
      ofModelName: (Notice).toString(),
      associatedKey: Notice.CREATOR
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField(
      fieldName: 'createdAt',
      isRequired: false,
      isReadOnly: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.dateTime)
    ));
    
    modelSchemaDefinition.addField(ModelFieldDefinition.nonQueryField(
      fieldName: 'updatedAt',
      isRequired: false,
      isReadOnly: true,
      ofType: ModelFieldType(ModelFieldTypeEnum.dateTime)
    ));
  });
}

class _TeacherModelType extends ModelType<Teacher> {
  const _TeacherModelType();
  
  @override
  Teacher fromJson(Map<String, dynamic> jsonData) {
    return Teacher.fromJson(jsonData);
  }
}

@MarlonJD
Copy link
Contributor Author

Hey @fjnoyp, you fixed #2087. Can you check this issue?

@fjnoyp
Copy link
Contributor

fjnoyp commented Oct 14, 2022

Hi @MarlonJD

I'm a bit new to this issue and seems like there's been a long conversation on this.

This is what I understand the issue to be:

You cannot retrieve certain object types because you receive a console error saying you don't have proper authorization.

You were told to use multi auth setup but then got a different issue because the use of multi-auth for API + multi-auth for DataStore in the same App is still unsupported1:
#1867

It seems you provided the information @HuiSF requested but also pasted all of your codegen models. While the extra information could be helpful it's a bit much and makes scrolling through this issue a bit harder - could you shorten your reply above to just include the authRules? If we need that info we can ask for it later.

@MarlonJD
Copy link
Contributor Author

MarlonJD commented Oct 23, 2022

Hi @MarlonJD

I'm a bit new to this issue and seems like there's been a long conversation on this.

This is what I understand the issue to be:

You cannot retrieve certain object types because you receive a console error saying you don't have proper authorization.

You were told to use multi auth setup but then got a different issue because the use of multi-auth for API + multi-auth for DataStore in the same App is still unsupported1: #1867

It seems you provided the information @HuiSF requested but also pasted all of your codegen models. While the extra information could be helpful it's a bit much and makes scrolling through this issue a bit harder - could you shorten your reply above to just include the authRules? If we need that info we can ask for it later.

Hey thanks for you detailed answer but I already cut my answer at the begining of the my answer.

There is authRules in Department but not in DepartmentStudent and DepartmentTeacher
on Department there is something like this.
I changed some permissions after I created this issue. So I does not matter it's private or public.
It seems like there is auth rules on main model but not in its nested manytomany model.

I just wrote all DepartmentStudent and DepartmentTeacher for debugging, because there is no authRules in there.

You were told to use multi auth setup but then got a different issue because the use of multi-auth for API + multi-auth for DataStore in the same App is still unsupported1:

I also used only API (GraphQL) without DataStore no luck. Cognito + API not works, I cannot access any public datas without login. I also used any method like IAM + API, Cognito + IAM etc. Can anybody access anything like these configration? I think there is an issue about the auto generated models.

@HuiSF HuiSF added the duplicate This issue or pull request already exists label Apr 18, 2023
@HuiSF
Copy link
Member

HuiSF commented Apr 18, 2023

Hi sorry for lacking activities on this issue. I've tested DataStore multi-auth based on a few similar issues in the repo, and found that both amplify-swift (v1) and amplify-android (v1+v2) have issues around multi-auth. This causes common issue that models with public permission cannot work correctly without signing in a user.

I'm going to close this issue as a duplicate, so we can track the progress in #1693.

@HuiSF HuiSF closed this as not planned Won't fix, can't repro, duplicate, stale Apr 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
datastore Issues related to the DataStore Category duplicate This issue or pull request already exists pending-triage This issue is in the backlog of issues to triage
Projects
None yet
Development

No branches or pull requests

5 participants