R
R
ravshan selimov2021-05-29 15:12:37
Laravel
ravshan selimov, 2021-05-29 15:12:37

Why does session id change in php?

Hello.
I wrote a simple custom authorization on laravel (pure api)

There are two routes

  • /auth
  • /auth/login

- /auth to check if the user is logged in or not
- /auth/login to

log in Everything worked when I tested via insomnia or postman.
I started to make a front and such a problem that session_id changes with each request, so cookies are not accepted (not found) and the session is empty due to the fact that the session is different.

Authorization is implemented on sessions and cookies (without tokens)

Some code
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;
    }
}

AuthService
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

1 answer(s)
P
part_os, 2021-05-29
@ravshan01

Laravel does not use $_SESSION as far as I remember.
It has a Session facade there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question