Skip to content

Commit

Permalink
Login action return user data + added account/auth-check route
Browse files Browse the repository at this point in the history
  • Loading branch information
lcharette committed Jul 6, 2024
1 parent 6fa076a commit 421a0e4
Show file tree
Hide file tree
Showing 6 changed files with 160 additions and 6 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [6.0.0](https://github.com/userfrosting/sprinkle-account/compare/5.2.0...6.0.0)
- Login action returns the user data instead of empty array
- Added `account/auth-check` route

## [5.2.0](https://github.com/userfrosting/sprinkle-account/compare/5.1.0...5.2.0)

## [5.1.3](https://github.com/userfrosting/sprinkle-account/compare/5.1.2...5.1.3)
Expand Down
54 changes: 54 additions & 0 deletions app/src/Controller/AuthCheckAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

/*
* UserFrosting Account Sprinkle (http://www.userfrosting.com)
*
* @link https://github.com/userfrosting/sprinkle-account
* @copyright Copyright (c) 2013-2024 Alexander Weissman & Louis Charette
* @license https://github.com/userfrosting/sprinkle-account/blob/master/LICENSE.md (MIT License)
*/

namespace UserFrosting\Sprinkle\Account\Controller;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use UserFrosting\Sprinkle\Account\Authenticate\Authenticator;

/**
* Return if the user is authenticated, and if he is, also return the user data.
*
* Middleware: None
* Route: /account/authcheck
* Route Name: account.authCheck
* Request type: GET
*/
class AuthCheckAction
{
/**
* Inject dependencies.
*/
public function __construct(
protected Authenticator $authenticator,
) {
}

/**
* Handle request and return data.
*
* @param Response $response
*/
public function __invoke(Response $response): Response
{
$auth = $this->authenticator->check();
$data = [
'auth' => $auth,
'user' => $auth ? $this->authenticator->user() : null,
];
$payload = json_encode($data, JSON_THROW_ON_ERROR);
$response->getBody()->write($payload);

return $response->withHeader('Content-Type', 'application/json');
}
}
19 changes: 16 additions & 3 deletions app/src/Controller/LoginAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,18 +77,31 @@ public function __construct(
public function __invoke(Request $request, Response $response): Response
{
$this->handle($request);
$response = $this->writeResponse($response);

return $response->withHeader('Content-Type', 'application/json');
}

/**
* Write to the response object.
*
* @param Response $response
*
* @return Response
*/
protected function writeResponse(Response $response): Response
{
// Get redirect target and add Header
$event = $this->eventDispatcher->dispatch(new UserRedirectedAfterLoginEvent());
if ($event->getRedirect() !== null) {
$response = $response->withHeader('UF-Redirect', $event->getRedirect());
}

// Write empty response
$payload = json_encode([], JSON_THROW_ON_ERROR);
// Write response with the user info in it
$payload = json_encode($this->authenticator->user(), JSON_THROW_ON_ERROR);
$response->getBody()->write($payload);

return $response->withHeader('Content-Type', 'application/json');
return $response;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions app/src/Routes/AuthRoutes.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use UserFrosting\Routes\RouteDefinitionInterface;
use UserFrosting\Sprinkle\Account\Authenticate\AuthGuard;
use UserFrosting\Sprinkle\Account\Authenticate\GuestGuard;
use UserFrosting\Sprinkle\Account\Controller\AuthCheckAction;
use UserFrosting\Sprinkle\Account\Controller\CaptchaAction;
use UserFrosting\Sprinkle\Account\Controller\CheckUsernameAction;
use UserFrosting\Sprinkle\Account\Controller\DenyResetPasswordAction;
Expand Down Expand Up @@ -56,6 +57,7 @@ public function register(App $app): void

// No guard
$app->group('/account', function (RouteCollectorProxy $group) {
$group->get('/auth-check', AuthCheckAction::class)->setName('account.authCheck');
$group->get('/captcha', CaptchaAction::class)->setName('account.captcha');
$group->get('/check-username', CheckUsernameAction::class)->setName('account.checkUsername');
$group->get('/suggest-username', SuggestUsernameAction::class)->setName('account.suggestUsername');
Expand Down
78 changes: 78 additions & 0 deletions app/tests/Controller/AuthCheckActionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

declare(strict_types=1);

/*
* UserFrosting Account Sprinkle (http://www.userfrosting.com)
*
* @link https://github.com/userfrosting/sprinkle-account
* @copyright Copyright (c) 2013-2024 Alexander Weissman & Louis Charette
* @license https://github.com/userfrosting/sprinkle-account/blob/master/LICENSE.md (MIT License)
*/

namespace UserFrosting\Sprinkle\Account\Tests\Controller;

use Mockery;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use UserFrosting\Sprinkle\Account\Authenticate\Authenticator;
use UserFrosting\Sprinkle\Account\Database\Models\User;
use UserFrosting\Sprinkle\Account\Tests\AccountTestCase;
use UserFrosting\Sprinkle\Core\Testing\RefreshDatabase;

/**
* Tests RegisterAction
*/
class AuthCheckActionTest extends AccountTestCase
{
use RefreshDatabase;
use MockeryPHPUnitIntegration;

/**
* Setup test database for controller tests
*/
public function setUp(): void
{
parent::setUp();
$this->refreshDatabase();
}

public function testGuest(): void
{
// Create request with method and url and fetch response
$request = $this->createJsonRequest('GET', '/account/auth-check');
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([
'auth' => false,
'user' => null,
], $response);
$this->assertResponseStatus(200, $response);
}

public function testNotAuth(): void
{
/** @var User */
$user = User::factory([
'password' => 'test'
])->create();

// Mock Authenticator
$authenticator = Mockery::mock(Authenticator::class)
->shouldReceive('check')->once()->andReturn(true)
->shouldReceive('user')->once()->andReturn($user)
->getMock();
$this->ci->set(Authenticator::class, $authenticator);

// Create request with method and url and fetch response
$request = $this->createJsonRequest('GET', '/account/auth-check');
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([
'auth' => true,
'user' => $user->toArray(),
], $response);
$this->assertResponseStatus(200, $response);
}
}
9 changes: 6 additions & 3 deletions app/tests/Controller/LoginActionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public function testLogin(): void
$user = User::factory([
'password' => 'test'
])->create();
$user->refresh();

// Create request with method and url and fetch response
$request = $this->createJsonRequest('POST', '/account/login', [
Expand All @@ -58,7 +59,7 @@ public function testLogin(): void
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([], $response);
$this->assertJsonResponse($user->toArray(), $response);
$this->assertResponseStatus(200, $response);

// Assert Event Redirect
Expand All @@ -82,6 +83,7 @@ public function testLoginWithEmail(): void
$user = User::factory([
'password' => 'test'
])->create();
$user->refresh();

// Create request with method and url and fetch response
$request = $this->createJsonRequest('POST', '/account/login', [
Expand All @@ -91,7 +93,7 @@ public function testLoginWithEmail(): void
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([], $response);
$this->assertJsonResponse($user->toArray(), $response);
$this->assertResponseStatus(200, $response);

// We have to logout the user to avoid problem
Expand Down Expand Up @@ -195,6 +197,7 @@ public function testLoginThrottlerDoesNotCountSuccessfulLogins(): void
$user = User::factory([
'password' => 'test'
])->create();
$user->refresh();

// Create fake throttler
/** @var Throttler */
Expand All @@ -212,7 +215,7 @@ public function testLoginThrottlerDoesNotCountSuccessfulLogins(): void
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([], $response);
$this->assertJsonResponse($user->toArray(), $response);
$this->assertResponseStatus(200, $response);

// We have to logout the user to avoid problem
Expand Down

0 comments on commit 421a0e4

Please sign in to comment.