mirror of
https://github.com/lkddi/nexusphp.git
synced 2026-04-03 22:20:57 +08:00
41 lines
1.4 KiB
PHP
41 lines
1.4 KiB
PHP
<?php
|
|
namespace App\Repositories;
|
|
|
|
use App\Http\Resources\UserResource;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Validation\UnauthorizedException;
|
|
|
|
class AuthenticateRepository extends BaseRepository
|
|
{
|
|
public function login($username, $password)
|
|
{
|
|
$user = User::query()
|
|
->where('username', $username)
|
|
->first(array_merge(User::$commonFields, ['class', 'secret', 'passhash']));
|
|
if (!$user || md5($user->secret . $password . $user->secret) != $user->passhash) {
|
|
throw new \InvalidArgumentException('Username or password invalid.');
|
|
}
|
|
if (IS_PLATFORM_ADMIN && !$user->canAccessAdmin()) {
|
|
throw new UnauthorizedException('Unauthorized!');
|
|
}
|
|
$user->checkIsNormal();
|
|
$tokenName = __METHOD__ . __LINE__;
|
|
$token = DB::transaction(function () use ($user, $tokenName) {
|
|
$user->tokens()->delete();
|
|
$tokenResult = $user->createToken($tokenName);
|
|
return $tokenResult->plainTextToken;
|
|
});
|
|
$result = (new UserResource($user))->response()->getData(true)['data'];
|
|
$result['token'] = $token;
|
|
return $result;
|
|
}
|
|
|
|
public function logout($id)
|
|
{
|
|
$user = User::query()->findOrFail($id, ['id']);
|
|
$result = $user->tokens()->delete();
|
|
return $result;
|
|
}
|
|
}
|