Completed
Push — master ( 10f060...e8bd2a )
by Terrence
10:44
created

index-functions.php ➔ getUID()   B

Complexity

Conditions 7
Paths 16

Size

Total Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 16
nop 0
dl 0
loc 72
rs 7.6775
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file contains functions called by index.php. The index.php
5
 * file should include this file with the following statement at the top:
6
 *
7
 * require_once __DIR__ . '/index-functions.php';
8
 */
9
10
use CILogon\Service\Util;
11
use CILogon\Service\Content;
12
use CILogon\Service\DBService;
13
use CILogon\Service\MyProxy;
14
use CILogon\Service\Loggit;
15
16
/**
17
 * getUID
18
 *
19
 * This function takes all of the various required SAML attributes (as
20
 * set in the current Shibboleth session) and makes a call to the
21
 * database (via the dbservice) to get the userid assoicated with
22
 * those attributes.  It sets several PHP session variables such as the
23
 * status code returned by the dbservice, the uid (if found), the
24
 * username to be passed to MyProxy ('distinguished_name'), etc.  If
25
 * there is some kind of error with the database call, an email is
26
 * sent showing which SAML attributes were missing.
27
 *
28
 * All 'returned' variables are stored in various  PHP session variables
29
 * (e.g. 'user_uid', 'distinguished_name', 'status').
30
 */
31
function getUID()
32
{
33
    $shibarray = Util::getIdpList()->getShibInfo();
34
35
    // Don't allow Organization Name to be empty
36
    if (strlen(@$shibarray['Organization Name']) == 0) {
37
        $shibarray['Organization Name'] = 'Unspecified';
38
    }
39
40
    // Extract Silver Level of Assurance from Shib-AuthnContext-Class
41
    if (
42
        preg_match(
43
            '%http://id.incommon.org/assurance/silver%',
44
            Util::getServerVar('Shib-AuthnContext-Class')
45
        )
46
    ) {
47
        $shibarray['Level of Assurance'] =
48
            'http://incommonfederation.org/assurance/silver';
49
    }
50
51
    // Check for session var 'storeattributes' which indicates to
52
    // simply store the user attributes in the PHP session.
53
    // If not set, then by default save the user attributes to
54
    // the database (which also stores the user attributes in
55
    // the PHP session).
56
    $func = 'CILogon\Service\Util::saveUserToDataStore';
57
    if (!empty(Util::getSessionVar('storeattributes'))) {
58
        $func = 'CILogon\Service\Util::setUserAttributeSessionVars';
59
    }
60
61
    // CIL-793 - Calculate missing first/last name for OAuth1
62
    $first_name = @$shibarray['First Name'];
63
    $last_name = @$shibarray['Last Name'];
64
    $display_name = @$shibarray['Display Name'];
65
    $callbackuri = Util::getSessionVar('callbackuri'); // OAuth 1.0a
66
    if (
67
        (strlen($callbackuri) > 0) &&
68
        ((strlen($first_name) == 0) ||
69
         (strlen($last_name) == 0))
70
    ) {
71
        list($first, $last) = Util::getFirstAndLastName(
0 ignored issues
show
Bug introduced by
The method getFirstAndLastName() does not seem to exist on object<CILogon\Service\Util>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
72
            $display_name,
73
            $first_name,
74
            $last_name
75
        );
76
        $first_name = $first;
77
        $last_name = $last;
78
    }
79
80
    $func(
81
        @$shibarray['User Identifier'],
82
        @$shibarray['Identity Provider'],
83
        @$shibarray['Organization Name'],
84
        $first_name,
85
        $last_name,
86
        $display_name,
87
        @$shibarray['Email Address'],
88
        @$shibarray['Level of Assurance'],
89
        @$shibarray['ePPN'],
90
        @$shibarray['ePTID'],
91
        '', // OpenID 2.0 ID
92
        '', // OpenID Connect ID
93
        @$shibarray['Subject ID'],
94
        @$shibarray['Pairwise ID'],
95
        @$shibarray['Affiliation'],
96
        @$shibarray['OU'],
97
        @$shibarray['Member'],
98
        @$shibarray['Authn Context'],
99
        @$shibarray['Entitlement'],
100
        @$shibarray['iTrustUIN']
101
    );
102
}
103
104
/**
105
 * getUserAndRespond
106
 *
107
 * This function gets the user's database UID puts several variables
108
 * in the current PHP session, and responds by redirecting to the
109
 * responseurl in the passed-in parameter.  If there are any issues
110
 * with the database call, an email is sent to the CILogon admins.
111
 *
112
 * @param string $responseurl The full URL to redirect to after getting
113
 *        the userid.
114
 */
115
function getUserAndRespond($responseurl)
0 ignored issues
show
Best Practice introduced by
The function getUserAndRespond() has been defined more than once; this definition is ignored, only the first definition in getuser/index-functions.php (L22-132) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
116
{
117
    getUID(); // Get the user's database user ID, put info in PHP session
118
119
    // Finally, redirect to the calling script.
120
    header('Location: ' . $responseurl);
121
    exit; // No further processing necessary
122
}
123
124
/**
125
 * getPKCS12
126
 *
127
 * This function is called when an ECP client wants to get a PKCS12
128
 * credential.  It first attempts to get the user's database UID. If
129
 * successful, it tries to create a PKCS12 file on disk by calling
130
 * MyProxy.  If successful, it returns the PKCS12 file by setting the
131
 * HTTP Content-type.  If there is an error, it returns a plain text
132
 * file and sets the HTTP response code to an error code.
133
 */
134
function getPKCS12()
135
{
136
    $log = new Loggit();
137
138
    getUID(); // Get the user's database user ID, put info in PHP session
139
140
    $skin = Util::getSkin();
141
    $skin->init(); // Check for forced skin
142
143
    // If 'status' is not STATUS_OK*, then return error message
144
    if (Util::getSessionVar('status') & 1) { // Bad status codes are odd
145
        $errstr = array_search(Util::getSessionVar('status'), DBService::$STATUS);
146
        $log->info('ECP PKCS12 error: ' . $errstr . '.');
147
        outputError($errstr);
148
        Util::unsetAllUserSessionVars();
149
        return; // ERROR means no further processing is necessary
150
    }
151
152
    // CIL-624 Check if X509 certs are disabled
153
    if ((defined('DISABLE_X509')) && (DISABLE_X509 === true)) {
154
        $log->info('ECP PKCS12 error: Downloading certificates is ' .
155
            'disabled due to DISABLE_X509.');
156
        outputError('Downloading certificates is disabled.');
157
        Util::unsetAllUserSessionVars();
158
        return; // ERROR means no further processing is necessary
159
    }
160
161
    // Verify myproxy-logon binary is configured
162
    $disabledbyconf = ((!defined('MYPROXY_LOGON')) || (empty(MYPROXY_LOGON)));
163
    if ($disabledbyconf) {
164
        $log->info('ECP PKCS12 error: Downloading certificates is ' .
165
            'disabled due to myproxy-logon not configured.');
166
        outputError('Downloading certificates is disabled.');
167
        Util::unsetAllUserSessionVars();
168
        return; // ERROR means no further processing is necessary
169
    }
170
171
    $shibarray = Util::getIdpList()->getShibInfo();
172
    if (Util::isEduGAINAndGetCert(@$shibarray['Identity Provider'], @$shibarray['Organization Name'])) {
173
        $log->info('ECP PKCS12 error: Failed to get cert due to eduGAIN IdP restriction.');
174
        outputError('Failed to get cert due to eduGAIN IdP restriction.');
175
        return; // ERROR means no further processing is necessary
176
    }
177
178
    $skin->setMyProxyInfo();
179
    Content::generateP12();  // Try to create the PKCS12 credential file on disk
180
181
    // Look for the p12error PHP session variable. If set, return it.
182
    $p12error = Util::getSessionVar('p12error');
183
    if (strlen($p12error) > 0) {
184
        $log->info('ECP PKCS12 error: ' . $p12error);
185
        outputError($p12error);
186
    } else { // Try to read the .p12 file from disk and return it
187
        $p12 = Util::getSessionVar('p12');
188
        $p12expire = '';
189
        $p12link = '';
190
        $p12file = '';
191
        if (preg_match('/([^\s]*)\s(.*)/', $p12, $match)) {
192
            $p12expire = $match[1];
193
            $p12link = $match[2];
194
        }
195
        if ((strlen($p12link) > 0) && (strlen($p12expire) > 0)) {
196
            $p12file = file_get_contents($p12link);
197
        }
198
199
        if (strlen($p12file) > 0) {
200
            $log->info('ECP PKCS12 success!');
201
            // CIL-507 Special log message for XSEDE
202
            $log->info('USAGE email="' . Util::getSessionVar('email') .
203
                       '" client="ECP"');
204
            header('Content-type: application/x-pkcs12');
205
            echo $p12file;
206
        } else {
207
            $log->info('ECP PKCS12 error: Missing or empty PKCS12 file.');
208
            outputError('Missing or empty PKCS12 file.');
209
        }
210
    }
211
}
212
213
/**
214
 * getCert
215
 *
216
 * This function is called when an ECP client wants to get a PEM-
217
 * formatted X.509 certificate by inputting a certificate request
218
 * generated by 'openssl req'.  It first attempts to get the user's
219
 * database UID. If successful, it calls out to myproxy-logon to get
220
 * a certificate. If successful, it returns the certificate by setting
221
 * the HTTP Content-type to 'text/plain'.  If there is an error, it
222
 * returns a plain text file and sets the HTTP response code to an
223
 * error code.
224
 */
225
function getCert()
226
{
227
    $log = new Loggit();
228
229
    // Verify that a non-empty certreq <form> variable was posted
230
    $certreq = Util::getPostVar('certreq');
231
    if (strlen($certreq) == 0) {
232
        $log->info('ECP certreq error: Missing certificate request.');
233
        outputError('Missing certificate request.');
234
        return; // ERROR means no further processing is necessary
235
    }
236
237
    getUID(); // Get the user's database user ID, put info in PHP session
238
239
    $skin = Util::getSkin();
240
    $skin->init(); // Check for forced skin
241
242
    // If 'status' is not STATUS_OK*, then return error message
243
    if (Util::getSessionVar('status') & 1) { // Bad status codes are odd
244
        $errstr = array_search(Util::getSessionVar('status'), DBService::$STATUS);
245
        $log->info('ECP certreq error: ' . $errstr . '.');
246
        outputError($errstr);
247
        Util::unsetAllUserSessionVars();
248
        return; // ERROR means no further processing is necessary
249
    }
250
251
    // CIL-624 Check if X509 certs are disabled
252
    if ((defined('DISABLE_X509')) && (DISABLE_X509 === true)) {
253
        $log->info('ECP certreq error: Downloading certificates is ' .
254
            'disabled due to DISABLE_X509.');
255
        outputError('Downloading certificates is disabled.');
256
        Util::unsetAllUserSessionVars();
257
        return; // ERROR means no further processing is necessary
258
    }
259
260
    // Verify myproxy-logon binary is configured
261
    $disabledbyconf = ((!defined('MYPROXY_LOGON')) || (empty(MYPROXY_LOGON)));
262
    if ($disabledbyconf) {
263
        $log->info('ECP certreq error: Downloading certificates is ' .
264
            'disabled due to myproxy-logon not configured.');
265
        outputError('Downloading certificates is disabled.');
266
        Util::unsetAllUserSessionVars();
267
        return; // ERROR means no further processing is necessary
268
    }
269
270
    $shibarray = Util::getIdpList()->getShibInfo();
271
    if (Util::isEduGAINAndGetCert(@$shibarray['Identity Provider'], @$shibarray['Organization Name'])) {
272
        $log->info('ECP certreq error: Failed to get cert due to eduGAIN IdP restriction.');
273
        outputError('Failed to get cert due to eduGAIN IdP restriction.');
274
        return; // ERROR means no further processing is necessary
275
    }
276
277
    // Get the certificate lifetime. Set to a default value if not set.
278
    $certlifetime = (int)(Util::getPostVar('certlifetime'));
279
    if ($certlifetime == 0) {  // If not specified, set to default value
280
        $defaultlifetime = $skin->getConfigOption('ecp', 'defaultlifetime');
281
        if ((!is_null($defaultlifetime)) && ((int)$defaultlifetime > 0)) {
282
            $certlifetime = (int)$defaultlifetime;
283
        } else {
284
            $certlifetime = MyProxy::getDefaultLifetime();
285
        }
286
    }
287
288
    // Make sure lifetime is within acceptable range. 277 hrs = 1000000 secs.
289
    list($minlifetime, $maxlifetime) = Util::getMinMaxLifetimes('ecp', 277);
290
    if ($certlifetime < $minlifetime) {
291
        $certlifetime = $minlifetime;
292
    } elseif ($certlifetime > $maxlifetime) {
293
        $certlifetime = $maxlifetime;
294
    }
295
296
    // Make sure that the user's MyProxy username is available.
297
    $dn = Util::getSessionVar('distinguished_name');
298
    if (strlen($dn) > 0) {
299
        // Append extra info, such as 'skin', to be processed by MyProxy.
300
        $skin->setMyProxyInfo();
301
        $myproxyinfo = Util::getSessionVar('myproxyinfo');
302
        if (strlen($myproxyinfo) > 0) {
303
            $dn .= " $myproxyinfo";
304
        }
305
        // Attempt to fetch a credential from the MyProxy server
306
        $cert = MyProxy::getMyProxyCredential(
307
            $dn,
308
            '',
309
            MYPROXY_HOST,
310
            Util::getLOAPort(),
311
            $certlifetime,
312
            '/var/www/config/hostcred.pem',
313
            '',
314
            $certreq
315
        );
316
317
        if (strlen($cert) > 0) { // Successfully got a certificate!
318
            $log->info('ECP getcert success!');
319
            // CIL-507 Special log message for XSEDE
320
            $log->info('USAGE email="' . Util::getSessionVar('email') .
321
                       '" client="ECP"');
322
            header('Content-type: text/plain');
323
            echo $cert;
324
        } else { // The myproxy-logon command failed - shouldn't happen!
325
            $log->info('ECP certreq error: MyProxy unable to create certificate.');
326
            outputError('Error! MyProxy unable to create certificate.');
327
        }
328
    } else { // Couldn't find the 'distinguished_name' PHP session value
329
        $log->info('ECP certreq error: Missing \'distinguished_name\' session value.');
330
        outputError('Cannot create certificate due to missing attributes.');
331
    }
332
}
333
334
/**
335
 * outputError
336
 *
337
 * This function sets the HTTP return type to 'text/plain' and also
338
 * sets the HTTP return code to 400, meaning there was an error of
339
 * some kind.  If there is also a passed in errstr, that is output as
340
 * the body of the HTTP return.
341
 * @param string $errstr (Optional) The error string to print in the
342
 *        text/plain return body.
343
 */
344
function outputError($errstr = '')
345
{
346
    header('Content-type: text/plain', true, 400);
347
    if (strlen($errstr) > 0) {
348
        echo $errstr;
349
    }
350
}
351