Notice: You're viewing an old version of the Nylo documentation.
Consider upgrading your project to Nylo 5.20.0.
Basics

Authentication



Introduction

In Nylo, you can use the built-in helpers to make Authentication a breeze.

To authenticate a user, run the below command.

User user = User();

await Auth.set(user);

To retrieve a user, run the below command.

User? user = await Auth.user<User>();

print(user); // User

Let's imagine the below scenario.

  1. A user registers using an email and password.
  2. After registering, you create the user a session token.
  3. We now want to store the session token on the user's device for future use.
TextEditingController _tfEmail = TextEditingController();
TextEditingController _tfPassword = TextEditingController();

_login() async {
  // 1 - Example register via an API Service
  User? user = await api<AuthApiService>((request) => request.register(email: _tfEmail.text, password: _tfPassword.text));

  // 2 - Returns the users session token
  print(user?.token);

  // 3 - Save the user to Nylo
  await Auth.set(user);
}

Now the User model will be saved on the device.

To retrieve the authenticated user back, use Backpack.instance.auth(). This will return the model that was saved previously.


Adding an auth user

When a user logs in to your application, you can add them using the Auth.set(user) helper.

_login() async {
  User user = User();

  await Auth.set(user);
} 


Retrieve an auth user

If a user is logged into your app, you can retrieve the user by calling getAuthUser(). This helper method will return the model stored.

_getUser() async {
  User? user = await Auth.user<User>();
  // or
  User? user = Backpack.instance.auth();
}


Removing an auth user

When a user logs out of your application, you can remove them using the Auth.remove() helper.

_logout() async {

  await Auth.remove();
}

Now, the user is logged out of the app and the authentication page won't show when they next visit the app.


Authentication Page

Once your user is stored using the Auth.set(user) helper. You'll be able to set an 'authentication page', this will be used as the initial page the user sees when they open the app.

Go to your routes/router.dart file and set parameter authPage.

appRouter() => nyRoutes((router) {

  router.route(HomePage.path, (context) => HomePage(title: "Hello World"));

  router.route(ProfilePage.path, (context) => ProfilePage(), authPage: true); // auth page
});

Now, when the app boots, it will use the auth page instead of the default route link.