amplify-cli icon indicating copy to clipboard operation
amplify-cli copied to clipboard

How to make a relationship of data from user pool to aws appsync model

Open yvescoinpass opened this issue 6 years ago • 16 comments

** Which Category is your question related to? ** Auth, API ** What AWS Services are you utilizing? ** Cognito, AWS AppSync, ** Provide additional details e.g. code snippets **

I am new to amplify and appsync. I am trying to create a Post model that needs to have a relationship of the user who is creating the Post. The problem is my user is from cognito user pool.

How should I create a relationship of this?

I create amlify api like this

? Please select from one of the below mentioned services: GraphQL
? Choose the default authorization type for the API API key
? Enter a description for the API key: 
? After how many days from now the API key should expire (1-365): 7
? Do you want to configure advanced settings for the GraphQL API Yes, I want to make some additional changes.
? Configure additional auth types? Yes
? Choose the additional authorization types you want to configure for the API Amazon Cognito User Pool
Cognito UserPool configuration
Use a Cognito user pool configured as a part of this project.
? Configure conflict detection? No

Here is my current Post model

type Post @model @versioned @aws_cognito_user_pools @auth(rules:[{allow: owner, queries:null},{allow: public}]){
  id: ID!
  title: String!
  content: String
  thumb: String
  slug: String!
  allow_comments: Boolean
  owner: String!
  version: Int!
  comments: [Comment] @connection(name: "PostComments")
}

I can't find any documentation how to build something like this.

"aws-amplify": "^2.2.1", "aws-amplify-react": "^3.1.2",

yvescoinpass avatar Jan 23 '20 05:01 yvescoinpass

@yvescoinpass the field owner of the Post type will be populated automatically with the user.username (because of the @auth(rules:[{allow: owner}]) )

sorokinvj avatar Jan 23 '20 22:01 sorokinvj

Hello @yvescoinpass if you are looking at adding authorization based solely on the user who created the post you can use @auth(rules:[{allow: owner}]) ) as stated by @sorokinvj.

View our @auth docs here: https://aws-amplify.github.io/docs/cli-toolchain/graphql#auth

Should you run into any @auth related issues please feel free to comment below.

SwaySway avatar Jan 24 '20 01:01 SwaySway

Hello @SwaySway @sorokinvj I tried it but it only returns {ownser:"user1"}. But what I want is the whole information of that user from cognito user pool as an object. Is that possible?

Here is my new Post model. I remove the owner field since it is automatically be added.

type Post @model @versioned @aws_cognito_user_pools @auth(rules:[{allow: owner},{allow: public}]){
  id: ID!
  title: String!
  content: String
  thumb: String
  slug: String!
  allow_comments: Boolean
  version: Int!
  comments: [Comment] @connection(name: "PostComments")
}

Right now I can only do this query

query ListPost {
  listPosts {
    items {
      title
      content
      owner
      }
    }
  }
}

and here is the result for query ListPost

{
  "data": {
    "listPosts": {
      "items": [
        {
           "title": "title 1"
          "content": "Test long text cotent"
          "owner": "user1"
        },
      ]
    }
  }
}

Here is the query that I want

query ListPost {
  listPosts {
    items {
      title
      content
      owner{
          username
          id
          email
          first_name
          last_name
        }
      }
    }
  }
}

Here is the result of the query that I want

{
  "data": {
    "listPosts": {
      "items": [
        {
          "title": "title 1"
          "content": "Test long text cotent"
          "owner": {
              "username": "user1"
              "id": "234234234"
              "email": "[email protected]"
              "first_name": "John"
              "last_name": "Doe"
           }
        },
       {
          "title": "title 1"
          "content": "Test long text cotent"
          "owner": {
              "username": "user1"
              "id": "234234234"
              "email": "[email protected]"
              "first_name": "John"
              "last_name": "Doe"
           }
        },
      ]
    }
  }
}

yvescoinpass avatar Jan 24 '20 06:01 yvescoinpass

Hello @SwaySway @sorokinvj I tried it but it only returns {ownser:"user1"}. But what I want is the whole information of that user from cognito user pool as an object. Is that possible?

If you want it in the same response when you got all the info about Post, no I don't think its possible, but you can make another request to Cognito and fetch everything connected to user1

sorokinvj avatar Jan 24 '20 14:01 sorokinvj

Thank you. Ok good to know that it its not possible. Can you give me a link to the documentation where I can request for the information of the user on Cognito User Pool? Maybe a lambda function.

yvescoinpass avatar Jan 24 '20 15:01 yvescoinpass

@yvescoinpass Sure! I use amplify framework in my app, so I communicate with Cognito via

import { Auth } from 'aws-amplify';

Auth.currentAuthenticatedUser()
.then(user => console.log(user))
.catch(err => console.log(err));

Here are the docs - https://aws-amplify.github.io/docs/js/authentication

If you want all users, not only the current one – then I think this issue might help https://github.com/aws-amplify/amplify-js/issues/1324

sorokinvj avatar Jan 27 '20 16:01 sorokinvj

Ok thank you so much @sorokinvj

yvescoinpass avatar Jan 28 '20 10:01 yvescoinpass

I have an update on this question. What I did is follow @sorokinvj adviced. I created a new Model UserProfile on my schema.graphql.

Here is my new schema.graphql

type UserProfile
	@model
	@versioned
	@aws_cognito_user_pools
	@auth(
		rules: [
			{
				allow: owner
				provider: userPools
				operations: [read, create, update, delete]
			}
			{ allow: public, provider: apiKey, operations: [read] }
		]
	) {
	id: ID!
	username: String!
	first_name: String!
	last_name: String!
	email: String!
	version: Int!
	picture: String
	post: [Post] @connection(name: "UserProfilePost")
}

type Post
	@model
	@versioned
	@aws_cognito_user_pools
	@auth(
		rules: [
			{
				allow: owner
				provider: userPools
				operations: [read, create, update, delete]
			}
			{ allow: public, provider: apiKey, operations: [read] }
		]
	) {
	id: ID!
	title: String!
	content: String
	thumb: String
	slug: String!
	allow_comments: Boolean
	post_type: String!
	add_to_nav: Boolean!
	version: Int!
	comments: [Comment] @connection(name: "PostComments")
	user_profile: UserProfile! @connection(name: "UserProfilePost")
}

After logged in I fetch the user pool data when I got the data.

Then I try adding it on user_profile table but I get an error

message: "Not Authorized to access createUserProfile on type Mutation"

This means that the API still didn't recognize me as a logged in user?

Here is the code to my logged in component

handleSumbmit(e) {
		e.preventDefault();

		this.setState({ authenticating: true });

		const { username, password } = this.state;

		Auth.signIn({
			username: username,
			password: password
		})
			.then(res => {
				console.log(res);
				this.setState({
					has_error: false,
					error_message: ""
				});
				this.setState({ authenticating: false });
				this.getCurrentUser(); // GET THE CURRENT LOGGED IN USER INFO
			})
			.catch(err => {
				console.log("handleSumbmit:", err);
				this.setState({ authenticating: false });
				this.setState({
					has_error: true,
					error_message: err.message
				});
			});
	}
	
	async getCurrentUser() {
		try {
			let user = await Auth.currentAuthenticatedUser();
			console.log("getCurrentUser", user);

			this.checkUserProfile(user); // CHECK IF THIS USER IS ALREADY ADDED IN USER PROFILE TABLE
		} catch (err) {
			console.log(err);
		}
	}

	async checkUserProfile(user_pool_data) {
		try {
			let { data } = await API.graphql(
				graphqlOperation(GetUserProfile, {
					id: user_pool_data.attributes.sub
				})
			);
			console.log("checkUserProfile", data);

			if (!data.getUserProfile) {
				this.addUserProfile(user_pool_data); // ADD A USER PROFILE FOR THIS USER
			} else {
				this.setAuthenticatedUser(user_pool_data, 1);
			}
		} catch (err) {
			console.log(err);
		}
	}

	async addUserProfile(user_pool_data) {
		try {
			let user_profile = {
				id: user_pool_data.attributes.sub,
				username: user_pool_data.username,
				first_name: user_pool_data.attributes.given_name,
				last_name: user_pool_data.attributes.family_name,
				email: user_pool_data.attributes.email
			};
			await API.graphql(
				graphqlOperation(CreateUserProfile, { input: user_profile })
			);
			console.log("addUserProfile", user_profile);
			this.setState({ confirm_success: true });
			this.setAuthenticatedUser(user_pool_data, 1);
		} catch (err) {
			console.log(err);
		}
	}

@sammartinez @SwaySway maybe you know about this?

yvescoinpass avatar Jan 30 '20 07:01 yvescoinpass

Why not get rid of the UserProfile type altogether and get those fields directly from the Cognito User Pool attributes?

ianmartorell avatar Jul 29 '20 09:07 ianmartorell

@ianmartorell Then how can I make a relationship to it in another table on my dynamodb?

yvescoinpass avatar Jul 30 '20 05:07 yvescoinpass

You could use a custom resolver like this: https://github.com/aws-amplify/amplify-cli/issues/1352#issuecomment-487176176. I haven't tried this myself though. Since I only need to get the profile for the current user, I can just Auth.currentUserInfo() from Amplify js.

ianmartorell avatar Jul 30 '20 07:07 ianmartorell

@yvescoinpass how do you define CreateUserProfile in your code? do you import it from the graphql/mutation.js? could you provide the mutation query?

sorokinvj avatar Jul 30 '20 16:07 sorokinvj

I am also experiencing this, when I create a 1 to 1 relationship it doesn't update the ownership of the second object being saved.

JoeKolba avatar Aug 06 '20 17:08 JoeKolba

IMHO - directly hitting Cognito for user information does not sound appetizing, especially since there are no easy ways to do batch reads. My take is to create Lambda and trigger Lambda using Cognito events. Using that technique, you will be able to sync the User attributes to a Userprofile table. Yes, it creates duplication of data, but this is much easier to manage.

harinair avatar Sep 02 '20 05:09 harinair

I built a User model in GraphQL for the api before deciding to try the Auth features of Amplify. My User model appears it was merged into the Cognito-generated one. However, the data in AdminUI shows a separate notion of User and retained that data. Would welcome other input on how to peer App-related attributes with the Auth User data. Thanks

oristian avatar Dec 17 '20 22:12 oristian

This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.

Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels for those types of questions.

github-actions[bot] avatar May 25 '21 11:05 github-actions[bot]