summaryrefslogtreecommitdiffstats
path: root/examples/server/common.php
blob: 33e936fa4d1e417ea0867aedf47df0de298d79c2 (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
<?php

require_once "config.php";
require_once "Auth/OpenID/Server.php";
require_once "Auth/OpenID/HMACSHA1.php";

/**
 * Instantiate a new OpenID server object
 */
function getServer()
{
    global $server_url;
    static $server = null;
    if (!isset($server)) {
        $server = new Auth_OpenID_Server($server_url, getOpenIDStore());
    }
    return $server;
}

/**
 * Respond to an OpenID consumer POST request
 */
function returnKV($kv, $success=true)
{
    if (!$success) {
        header('400 Bad Request');
    }
    header('Content-Type: text/plain; charset=us-ascii');
    print $kv;
}

/**
 * Perform an HTTP redirect
 */
function redirect($redir_url)
{
    header('HTTP/1.1 302 Found');
    header('Location: ' . $redir_url);
    header('Content-Type: text/plain; charset=us-ascii');
    print 'Please wait; you are being redirected to ' . $redir_url;
}

/**
 * Display an error page
 */
function showError($error, $status, $message)
{
    header('HTTP/1.1 ' . $status . ' ' . $message);
    header('Content-Type: text/plain; charset=us-ascii');
    print "An error occurred when processing your request:\n$error\n";
}

/**
 * Return a string containing an anchor tag containing the given URL
 *
 * The URL does not need to be quoted, but if text is passed in, then
 * it does.
 */
function linkURL($url, $text=null) {
    $esc_url = htmlspecialchars($url, ENT_QUOTES);
    if ($text === null) {
        $text = $esc_url;
    }
    return "<a href='$esc_url'>$text</a>";
}

function hashPassword($password)
{
    return bin2hex(Auth_OpenID_SHA1($password));
}

/**
 * Set up the session
 */
function init()
{
    session_name('openid_server');
    session_start();
}

/**
 * Check the user's login information
 */
function checkLogin($openid_url, $password)
{
    global $openid_users;
    $hash = hashPassword($password);

    return isset($openid_users[$openid_url])
        && $hash == $openid_users[$openid_url];
}

/**
 * Get the openid_url out of the cookie
 *
 * @return mixed $openid_url The URL that was stored in the cookie or
 * false if there is none present or if the cookie is bad.
 */
function getLoggedInUser()
{
    return isset($_SESSION['openid_url'])
        ? $_SESSION['openid_url']
        : false;
}

/**
 * Set the openid_url in the cookie
 *
 * @param mixed $identity_url The URL to set. If set to null, the
 * value will be unset.
 */
function setLoggedInUser($identity_url=null)
{
    if (!isset($identity_url)) {
        unset($_SESSION['openid_url']);
    } else {
        $_SESSION['openid_url'] = $identity_url;
    }
}

function pageHeader($user, $title, $h1=null, $login=false)
{
    if (!$h1) {
        $h1 = $title;
    }

    if ($user) {
        $head = sprintf(logged_in_pat, linkURL($user));
    } else {
        if (!$login) {
            $head = logged_out_pat;
        }
    }

    return sprintf(html_start, $title, $h1, $head);
}

function pageFoot()
{
    return html_end;
}

function succeed($info)
{
    $server = getServer();
    $resp = $server->getAuthResponse(&$info, true);
    handleResponse($resp, 'badAuth');
}

function doAuth($info)
{
    $req_url = $info->getIdentityURL();
    $user = getLoggedInUser();
    if ($req_url == $user) {
        if (isTrusted($info->getTrustRoot())) {
            // This is a trusted site, so continue
            succeed($info);
        } else {
            $_SESSION['request'] = serialize($info);
            trustPage($info);
        }
    } else {
        $_SESSION['request'] = serialize($info);
        if ($user) {
            $msg = sprintf(bad_user_pat, linkURL($user), linkURL($req_url));
        } else {
            $msg = sprintf(no_user_pat, linkURL($req_url));
        }
        loginPage(array($msg), $req_url);
    }
}

function isTrusted($trust_root)
{
    global $trusted_sites;
    return in_array($trust_root, $trusted_sites);
}

function doError($error)
{
    showError($error, '500', 'Internal error');
    exit(1);
}

function badAuth($info)
{
    doError('Unexpectedly got DO_AUTH inside of DO_AUTH');
}

function handleResponse($response, $do_auth)
{
    list ($status, $info) = $response;
    switch($status) {
    case Auth_OpenID_REMOTE_ERROR:
    case Auth_OpenID_REMOTE_OK:
        returnKV($info);
        break;
    case Auth_OpenID_REDIRECT:
        redirect($info);
        break;
    case Auth_OpenID_DO_AUTH:
        $do_auth($info);
        break;
    case Auth_OpenID_DO_ABOUT:
        aboutPage();
        break;
    case Auth_OpenID_LOCAL_ERROR:
        showError($info, '400', 'Bad request');
        break;
    default:
        $repr = var_export($status, true);
        doError("Internal error: unknown status $repr");
    }
    exit(0);
}


function loginForm($identity_url='')
{
    return sprintf(login_form_pat, $identity_url);
}

function showErrors($errors)
{
    if ($errors) {
        foreach ($errors as $error) {
            print '<div class="error">' . $error . "</div>\n";
        }
    }
}

function loginPage($errors=null, $input=null)
{
    $current_user = getLoggedInUser();
    if ($input === null) {
        $input = $current_user;
    }
    print pageHeader($current_user, 'Log In', null, true);
    showErrors($errors);
    print loginForm(htmlspecialchars($input, ENT_QUOTES));
    print pageFoot();
}

function trustPage($info)
{
    $current_user = getLoggedInUser();
    print pageHeader($current_user, 'Trust This Site');
    print '<p>' . htmlspecialchars($info->getTrustRoot()) . '</p>';
    print '<form method="post" action="trust.php">
<input type="submit" name="trust" value="Trust this site" />
<input type="submit" value="Do not trust this site" />
</form>
';
    print pageFoot();
}

function aboutPage()
{
    $current_user = getLoggedInUser();
    print pageHeader($current_user, 'OpenID Server Endpoint');
    print pageFoot();
}

define('login_form_pat',
       '<div class="login">
  <p>
    Enter your identity URL and password into this form to log in to
    this server. This server must be configured to accept your identity URL.
  </p>

  <form method="post" action="login.php">
    <table>
      <tr>
        <th><label for="openid_url">OpenID URL:</label></th>
        <td><input type="text" name="openid_url"
                   value="%s" id="openid_url" /></td>
      </tr>
      <tr>
        <th><label for="password">Password:</label></th>
        <td><input type="password" name="password" id="password" /></td>
      </tr>
      <tr>
        <td colspan="2"><input type="submit" value="Log in" /></td>
      </tr>
    </table>
  </form>
</div>
');
define('html_start',
'<html>
  <head>
    <title>%s</title>
    <link rel="stylesheet" type="text/css" href="default.css" />
  </head>
  <body>
    <h2>PHP OpenID Server</h2>
    <h1>%s</h1>
    <div class="header">%s</div>
');
define('html_end',
       '  </body>
</html>');

define('bad_user_pat',
       'You are logged in as %s and this request is for %s.');
define('no_user_pat',
       'You are not logged in and this request is for %s.');

define('logged_in_pat',
       'You are logged in as %s. <a href="logout.php">Log out</a>');
define('logged_out_pat',
       'Not logged in. <a href="login.php">Log in</a>');

?>