Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
We have an auth cookie being set on login and removed on logout. Now we need to switch our authentication to use this cookie instead of the session.
Decoding the Cookie
function decodeAuthCookie($prop = null)
{
$cookie = json_decode(request()->cookies->get('auth'));
if ($prop === null) {
return $cookie;
}
if (!isset($cookie->$prop)) {
return false;
}
return $cookie->$prop;
}
-
0:00
We have an off cookie being set on login, and removed on logout.
-
0:06
Now we need to switch our authentication to use this cookie instead of the session.
-
0:12
Let's create a helper function to make it easier to read the cookie properties.
-
0:17
Function DecodeAuthCookie().
-
0:28
Cookie = json_decode(request()
-
0:36
cookies->get('auth') and
-
0:44
return $cookie.
-
0:48
Let's call this new function on our homepage.
-
0:54
We can remove those request and call decondeAuthCookie.
-
1:03
Now let's go back to the browser.
-
1:06
Great, we can see both the auth, user ID and the auth roles.
-
1:11
But what if we just want to grab the user ID?
-
1:14
Let's go back to the function.
-
1:19
We're going to accept a new optional argument.
-
1:24
Prop = null.
-
1:29
Then we're going to check if, $prop === null,
-
1:41
Then we're just going to return the cookie.
-
1:45
Next, we want to check if
-
1:50
(!isset($cookie->$prop)) then
-
1:59
we'll return false.
-
2:03
And finally we can return
-
2:08
the cookie $prop.
-
2:12
Four conditionals.
-
2:13
First we check if the property is null.
-
2:16
If so we're returning the whole cookie.
-
2:19
Next, if we have a property, we're going to check if the cookie has that property.
-
2:24
If not, we're going to return false.
-
2:27
And finally, if both of those paths we have an actual property on our cookie so
-
2:33
we will return that single property.
-
2:36
Now let's go back to our homepage.
-
2:39
And to our decodeAuthCookie, we'll add auth_user_id.
-
2:45
Now we can go back to the browser.
-
2:50
And now, in the browser, we see only the user ID.
-
2:54
Let's clean up the homepage.
-
2:59
We'll remove the var_dump and then we can close the index.php.
-
3:05
Now we're ready to use this new decode auth cookie.
You need to sign up for Treehouse in order to download course files.
Sign up