Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auth v3 #26

Closed
wants to merge 32 commits into from
Closed

Auth v3 #26

wants to merge 32 commits into from

Conversation

mychidarko
Copy link
Member

@mychidarko mychidarko commented Oct 21, 2024

What kind of change does this PR introduce? (pls check at least one)

  • Bugfix
  • Feature
  • Code style update
  • Refactor
  • Build-related changes
  • Other, please describe below

Description

This PR introduces a cleaner end-user experience to working with authentication in Leaf. It normalizes the configuration and removes options for some configuration that should be default as well as simplifying the available options and making them easier to use.

V3 also introduces an improved DX for working with middleware, removes the numerous redirect options and removes session guards as well. Session and token auth is more normalized, leaving side effects to you instead of trying to anticipate what you want to do (to the detriment of other users).

Beyond these changes, we've maintained every other thing v2 came with which means if you had no custom config and didn't use session guards, you can upgrade to v3 with almost zero changes to your existing code.

Change Examples

$data = auth()->register([
  'username' => 'example',
  'email' => '[email protected]',
  'password' => 'password'
], ['username', 'email']);

if ($data) {
  // user is authenticated
} else {
  // user is not authenticated
  $errors = auth()->errors();
}

This will now look like:

auth()->config('unique', ['email', 'username']);

$success = auth()->register([
  'username' => 'example',
  'email' => '[email protected]',
  'password' => 'password'
]);

if (!$success) {
  $error = auth()->errors();
  // ['email' => 'The email already exists']
} else {
  $dataWithTokens = auth()->data();
  $authUser = auth()->user();
}

This is easier to read and write and also allows you to share unique items between register() and update() which is usually what you would want to do.


app()->get('/protected', function () {
  $user = auth()->user();

  if ($user) {
    // user is logged in
  } else {
    // user is not logged in
    response()->json([
      "error" => "Unauthorized",
      "data" => auth()->errors(),
    ], 401);
  }
});

app()->get('/protected2', function () {
  $user = auth()->user();

  if ($user) {
    // user is logged in
  } else {
    // user is not logged in
    response()->json([
      "error" => "Unauthorized",
      "data" => auth()->errors(),
    ], 401);
  }
});

Auth v3 comes with built-in middleware that integrates with Leaf which means you don't need to write the above or your own middleware or even use guards:

// define actions for when your middleware fails
auth()->middleware('auth.required', function () {
  response()->exit([
      'error' => 'Unauthorized',
      'data' => auth()->errors(),
    ], 401);
});

// use middleware in routes or route groups
app()->get('/protected', ['middleware' => 'auth.required', function () {
  // this route is protected
}]);

// or on a route group
app()->group('/protected', ['middleware' => 'auth.required', function () {
  app()->get('/route', function () {
    // this route is protected
  });
}]);

The updated user object is more powerful and makes sure that the authenticated user is always in scope when it should be which was not the case in the previous version.

Before:

$userData = auth()->login(...);

...

$user = auth()->user();
// null: token not found. Will work with session auth

Now:

$success = auth()->login(...);

...

$user = auth()->user();
// user data available with both token and session auth

This makes sure that behaviour is consistent


The update user object also allows you to build queries directly by extending Leaf DB when a relationship is available. For instance, if a user has many blog posts in the articles db column, you can get them using Leaf auth directly:

Before:

$userId = auth()->id();

$articles = db()->select('articles')->where('user_id', $userId)->all();

After:

$articles = auth()->user()->articles()->all();

When you call any method that doesn't exist on the user object, Leaf Auth will assume that you mean to get data related to the current user from the database. This still uses Leaf DB, so you don't need to learn any additional syntax. If you want to do additional filtering, you can add a where block or anything you need.

$articles = auth()->user()->articles()->where('title', 'Far far away!')->first();

Back to the user object, it used to return an array which was the user information without any hidden fields. This behaviour has been updated to now return an entire user class. This class has methods and properties for getting user data, tokens and related db as we saw above:

// get all user data without hidden fields
$user = auth()->user()->get();

// or pick specific fields
$email = auth()->user()->email;
$username = auth()->user()->username;

Picking specific fields using the user object gives you access to hidden fields which means you can do something like this:

$password = auth()->user()->password;

This is allowed because once again, we assume that a single value you pick is going to be used within your application which should not be a security issue.

Does this PR introduce a breaking change? (check one)

  • Yes
  • No

Related Issue

None

@mychidarko mychidarko marked this pull request as draft October 25, 2024 01:38
@mychidarko mychidarko marked this pull request as ready for review November 6, 2024 23:26
@mychidarko
Copy link
Member Author

Closing as merged

@mychidarko mychidarko closed this Nov 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant