mardi 27 août 2019

Redirect User to Login Page When Token Session Expired - Laravel 5.8

I want

to redirect my user to the login screen when token session expired.

My API will return http_code 401 when that happens.

I did

public static function get($url) {

    try {

        $token = Session::get('user')->token;

        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Authorization: Bearer '.$token));

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_ENCODING , "gzip");
        curl_setopt($ch, CURLOPT_USERAGENT,'php');

        $result   = curl_exec($ch);
        $info     = curl_getinfo($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        $result = json_decode($result, TRUE);

        if($result['http_code'] == 401){

            $token = Session::get('user')->token;
            $user = User::where('token',$token)->first();
            $user->delete();

            Session::flush();
            Auth::logout();

            return Redirect::to('/')->with('error', 'Token expired.');

        }

        return $result;

    } catch (ConnectException $e) {

        Logging::error($e);
        return null;
    }

    return json_decode($result->getBody(), TRUE);
}

I got

How would one achive this in Laravel 5.8 ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2LaAVAb
via IFTTT

Aucun commentaire:

Enregistrer un commentaire