2021-04-22 03:24:59 +08:00
|
|
|
<?php
|
|
|
|
|
namespace App\Repositories;
|
|
|
|
|
|
2021-04-30 15:10:31 +08:00
|
|
|
use App\Http\Resources\UserResource;
|
2021-04-23 01:28:41 +08:00
|
|
|
use App\Models\User;
|
|
|
|
|
use Illuminate\Support\Facades\DB;
|
2021-06-04 21:04:12 +08:00
|
|
|
use Illuminate\Validation\UnauthorizedException;
|
2021-04-23 01:28:41 +08:00
|
|
|
|
2021-04-22 03:24:59 +08:00
|
|
|
class AuthenticateRepository extends BaseRepository
|
|
|
|
|
{
|
2021-04-23 01:28:41 +08:00
|
|
|
public function login($username, $password)
|
|
|
|
|
{
|
|
|
|
|
$user = User::query()
|
|
|
|
|
->where('username', $username)
|
2021-06-04 21:04:12 +08:00
|
|
|
->first(array_merge(User::$commonFields, ['class', 'secret', 'passhash']));
|
2021-04-30 15:10:31 +08:00
|
|
|
if (!$user || md5($user->secret . $password . $user->secret) != $user->passhash) {
|
|
|
|
|
throw new \InvalidArgumentException('Username or password invalid.');
|
2021-04-23 01:28:41 +08:00
|
|
|
}
|
2021-12-14 16:22:03 +08:00
|
|
|
if (IS_PLATFORM_ADMIN && !$user->canAccessAdmin()) {
|
2021-06-04 21:04:12 +08:00
|
|
|
throw new UnauthorizedException('Unauthorized!');
|
|
|
|
|
}
|
2022-02-21 23:20:25 +08:00
|
|
|
$user->checkIsNormal();
|
2021-04-30 15:10:31 +08:00
|
|
|
$tokenName = __METHOD__ . __LINE__;
|
|
|
|
|
$token = DB::transaction(function () use ($user, $tokenName) {
|
2021-04-23 01:28:41 +08:00
|
|
|
$user->tokens()->delete();
|
2021-04-30 15:10:31 +08:00
|
|
|
$tokenResult = $user->createToken($tokenName);
|
2021-04-23 01:28:41 +08:00
|
|
|
return $tokenResult->plainTextToken;
|
|
|
|
|
});
|
2021-04-30 15:10:31 +08:00
|
|
|
$result = (new UserResource($user))->response()->getData(true)['data'];
|
2021-04-23 01:28:41 +08:00
|
|
|
$result['token'] = $token;
|
|
|
|
|
return $result;
|
|
|
|
|
}
|
2021-04-22 03:24:59 +08:00
|
|
|
|
2021-04-23 01:28:41 +08:00
|
|
|
public function logout($id)
|
|
|
|
|
{
|
|
|
|
|
$user = User::query()->findOrFail($id, ['id']);
|
|
|
|
|
$result = $user->tokens()->delete();
|
|
|
|
|
return $result;
|
|
|
|
|
}
|
2021-04-22 03:24:59 +08:00
|
|
|
}
|