Programming Tutorial #8: Using Steemconnect OAuth (PHP)

Code

What Will I Learn?

  • You will learn how to authorise a user
  • You will learn how to find a username from AuthCode
  • You will learn how to display customised content
  • You will learn how to redirect a user to the page they were on

Requirements

  • 3 Steem / A registered SteemConnect Version 2 App
  • WAMP, LAMP or XAMPP Preconfigured
  • PHPStorm, Notepad++ or any other text editor/IDE
  • A Willingness to learn

Difficulty

  • Intermediate

Tutorial Contents

See this first: Oauth Part 1

Logging Out / Session Invalidation

We are now going to create a file called Logout.php which will allow users to log out upon visiting it.

Firstly, like every other page which uses the user's username, we have to start it with

<?php
session_start();

Now we need to check if they are signed in, so to do this, we check if they have an auth code.

If not we send them back to the state variable / the homepage (set to your homepage url).

if (!isset($_SESSION['code'])) {
    if(isset($_GET['state'])) {header("Location: " . $_GET['state']);} else {header("Location: http://localhost:8080/SteemApps");}

Next, we need to create a curl request, if you do not understand this, see this: Oauth Part 1

The URL we send it to is the one which destroys tokens so that they become useless.

} else {
    $authstr = "authorization: " . $_SESSION['code'];
    $headers = array($authstr,"Content-Type: application/json");
    $check = curl_init();
    curl_setopt_array($check, array(
        CURLOPT_URL => "https://v2.steemconnect.com/api/oauth2/token/revoke",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 1,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "{}",
        CURLOPT_HTTPHEADER => array(
            $authstr,
            "cache-control: no-cache",
            "content-type: application/json",
        ),
    ));
    $result = curl_exec($check);
    curl_close($check);

Since they are no longer logged in, we should get rid of their session and clear all the variables.

    session_unset();
    session_destroy();

Then we redirect them back to where they came from, or to our homepage (replace it once again) and end our if statement.

if(isset($_GET['state'])) {header("Location: " . $_GET['state']);} else {header("Location: http://localhost:8080/SteemApps");}
}

Now they are signed out, and our application knows this as the code variable is no longer set.

Checking whether a user has deauthorised our app!

What? How dare they

But, on a more serious note, some people will no longer need your application, and they can remove your access to the account Here
So, if they haven't logged out, how will we know?
We will have to create a function to check whether they are still logged in on every page that requires them to sign in.

Now, create a file called verifyLogin.php, this file will return true if the user is still logged in, and false, and destroy the session if not.

Firstly, we need to check if their code has already expired, because if it has, then there is no need to check, because we will know it is invalid.
(Since it is imported into files with session_start(); already in them, it doesn't require it, and will cause errors if you try.)
Always call this file at the top, just after session start to make sure that their credentials are still valid before doing anything with them.

<?php
if(isset($_SESSION['expires'])) {if($_SESSION['expires'] < time()) {session_unset(); session_regenerate_id(true);}} else {session_regenerate_id(true);}

Next, we need to check if they have even signed in, no matter of whether it is valid or not.

(Checks if code is not set)

if (!isset($_SESSION['code'])) {
    return false;
} else {

Do another CURL request to make sure that their login is still valid

    $authstr = "authorization: " . $_SESSION['code'];
    $headers = array($authstr,"Content-Type: application/json");
    $check = curl_init();
    curl_setopt_array($check, array(
        CURLOPT_URL => "https://v2.steemconnect.com/api/me",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 1,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "{}",
        CURLOPT_HTTPHEADER => array(
            $authstr,
            "cache-control: no-cache",
            "content-type: application/json",
        ),
    ));
    $result = curl_exec($check);
    curl_close($check);

Now we turn it into a php data object

$_result = json_decode($result);

Now we check if the result has a user attribute, it only returns one if the code is valid, otherwise, it just returns an error and an error description.
And return true if it succeeds

if(isset($_result->user)) {
    return true;
} else {

If it doesn't have it, destroy the session, so that we know next time that it is invalid straight away.
and return false because they are no longer validly logged in.

        session_unset(); session_regenerate_id(true);
        return false;
    }
}
Using their account info on other pages.

Now that we have all this data, how do we know they are logged in, and how do we know who they are.

Well, since we made a file to check if they are logged in, we can just use it.

A minimalistic example is:
(But obviously, you can use it to change what a user sees and what they can do)

<?php
session_start();
$vl = require 'verifyLogin.php'; //Require because we need it, $vl because it is the initials of the file's function

if($vl) {
    echo "

Hello, Logged in User!

"
; } else { echo "

Hello, You need to sign in Here

";
} ?>

If you want to display their username, you can use verifyLogin to make sure that they are logged in with a username, and then use it from the variable.

<?php
session_start();
$vl = require 'verifyLogin.php'; //Require because we need it, $vl because it is the initials of the file's function

if($vl) {
    echo "

Hello, " . $_SESSION['user'] . "!"; } else { echo "

Hello, Guest!

"
; } ?>

Or if you wish to write in HTML and not have to echo it out of php, you can do it like so:

<?php
session_start();
$vl = require 'verifyLogin.php'; //Require because we need it, $vl because it is the initials of the file's function

if($vl) {
?>

Your HTML Here, no quotes needed, PHP is smart!
<p>More Words, In a paragraph</p>
<ul>
<li>Name: <?php /*Back Into PHP*/ echo $_SESSION['user']; ?></li>
<li>Rank: 500</li>
</ul>

<?php
} else {
?>

Your HTML Here, Yet again, no quotes needed. 
<p>More Words, In a paragraph</p>
<ul>
<li>Name: Guest</li>
<li>Rank: 500</li>
</ul>

<?php
{
    

Thanks for reading my tutorial, hope it will help you, as it took me way too long to find out how to do this!

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now