Customer Sign In

upLynk

Embedding the upLynk player Part 4: Login-restricted content

Tutorial thumbnail

Summary Combine the concepts from the previous Embedding Tutorials and add in user authentication to demonstrate conditional access to content.

Skill level required Basic understanding of mysql, PHP, and html

Time to complete 30-45 minutes

Things you’ll need
  • A PHP enabled web server
  • A MySQL database accessible from your web server

Introduction

This tutorial will build on the concepts we've visited in tutorial parts 2 & 3. We demonstrate a simplified, yet complete demonstration of blocking access to content. Some liberties are taken to keep the code brief such as password security and SQL query methods. This example should not be considered production ready. Security, scale, etc. are outside the scope considered in this tutorial.

Step 1. Setting up the database

The database used in this example contains 1 table named "users". The records it holds are self-explanatory. Again, for simplicity's sake, we've foregone password security. Below is sample code that can be executed in the mysql interpreter or on the command line using the mysql tools. It first creates the users table, if it doesn't already exist. It then creates one user named "test" with a password of "testtest".

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
CREATE TABLE IF NOT EXISTS `users` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(256) NOT NULL,
  `password` varchar(256) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

INSERT INTO users (username, password) VALUES('test', 'testtest');
    		

Step 2. The Application

Our application is simple and straightforward. When a user first visits the website they will not have authenticated yet. We will greet them as a guest and give them guest privileges. The only privilege a guest has is to view and submit the login form.

If the user submits the form with their credentials, and we cannot verify those credentials they will see the same login form with a note at the top of the page stating there was a problem with the credentials they provided. They can then re-enter credentials and attempt to authenticate once again.

If the user provides the correct credentials, they will be authenticated. We'll store their username in their session. We'll then greet them by username on the player page. We'll also render the HTML code that provides the player to the page. Included in this HTML will be a valid playback URL for the content, complete with an authorization token. Once the page finishes loading, playback will begin.

The application is composed of 3 php source code files:

  1. index.php - Provides the application logic as well as the html templates for our 2 pages, the login page and the video page.
  2. dbconn.php - Provides the database connection.
  3. uplynk.php - PHP utilities provided by upLynk.

In-line comments in the source code files provide more information about the application flow.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
/*
*
* index.php
* Embedding player 4 Application Script and HTML
*
*/

// Include the Database Connection Script
require_once("dbconn.php");

// Start a new, or retrieve our previously started session
session_start();

if($_SERVER['REQUEST_METHOD'] == "POST")
{
    // If a form has been POSTed, proceed with user authentication.

    // Check if our credentials are valid.
    // Grab the vaules for username and password from the form
    $username = $_POST["username"];
    $password = $_POST["password"];

    // Build an overly simple insecure  SQL Query we'll use to validate if
    // the credentials match one user in our table.
    $qs = "SELECT * FROM users where username='".$username."' and password='".$password."'";
    $result = mysql_query($qs);

    if (mysql_num_rows($result) == 1){
        // SUCCESS!  Set the username to the actual user's username which
        // we'll use as a method for denoting the user has authenticated.
        $_SESSION["username"]=$username;
        // Include the uplynk helper module.  It currently provides a token
        // generation function called GenerateToken.
        require_once("uplynk.php");
    } else {
        // FAIL!  The credentials were wrong.  Give the user an error
        // and send them back the form for another try.
        echo 'Your login credentials were invalid.  Please try again.';
    }

} else {
    // Most likely the user's first visit to the page, or a failed login attempt
    // has caused them to revisit the page as a guest.
    $_SESSION["username"] = "Guest";
}

// Below is the HTML code for both the authenticated and unauthenticated users.
// The HTML is selectively included based on a check of the username value set
// in the session.  If it's value is "Guest", display the form, otherwise
// assume the user is authenticated, generate a token, and send the player
// to the user's browser.

?>

<! DOCTYPE html>
<html>
    <head>
        <title>upLynk Test App <?php echo $_SESSION["username"]; ?></title>
        <?php if($_SESSION["username"] != "Guest") : ?>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://storage.uplynk.com/js/swfobject.js"></script>
        <script type="text/javascript" src="http://storage.uplynk.com/js/uplynk.js"></script>
        <?php endif; ?>
    </head>
    <body>
        <?php if($_SESSION["username"] == "Guest") : ?>
        <div id="not_logged_in">
            <h1>upLynk Test App</h1>
            <h2>Welcome, Guest!</h2>
            <p>If you'd like to view a video, please login below.</p>
            <div id="login_form">
                <form method="POST" action="">
                <label>Username</label><br />
                <input type="text" name="username" /><br />
                <label>Password</label><br />
                <input type="password" name="password" /><br />
                <input type="submit" value="submit" />
            </div>
        </div>
        <?php else : ?>
        <div id="navigation"><a href=".">Logout</a></div>
        <div id="logged_in">
            <h1>upLynk Test App</h1>
            <h2>Welcome, <?php echo $_SESSION["username"]; ?></h2>
            <div id="videoPlayer"></div>
        </div>
        <script type="text/javascript">
            $(function(){
                $('#videoPlayer').player('play','<?php echo GenerateToken('http://content.uplynk.com/d7d8471a20c444a59d66c6f9887593e7.m3u8');?>');
            });
        <?php endif; ?>
        </script>
    </body>
</html>
		
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
/*
*
* dbconn.php
* Database connection script
*
* Edit the $DB_* vars to fit your environment
*
*/

$DB_HOST = "127.0.0.1";
$DB_DB = "YOUR DATABASE NAME";
$DB_USERNAME = "YOUR USERNAME";
$DB_PASSWORD = "YOUR PASSWORD";

// $debug will cause the script to print additional information and echo test
// information to ensure the connection is working, when set to true.
$debug = false;

if($debug) echo "start <br /><br />";

// Connect to the DB Server
$c = mysql_connect($DB_HOST,$DB_USERNAME,$DB_PASSWORD);
if (!$c)
{
    die('Could not connect: ' . mysql_error());
} else {
    // Select the DB by name
    mysql_select_db($DB_DB) or die(mysql_error());
}

if($debug)
{
    // This is the test query.  It dumps the usernames from the users table
    $query = mysql_query("SELECT username FROM users");
    while($row = mysql_fetch_array($query, MYSQL_ASSOC))
    {
        echo $row['username'];
    }
}

if($debug) echo "<br /><br />done";

?>
		
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
/*
*
* uplynk.php
* uplynk utilties for use with PHP
*
*/


// Token generation helper function
// Takes the asset Playback URL, available in the upLynk CMS and returns
// a tokenized URL.
function GenerateToken($uri)
{
    // Edit $SECRET with your own API Key
    $SECRET = 'Your API Key'; // See DRM Docs
    $msg = array();
    $msg['exp'] = time() + 300; // 5 minutes from now
    $msg['ct'] = 'a'; // asset
    $parts = parse_url($uri);
    list($part1, $part2) = explode('.',$parts['path']);
    $msg["cid"] = substr($part1,1);
    $msg['iph'] = hash('sha256', $_SERVER['REMOTE_ADDR']);
    $msg['sig'] = hash_hmac('sha256', http_build_query($msg), $SECRET);

    return $uri . '?' . http_build_query($msg);
}

?>
		

You can copy the code above and deploy it on your own server for testing. Save the files with their respective names.

Finished!

You've created a simple player requiring user authentication to allow video playback.

Back to tutorials