简体   繁体   中英

Segregating user data with AWS Amplify

I'm following the AWS Amplify tutorials on API and Authentication . While I've made progress to get both working (!), it's not clear to me how I might connect the two features of Amplify so as to separate/segregate (?) user data...

For instance, take this GraphQL Todo Model:

type Todo @model @auth(rules: [{allow: public}]) {
  id: ID!
  name: String!
  description: String
  completed: Boolean!
}

I can save and fetch these Todo s with a ViewModel:

import Amplify

class TodoListViewModel: ObservableObject {
    @Published var todos = [Todo]()
    @Published var completedTodos = [Todo]()
    
    func loadToDos() {
        Amplify.DataStore.query(Todo.self) { result in
            switch result {
            case .success(let todos):
                self.todos = todos.filter { !$0.completed }
                self.completedTodos = todos.filter { $0.completed }
            case .failure(let error):
                print("Could not query DataStore: \(error)")
            }
        }
    }
    
    func createTodo(name: String, description: String?) {
        let item = Todo(name: name, description: description, completed: false)
        todos.append(item)
        Amplify.DataStore.save(item) { result in
            switch result {
            case .success(let savedItem):
                print("Saved item: \(savedItem.name)")
            case .failure(let error):
                print("Could not save item with error: \(error)")
            }
        }
    }
}

But these methods seemingly allow any user to access any other users Todo data (?)

Reading through the docs, I think I need to setup authorization rules (?)

If I'm reading this correctly, to make sure that an arbitrary user can only see their data, is it really as simple as changing the GraphQL Todo model to:

type Todo @model @auth(rules: [{allow: owner}]) {
  id: ID!
  name: String!
  description: String
  completed: Boolean!
}

That can't be it?

...what other modifications will I need to implement in order to ensure that "Alice" can save and fetch her data and be sure that I'm not mixing it with "Bob's" data?

A fully worked example that uses an Authenticated (logged-in) user would be appreciated!

It really is that simple. That's the value of using Amplify. Every record that is saved to the database has a column called owner . The value of owner is the Id of the Cognito user that created the record.

AppSync's auto-generated resolvers are smart enough to verify that the user asking for data is the same user that owns the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM