This section of the guide show on how to implement authentication using the Slyk Api and the Slyk SDK.
Each step has code snippets with examples on how to do each part. Please do note that, for brevity, the examples lack things like error handling.
Sign up
Create the sign up endpoint
First create an API endpoint that uses the Slyk SDK to create a user.
The SDK method is slyk.user.create and it takes the user's email, password, name, and other optional fields. For this example we'll pass verified: true to the method to automatically verify users.
After this step you can either create a success page with a link to the sign in page or you can redirect to the sign in directly.
You can also update the endpoint to create a session using the slyk.auth.login method. You can see how that is done in the sign in flow below.
Sign in
Create the sign in endpoint
Create an API endpoint that takes in the user's email and password and uses the slyk.auth.login method to create a session for the user. The session consists on a JWT used to authorize the user in the API and a refresh token that is used to request a new JWT when the old one expires.
The way you manage and secure these tokens is up to you. You can either store them on the client-side using localStorage or you can store them on secure cookies.
In this example we'll store them on cookies using the cookies module. They'll later be read on API endpoints that need the JWT.
Create an API endpoint that reads the JWT from the cookies (or receives it from the client-side on the request body if you decided to store the tokens on local storage) and uses the slyk.auth.validate method to validate the token and fetch the user's data.
Make sure to abstract this in some way so that you don't forget to do it.
Sign out
Create the sign out endpoint
Create an API endpoint that reads the refresh token from the cookies (or receives it from the client-side on the request body if you decided to store the tokens on local storage) and uses the slyk.auth.logout method to revoke it. This endpoint should also clear the cookies used to store the tokens.
As we did on the sign in endpoint, we'll use the cookies module to handle cookies.
Next add a button to your app that invokes the sign out endpoint and then redirects the user back to the sign in page (or any other non-authenticated page in your app). This button is usually on the profile menu or page.