Answer the question
In order to leave comments, you need to log in
Why does session id change in php?
Hello.
I wrote a simple custom authorization on laravel (pure api)
There are two routes
class AuthController extends Controller
{
public function auth(Request $request) {
$user = AuthService::auth($request);
if ($user) return CustomJsonResponse::create(true, [ 'user' => $user ]);
return CustomJsonResponse::create(false, 'Вы не можете быть авторизованы', 400);
}
public function login(Request $request) {
try {
$requestUser = $request->json('user');
$user = UserService::getUser($requestUser);
if ( !$user ) {
return CustomJsonResponse::create(false, 'Пользователь не найден', 400);
}
if ( !UserService::validateUser($requestUser) ) {
return CustomJsonResponse::create(false, 'Неверный пароль', 400);
}
$response = CustomJsonResponse::create(true, ['user' => $user]);
$response->withCookie('user', $user, 60 * 24 * 14, '/'); // 14 days
$_SESSION['user'] = $user;
return $response;
} catch (\Throwable $th) {
return $th;
return CustomJsonResponse::create(false, 'Error', 500);
}
}
public function logout() {
$response = CustomJsonResponse::create(true, 'Пользователь деавторизован');
$response->withoutCookie('user');
unset( $_SESSION['user'] );
return $response;
}
}
class AuthService {
public static function auth(Request $request) {
if ( isset($_SESSION['user']) ) {
$request['user'] = $_SESSION['user'];
return $_SESSION['user'];
}
if ( $request->cookie('user') ) {
$user_cookie = $request->cookie('user');
$user = UserService::getUser($user_cookie);
if ( $user && UserService::validateUser($user_cookie) ) {
$_SESSION['user'] = $user;
$request['user'] = $user;
return $user;
}
}
return null;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question