feat: reset API token if password is changed

This commit is contained in:
Phan An 2021-01-31 18:21:57 +01:00
parent 1c93222085
commit 8a966242f0
4 changed files with 29 additions and 7 deletions

View file

@ -1,7 +1,7 @@
openapi: 3.0.0
info:
title: Koel API
version: 5.0.0
version: 5.1.0
description: 'The API for [Koel](https://koel.dev), the music streaming application that works.'
contact:
name: An Phan
@ -164,8 +164,16 @@ paths:
tags:
- authentication
responses:
'204':
description: No Content
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
token:
type: string
description: New API token if the password is changed.
operationId: put-me
description: Update the current user's profile
security:

View file

@ -4,20 +4,22 @@ namespace App\Http\Controllers\API;
use App\Http\Requests\API\ProfileUpdateRequest;
use App\Models\User;
use App\Services\TokenManager;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Hashing\Hasher as Hash;
use Illuminate\Http\Response;
class ProfileController extends Controller
{
private $hash;
private $tokenManager;
/** @var User */
private $currentUser;
public function __construct(Hash $hash, ?Authenticatable $currentUser)
public function __construct(Hash $hash, TokenManager $tokenManager, ?Authenticatable $currentUser)
{
$this->hash = $hash;
$this->tokenManager = $tokenManager;
$this->currentUser = $currentUser;
}
@ -40,6 +42,10 @@ class ProfileController extends Controller
$this->currentUser->update($data);
return response()->json(null, Response::HTTP_NO_CONTENT);
$responseData = $request->password
? ['token' => $this->tokenManager->refreshToken($this->currentUser)->plainTextToken]
: [];
return response()->json($responseData);
}
}

View file

@ -33,4 +33,11 @@ class TokenManager
return $token ? $token->tokenable : null;
}
public function refreshToken(User $user): NewAccessToken
{
$this->destroyTokens($user);
return $this->createToken($user);
}
}

View file

@ -42,7 +42,8 @@ class ProfileTest extends TestCase
'name' => 'Foo',
'email' => 'bar@baz.com',
'password' => 'qux',
], $user);
], $user)
->assertJsonStructure(['token']);
self::assertDatabaseHas('users', [
'id' => $user->id,