82 lines
2.7 KiB
PHP
82 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Client;
|
|
|
|
use App\Admin\Services\UserService;
|
|
use App\Enums\SocialiteType;
|
|
use App\Exceptions\BaseException;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\User;
|
|
use App\Models\UserSocialite;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Hash;
|
|
|
|
class AuthController extends Controller
|
|
{
|
|
public function login(Request $request)
|
|
{
|
|
$request->validate([
|
|
'username' => 'required',
|
|
'password' => 'required',
|
|
]);
|
|
|
|
$user = User::where('phone', $request->input('username'))->first();
|
|
if (!$user) {
|
|
throw new BaseException('手机号不存在');
|
|
}
|
|
if (!Hash::check($request->input('password'), $user->password)) {
|
|
throw new BaseException('用户名或密码错误');
|
|
}
|
|
// 更新第三方账户
|
|
$openid = $request->input('openid');
|
|
$open_type = $request->input('open_type');
|
|
if ($openid && $open_type) {
|
|
$this->updateUserSocialite($user, $openid, SocialiteType::from($open_type));
|
|
}
|
|
$token = $user->createToken('client')->plainTextToken;
|
|
return $this->response()->success(['token' => $token, 'user' => $user]);
|
|
}
|
|
|
|
public function register(Request $request)
|
|
{
|
|
try {
|
|
DB::beginTransaction();
|
|
$service = UserService::make();
|
|
if (!$service->store($request->all())) {
|
|
throw new BaseException($service->getError());
|
|
}
|
|
$user = User::where('phone', $request->input('phone'))->first();
|
|
// 更新第三方账户
|
|
$openid = $request->input('openid');
|
|
$open_type = $request->input('open_type');
|
|
if ($openid && $open_type) {
|
|
$this->updateUserSocialite($user, $openid, SocialiteType::from($open_type));
|
|
}
|
|
DB::commit();
|
|
$token = $user->createToken('client')->plainTextToken;
|
|
return $this->response()->success(['token' => $token, 'user' => $user]);
|
|
} catch (\Exception $e) {
|
|
DB::rollBack();
|
|
return $this->response()->fail($e->getMessage());
|
|
}
|
|
}
|
|
|
|
protected function updateUserSocialite($user, $openid, $type)
|
|
{
|
|
// 清空以前绑定的
|
|
UserSocialite::where([
|
|
'type' => $type,
|
|
'user_type' => $user->getMorphClass(),
|
|
'user_id' => $user->id,
|
|
])->update(['user_id' => null]);
|
|
UserSocialite::updateOrCreate([
|
|
'type' => $type,
|
|
'user_type' => $user->getMorphClass(),
|
|
'openid' => $openid,
|
|
], [
|
|
'user_id' => $user->id,
|
|
]);
|
|
}
|
|
}
|