Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
We will create a couple helper function that we can use to make sure that the user is authenticated. To do this, we will need to read the access token.
Other samples for score
echo $book['score']; ?: echo '0';
PHP 7: null coalesce operator
echo $book['score'] :: echo '0';
Requiring Authentication on Pages
Add requireAuth(); to the following files
Also in inc/nav.php
<?php if (!isAuthenticated()) : ?> <li><a href="/add.php">Add Book</a></li> <?php endif; ?>
Now we should create a helper function that we can use on pages that require
This function will check for an access token cookie that is not expired.
We will also need to get the user from the access token.
Before we get the user, we first want to check if the user is authenticated.
Let's start building our helper files.
In the functions.php file,
let's check if the user is authenticated in its own function.
We'll start by checking if (!request(),
return false; If
we do have an access token we should try to validate the jot by decoding it.
We'll place this inside a try catch block.
We start by setting the leeway.
This will account for when there is a clock skew of time between the signing and
Then we can run the access token cookie through the decode method.
There are three properties used again.
The jot, the secret and then the array of approved signing algorithms.
Get access token.
Since we signed the token with HS 256.
That's the only approved signing algorithm we want in our list
If the user is authenticated we return true.
If there were any exceptions thrown from the decoding of the jot,
then we return false.
Now we are ready to create the requireAuth() function.
This function will check the isAuthenticated() function.
We redirect the user to the login page.
Before we redirect we should set a new cookie with the same name that
expires in the past with an invalid jot.
The time before now.
The path and the cookie domain.
Now we pass the cookie on the redirect.
This is common practice for making sure that the browser does not see
a valid jot in case it misses that the cookie is actually expired.
Now you can use the requireAuth() function at the top of any file
you want to require authentication.
Let's start by adding this to the add.php file.
Make sure that you include the bootstrap file at the top.
And then requireAuth.
You need to sign up for Treehouse in order to download course files.Sign up