Skip to content

Commit

Permalink
Introduces a new option to publish specific auth actions. (#551)
Browse files Browse the repository at this point in the history
* fix: docs for auth wip

* Fix styling

* fix: reset

* Fix styling

* fix: wip

* Fix styling

* fix: try to offer full permissions for windows

* fix: retry tests

* fix: refactoring tests

* fix: wip

* fix: wi

* fix: wip

* fix: pipeline

---------

Co-authored-by: binaryk <[email protected]>
  • Loading branch information
binaryk and binaryk authored Mar 26, 2023
1 parent 5b1920b commit cfe365a
Show file tree
Hide file tree
Showing 32 changed files with 616 additions and 308 deletions.
6 changes: 6 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,11 @@ jobs:
composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update
composer update --${{ matrix.stability }} --prefer-dist --no-interaction
- name: Clear Composer cache
run: composer clear-cache

- name: Wait for a few seconds
run: sleep 5

- name: Execute tests
run: ./vendor/bin/testbench package:test --parallel --no-coverage
7 changes: 6 additions & 1 deletion docs-v2/content/en/api/rest-methods.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
--- title: REST Methods menuTitle: Controllers category: API position: 12 ---
---
title: REST Methods
menuTitle: Controllers
category: API
position: 12
---

## Introduction

Expand Down
289 changes: 275 additions & 14 deletions docs-v2/content/en/auth/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ Now you can finally enjoy the auth setup (`register`, `login`, `forgot`, and `re

Migrate the `users`, `password_resets` table (they already exist into a fresh Laravel app).

<alert type="success">

Laravel 10 automatically ships with Sanctum, so you don't have to install it.

</alert>

### Install sanctum

See the docs [here](https://laravel.com/docs/sanctum#installation). You don't need to add `\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,` in your `'api'` middleware group.
Expand Down Expand Up @@ -42,7 +48,8 @@ The `User` model should extend the `Illuminate\Foundation\Auth\User` class or im

<alert type="info">

Make sure you didn't skip adding the `\Laravel\Sanctum\HasApiTokens` trait to your `User` model.
Make sure you have the `\Laravel\Sanctum\HasApiTokens` trait to your `User` model.
Laravel 10 will automatically add this trait to your `User` model.

</alert>

Expand All @@ -66,32 +73,33 @@ Restify provides you a simple way to add all of your auth routes prepared. Simpl
Route::restifyAuth();
```

And voila, now you have auth routes ready to be used.
And voilà, now you have auth routes ready to be used.

These are the default routes provided by restify:

| Verb | URI | Action |
| :------------- |:-----------------------------------------| :----------------|
| **POST** | `/api/register` | register |
| **POST** | `/api/login` | login |
| **POST** | `/api/restify/forgotPassword` | forgot password |
| **POST** | `/api/restify/resetPassword` | reset password |
| **POST** | `/api/restify/verify/{id}/{emailHash}` | verify user |
| Verb | URI | Action |
| :------------- |:-----------------------------------------|:---------------|
| **POST** | `/api/register` | register |
| **POST** | `/api/login` | login |
| **POST** | `/api/restify/forgotPassword` | forgotPassword |
| **POST** | `/api/restify/resetPassword` | resetPassword |
| **POST** | `/api/restify/verify/{id}/{emailHash}` | verifyEmail |

<alert type="info">

The `register` and `login` routes are outside the base `restify` prefix because they don't have to follow the `auth` middleware defined in the `config/restify.php` config file.

</alert>

## Export auth controllers

All of these routes are handled by default, so you can just use them facilely. However, you can customize each of them by exporting auth controllers:
You can also pass an `actions` argument, which is an array of actions you want to register. For example:

```shell
php artisan restify:auth
```php
Route::restifyAuth(actions: ['login', 'register']);
```
Now you have all the auth controllers and blade email files exported into your project.

By using the `actions` argument, only the specified routes will be registered. If no `actions` argument is passed, Restify will register all the routes by default.


## Sanctum Middleware

Expand All @@ -105,3 +113,256 @@ Next, add the `auth:sanctum` middleware after the `api` middleware in your confi
...
],
```

## Login

Let's ensure the authentication is working correctly. Create a user in the DatabaseSeeder class:

```php
// DatabaseSeeder.php
\App\Models\User::factory()->create([
'name' => 'Test User',
'email' => '[email protected]',
'password' => \Illuminate\Support\Facades\Hash::make('password'),
]);
```

Seed it:

```shell
php artisan db:seed
```

Now you can test the login with Curl or Postman:

```shell
curl -X POST "http://restify-app.test/api/login" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "password"
}'
```

So you should see the response like this:

```json
{
"id": "11",
"type": "users",
"attributes": {
"name": "Test User",
"email": "[email protected]"
},
"meta": {
"authorizedToShow": true,
"authorizedToStore": false,
"authorizedToUpdate": false,
"authorizedToDelete": false,
"token": "1|f7D1qkALtM9GKDkjREKpwMRKTZg2ZnFqDZTSe53k"
}
}
```

## Register

Let's see how to register a new user in the application. You can test the registration using Curl or Postman.

Use the following endpoint for registration:

`http://restify-app.test/api/register`

And send this payload:

```json
{
"name": "John Doe",
"email": "[email protected]",
"password": "secret!",
"password_confirmation": "secret!"
}
```

Note: Email and password fields are required.

Now, you can send a POST request with Curl:

```shell
curl -X POST "http://restify-app.test/api/register" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "[email protected]",
"password": "secret!",
"password_confirmation": "secret!"
}'
```

You should see the response like this:

```json
{
"id": "12",
"type": "users",
"attributes": {
"name": "John Doe",
"email": "[email protected]"
},
"meta": {
"authorizedToShow": true,
"authorizedToStore": false,
"authorizedToUpdate": false,
"authorizedToDelete": false,
"token": "2|z8D2rkBLtN8GKDkjREKpwMRKTZg2ZnFqDZTSe53k"
}
}
```

## Forgot Password

To initiate the password reset process, use the following endpoint:

`{{host}}/api/forgotPassword`

And send this payload:

```json
{
"email": "[email protected]"
}
```

After making a POST request to this endpoint, an email will be sent to the provided email address containing a link to reset the password. The link looks like this:

`'password_reset_url' => env('FRONTEND_APP_URL').'/password/reset?token={token}&email={email}',`

This configuration can be found in the `config/restify.php` file. The FRONTEND_APP_URL should be set to the URL of your frontend app, where the user lands when they click the action button in the email. The "token" is a variable that will be used to reset the password later on.

To view the email content during development, you can change the following configuration in your .env file:

```dotenv
MAIL_MAILER=log
```

This will log the email content to the `laravel.log` file, allowing you to see the password reset email without actually sending it.

Now, you can send a POST request with Curl:

```shell
curl -X POST "http://restify-app.test/api/forgotPassword" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]"
}'
```

If the email is successfully sent, you'll receive a response similar to the following:

```json
{
"message": "Reset password link sent to your email."
}
```

Now, the user can follow the link in the email to reset their password.


## Reset Password

After the user has received the password reset email from the Forgot Password process, they can reset their password using the following endpoint:

`http://restify-app.test/api/resetPassword`

The payload should include the token and email received from the password reset email:

```json
{
"token": "7e474bb9118e736306de27126343644a7cb0ecdaec558fdef30946d15225bc07",
"email": "[email protected]",
"password": "new_password",
"password_confirmation": "new_password"
}
```
Now, you can send a POST request with Curl:

```shell
curl -X POST "http://restify-app.test/api/resetPassword" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"token": "0d20b6cfa48f2bbbb83bf913d5e329207149f74d7b22d59a383d321c7af7fd5e",
"email": "[email protected]",
"password": "new_password",
"password_confirmation": "new_password"
}'
```

If the password reset is successful, you should receive a response similar to the following:

```json
{
"message": "Your password has been successfully reset."
}
```

Now the user's password has been successfully reset, and they can log in with their new password.


## Customizing Authentication Controllers

You can publish the authentication controllers from the Restify package to your own application, allowing you to customize their behavior as needed. To publish the controllers, run the following command:

```shell
php artisan restify:auth
```

This command will copy the authentication controllers to the `app/Http/Controllers/Restify` directory in your Laravel project.

The command accepts an optional `--actions` parameter, which allows you to specify which controllers you want to publish. If no action is passed, the command will publish all controllers and the `ForgotPasswordNotification`. For example, to publish only the `login` and `register` controllers, run:

```shell
php artisan restify:auth --actions=login,register
```

Now, you can make any necessary changes to these controllers to fit your specific requirements.

### Customizing the Register Route

In a real-world scenario, you might need to customize only the register route. To do this, you can use the `restify:auth` command with the `--actions` option to publish only the register controller:

```shell
php artisan restify:auth --actions=register
```

After running the command, the register controller will be published to your application, and you can modify it to fit your requirements.

<alert type="warning">

Important Note: If you want to publish other actions in the future, you'll need to manually update the `routes/api.php` file before running the restify:auth command again. Remove any previously published Restify routes, and keep the `Route::restifyAuth();` line so that the new routes can be correctly published.

</alert>

For example, if you previously published the register route, your `routes/api.php` file might look like this:

```php
// ...

Route::restifyAuth(actions: ["login", "resetPassword", "forgotPassword", "verifyEmail"]);

// ...
```

Before running the `restify:auth` command again, revert the file to its original state:

```php
// ...

Route::restifyAuth();

// ...
```

Now you can run the `restify:auth` command with other actions, and the routes will be published correctly.
8 changes: 8 additions & 0 deletions docs-v2/content/en/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ Laravel Restify is an extraordinary tool inspired by [Laravel Nova](https://nova

If you don't have an application written with Nova, you can start with Laravel Restify from scratch and get a powerful API in a few minutes.

<alert type="warning">

This documentation is for the latest version of Laravel Restify. Please ensure you are using the most recent release of the package to guarantee compatibility with the information provided in this documentation. To update Laravel Restify, refer to the upgrade guide for instructions.

</alert>

## Features

<list :items="[
Expand All @@ -22,6 +28,8 @@ If you don't have an application written with Nova, you can start with Laravel R
]">
</list>



## Playground

You can find a playground in the [Restify Demo GitHub repository](https://github.com/BinarCode/restify-demo).
Expand Down
Loading

0 comments on commit cfe365a

Please sign in to comment.