Search code examples
flutterdartaqueduct

Passing user id with AuthController


I just made simple authentication app using aqueduct as a back end. I used codes from aqueduct documentation pages for login and registering. When I login with this code in backend

 router
    .route('/auth/token')
    .link(() => AuthController(authServer));

I get back token, token type and expiration date, Is there any chance to also pass userId? Or do I have to create my own controller to do that?

UPDATE or how can I in my backend to save user id when saving the data

  @Operation.post()
  Future<Response> addData(@Bind.body(ignore: ['id']) Data newData) async {
    final query = Query<Data>(context)..values = newData;
    final insertData = await query.insert();
    return Response.ok(insertData);
  }

Solution

  • Flutter frontend

    Login initially with the username/email and password. You will get an authorization token back from the server if the username and password are valid. Then use that token to make further privileged requests to the server.

    You don't need to save any personal data about the user (email or password) on the client. You can save the token, though, if you don't want to make the user log in again the next time they use the app. When saving the token you should use a secure storage option. The flutter_secure_storage plugin uses KeyChain on iOS and KeyStore on Android.

    Aqueduct backend

    You can use the user IDs all you want on the backend. I don't know of any need to pass them to the client, though. On the backend you can query the user ID and then use it to fetch other information from the database.

    Here is an example from the documentation:

    class NewsFeedController extends ResourceController {
      NewsFeedController(this.context);
    
      ManagedContext context;
    
      @Operation.get()
      Future<Response> getNewsFeed() async {
        var forUserID = request.authorization.ownerID;
    
        var query = Query<Post>(context)
          ..where((p) => p.author).identifiedBy(forUserID);
    
        return Response.ok(await query.fetch());
      }
    }
    

    The client only passed in the token. Aqueduct looks up the user id for you based on that token. Now you know the user ID.

    Your other tables can have a column for the user ID so that only that user may save and retrieve their data. In the example above, Posts have an Author and an Author has an ID, that is, the user ID.

    where((p) => p.author).identifiedBy(forUserID)
    

    is equivalent to

    where((p) => p.author.id).equalTo(forUserID)
    

    You can read about this in the Advanced Queries section of the documentation.