summaryrefslogtreecommitdiffstats
path: root/examples/consumer.php
blob: 11337dc81575eca5efda66f256002129c5471655 (plain)
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
<?php

/**
 * A demonstration of the PHP OpenID Consumer.  This script assumes
 * Auth/OpenID has been installed and is in your PHP include path.
 */

set_include_path(get_include_path() . PATH_SEPARATOR . "/home/cygnus/production");

/**
 * Require files to use the OpenID consumer.  We need the consumer
 * itself, an OpenID store implementation, and some utility functions.
 */
require_once("Auth/OpenID/Consumer/Consumer.php");
require_once("Auth/OpenID/OIDUtil.php");

/**
 * Create the OpenID store and consumer objects, which we'll use to
 * perform the authentication.  Based on the value of $store_type,
 * create a different kind of store.  These are here as examples of
 * how you'd create the types of available OpenID stores.  The
 * fallback store (if you specify an invalid value for $store_type) is
 * to use a FileStore.  The settings for each store are contained in
 * the respective if blocks below.  In addition, the require lines are
 * included in each block to show which file you'll need to include to
 * use the store.
 */
$store_type = 'file';

if ($store_type = 'sqlite') {

    require_once("Auth/OpenID/Store/SQLStore.php");

    /**
     * This is where the example will store its OpenID information.
     * You should change this path if you want the example store to be
     * created elsewhere.  After you're done playing with the example
     * script, you'll have to remove this directory manually.
     */
    $store_path = "/tmp/_php_consumer_test";


    /**
     * Try to create the store directory.  ensureDir is provided by
     * OIDUtil.php.
     */
    if (!ensureDir($store_path)) {
        print "Could not create the SQLiteStore directory '$store_path'. ".
            " Please check the effective permissions.";
        exit(0);
    }

    $dsn = sprintf("sqlite:///%s/file.db", $store_path);

    $db =& DB::connect($dsn);

    $store = new Auth_OpenID_SQLiteStore($db);

    /**
     * This needs to be called once for the lifetime of the store, but
     * calling it each time you use the store won't hurt anything
     * (although it'll incur a slight performance pentalty because the
     * tables will already exist).
     */
    $store->createTables();

} else if ($store_type = 'pgsql') {

    require_once("Auth/OpenID/Store/SQLStore.php");

    /**
     * Assume that the database used by the PostgreSQL store has
     * already been created.
     */
    $dsn = array(
                 'phptype'  => 'pgsql',
                 'username' => 'openid_test',
                 'password' => '',
                 'hostspec' => 'dbtest',
                 'database' => 'openid_test',
                 );

    $db =& DB::connect($dsn);

    $store = new Auth_OpenID_PostgreSQLStore($db);

    /**
     * This needs to be called once for the lifetime of the store, but
     * calling it each time you use the store won't hurt anything
     * (although it'll incur a slight performance pentalty because the
     * tables will already exist).
     */
    $store->createTables();

} else {

    require_once("Auth/OpenID/Store/FileStore.php");

    /**
     * This is where the example will store its OpenID information.
     * You should change this path if you want the example store to be
     * created elsewhere.  After you're done playing with the example
     * script, you'll have to remove this directory manually.
     */
    $store_path = "/tmp/_php_consumer_test";


    /**
     * Try to create the store directory.  ensureDir is provided by
     * OIDUtil.php.
     */
    if (!ensureDir($store_path)) {
        print "Could not create the FileStore directory '$store_path'. ".
            " Please check the effective permissions.";
        exit(0);
    }

    $store = new Auth_OpenID_FileStore($store_path);
}

/**
 * Create a consumer object using the store object created earlier.
 */
$consumer = new Auth_OpenID_Consumer($store);

/**
 * Start the PHP session.
 */
session_start();

/**
 * Examine the CGI environment to find out what we should do.
 */
$action = null;
if (array_key_exists('action', $_GET)) {
    $action = $_GET['action'];
}

/**
 * Get this script's URL (since it's an example and may vary widely)
 * and use it later when building URLs to use in the OpenID auth
 * system.
 */
$self_url = $_SERVER['PHP_SELF'];

/**
 * These are the allowed values of the CGI 'action' variable.
 * Anything else will be ignored and will result in a default page.
 */
$urls = array('verify' => $self_url . "?action=verify",
              'process' => $self_url . "?action=process");

if (!array_key_exists($action, $urls)) {
    // Default behavior.
    $action = 'default_page';
}

/**
 * Run the approriatley-named function based on the scrubbed value of
 * $action.
 */
$action();


/**
 * Escapes double quotes in a value and returns the value wrapped in
 * double quotes for use as an HTML attribute.
 */
function quoteattr($s)
{
    $s = str_replace('"', '&quot;', $s);
    return sprintf('"%s"', $s);
}

/**
 * Prints the page header with a specified title.
 */
function print_header($title)
{

    $header_str = "<html>
  <head><title>%s</title></head>
  <style type=\"text/css\">
      * {
        font-family: verdana,sans-serif;
      }
      body {
        width: 50em;
        margin: 1em;
      }
      div {
        padding: .5em;
      }
      table {
        margin: none;
        padding: none;
      }
      .alert {
        border: 1px solid #e7dc2b;
        background: #fff888;
      }
      .error {
        border: 1px solid #ff0000;
        background: #ffaaaa;
      }
      #verify-form {
        border: 1px solid #777777;
        background: #dddddd;
        margin-top: 1em;
        padding-bottom: 0em;
      }
  </style>
  <body>
    <h1>%s</h1>
    <p>
      This example consumer uses the <a
      href=\"http://www.openidenabled.com/openid/libraries/php/\">PHP
      OpenID</a> library. It just verifies that the URL that you enter
      is your identity URL.
    </p>";

    print sprintf($header_str, $title, $title);
}

/**
 * Prints the page footer, which also includes the OpenID auth form.
 */
function print_footer()
{
    global $urls;

    $footer_str = "
    <div id=\"verify-form\">
      <form method=\"get\" action=%s>
        Identity&nbsp;URL:
        <input type=\"hidden\" name=\"action\" value=\"verify\" />
        <input type=\"text\" name=\"openid_url\" value=\"\" />
        <input type=\"submit\" value=\"Verify\" />
      </form>
    </div>
  </body>
</html>";
    print sprintf($footer_str, quoteattr($urls['verify']));
}

/**
 * Render a default page.
 */
function default_page()
{
    render();
}

/**
 * Use some parameters to render a page with the specified title,
 * including an optional message and CSS class to format the message
 * in case the caller wants to display a notification or error.
 */
function render($message = null, $css_class = null,
                $title = "PHP OpenID Consumer Example")
{
    print_header($title);
    if ($message) {
        if (!$css_class) {
            $css_class = 'alert';
        }
        print "<div class=\"$css_class\">$message</div>";
    }
    print_footer();
}

/**
 * Process the OpenID auth form submission by starting the OpenID auth
 * process.
 */
function verify()
{
    global $consumer, $urls, $self_url,
        $Auth_OpenID_HTTP_FAILURE,
        $Auth_OpenID_PARSE_ERROR,
        $Auth_OpenID_SUCCESS;

    // Render a default page if we got a submission without an
    // openid_url value.
    if (!array_key_exists('openid_url', $_GET) ||
        !$_GET['openid_url']) {
        default_page();
        return;
    }

    $openid_url = $_GET['openid_url'];

    // Begin the OpenID authentication process.
    list($status, $info) = $consumer->beginAuth($openid_url);

    // Handle failure status return values.
    if (in_array($status, array($Auth_OpenID_HTTP_FAILURE, $Auth_OpenID_PARSE_ERROR))) {
        if ($status == $Auth_OpenID_HTTP_FAILURE) {
            render("HTTP failure");
        } else {
            render("HTTP Parse error");
        }
    } else if ($status == $Auth_OpenID_SUCCESS) {
        // If we got a successful return, continue the auth by
        // redirecting the user agent to the OpenID server.  Be sure
        // to give the server a URL that will cause this script's
        // "process" function to process the server's response.
        $_SESSION['openid_token'] = $info->token;
        $return_to = "http://".$_SERVER['HTTP_HOST'].$urls['process'];
        $redirect_url = @$consumer->constructRedirect($info, $return_to,
                                                      "http://" . $_SERVER['HTTP_HOST']);

        header("Location: ".$redirect_url);
    } else {
        render("Got unexpected status: '$status'");
    }
}

/**
 * Process the response from an OpenID server.
 */
function process()
{
    global $consumer,
        $Auth_OpenID_SUCCESS,
        $Auth_OpenID_FAILURE;

    // Retrieve the token from the session.
    $token = $_SESSION['openid_token'];

    // Ask the library to check the response that the server sent us.
    // Status is a code indicating the response type. info is either
    // None or a string containing more information about the return
    // type.

    // Because PHP mangles CGI names by replacing dots with
    // underscores, try to fix the reponse by replacing underscores
    // with dots so we can look for openid.* values.
    $data = Auth_OpenID_Consumer::fixResponse($_GET);

    // Complete the authentication process using the server's
    // response.
    list($status, $info) = $consumer->completeAuth($token, $data);

    $css_class = 'error';
    $openid_url = null;

    // React to the server's response status.
    if (($status == $Auth_OpenID_FAILURE) &&
        $info) {
        // In the case of failure, if info is non-None, it is the URL
        // that we were verifying. We include it in the error message
        // to help the user figure out what happened.
        $openid_url = $info;
        $fmt = "Verification of %s failed.";
        $message = sprintf($fmt, $openid_url);
    } else if ($status == $Auth_OpenID_SUCCESS) {
        // Success means that the transaction completed without
        // error. If info is None, it means that the user cancelled
        // the verification.
        $css_class = 'alert';
        if ($info) {
            // This is a successful verification attempt. If this was
            // a real application, we would do our login, comment
            // posting, etc. here.
            $openid_url = $info;
            $fmt = "You have successfully verified %s as your identity.";
            $message = sprintf($fmt, $openid_url);
        } else {
            // cancelled
            $message = 'Verification cancelled';
        }
    } else {
        // Either we don't understand the code or there is no
        // openid_url included with the error. Give a generic failure
        // message. The library should supply debug information in a
        // log.
        $message = 'Verification failed.';
    }

    render($message, $css_class);
}

?>