summaryrefslogtreecommitdiffstats
path: root/shib/api.php
blob: 20987651cd61567bf36a6a73caaccb002a68097a (plain) (blame)
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
<?php

chdir('..');

require_once 'config.php';

/*
Header('Content-Type: text/plain; charset=utf-8');
die( json_encode($_SERVER, JSON_PRETTY_PRINT) );

// */

// Autoload classes from ./inc which adhere to naming scheme <lowercasename>.inc.php
function slxAutoloader($class)
{
	$file = 'inc/' . preg_replace('/[^a-z0-9]/', '', mb_strtolower($class)) . '.inc.php';
	if (!file_exists($file))
		return;
	require_once $file;
}
spl_autoload_register('slxAutoloader');


$response = array();

if (empty($_SERVER['persistent-id'])) {
	// No persistent id given, should not happen!
	$response['status'] = 'error';
	$response['error'] = 'Shibboleth meta data missing!';
	@file_put_contents('/tmp/shib-nopid-' . time() . '-' . $_SERVER['REMOTE_ADDR'] . '.txt', print_r($_SERVER, true));
} else {
	// Query database for user
	$shibId = md5($_SERVER['persistent-id']);
	$user = Database::queryFirst("SELECT user.userid, user.organizationid, user.firstname, user.lastname, user.email "
		. " FROM user "
		. " INNER JOIN organization USING (organizationid) "
		. " WHERE user.shibid = :shibid LIMIT 1", array('shibid' => $shibId));
	// Figure out role
	if (strpos(";{$_SERVER['entitlement']};", ';http://bwidm.de/entitlement/bwLehrpool;') !== false) {
		$role = 'TUTOR';
	} else if (strpos(";{$_SERVER['affiliation']};", ';employee@') !== false
			|| strpos(";{$_SERVER['affiliation']};", ';staff@') !== false
			|| strpos(";{$_SERVER['affiliation']};", ';faculty@') !== false) {
		$role = 'TUTOR';
	} else {
		@file_put_contents('/tmp/shib-student-' . time() . '-' . $_SERVER['REMOTE_ADDR'] . '.txt', print_r($_SERVER, true));
		$role = 'STUDENT';
		// NEW: Ignore students for now
		$response = array(
			'status' => 'error',
			'error' => "Sie wurden als Student eingestuft und können sich daher nicht an der bwLehrpool-Suite anmelden."
				. "\nFalls Ihr Nutzerkonto kein Studentenkonto ist stellen Sie sicher, dass Ihr IdP für berechtigte"
				. "\nAccounts entweder das bwLehrpool-Entitlement ausliefert, oder das Attribut 'affiliation'"
				. "\nausgeliefert wird, und es entweder 'employee@..', 'staff@..' oder 'faculty@..' enthält."
				. "\n\nMehr Informationen finden Sie unter www.bwlehrpool.de"
		);
		Header('Content-Type: text/plain; charset=utf-8');
		die(json_encode($response, JSON_PRETTY_PRINT));
		// end IGNORE STUDENTS
	}
	if ($user === false) {
		// Not found, so we don't know which satellite to use
		if ($role === 'STUDENT') {
			$response['status'] = 'ok';
			if (isset($_SERVER['givenName'])) {
				$response['firstName'] = $_SERVER['givenName'];
			}
			if (isset($_SERVER['sn'])) {
				$response['lastName'] = $_SERVER['sn'];
			}
			if (isset($_SERVER['mail'])) {
				$response['mail'] = $_SERVER['mail'];
			}
			$response['userId'] = $shibId;
			// Try to figure out orgId
			if (!isset($response['organizationId']) && isset($_SERVER['eppn'])) {
				if (preg_match('/@(.+)$/', $_SERVER['eppn'], $out)) {
					$out = Database::queryFirst("SELECT organizationid FROM organization_suffix WHERE suffix = :suffix", array(
						'suffix' => $out[1]
					));
					if ($out !== false) {
						$response['organizationId'] = $out['organizationid'];
					}
				}
			}
			if (!isset($response['organizationId']) && isset($_SERVER['affiliation'])) {
				if (preg_match('/(^|;)[^@]+@([^;]+)/', $_SERVER['affiliation'], $out)) {
					$out = Database::queryFirst("SELECT organizationid FROM organization_suffix WHERE suffix = :suffix", array(
						'suffix' => $out[2]
					));
					if ($out !== false) {
						$response['organizationId'] = $out['organizationid'];
					}
				}
			}
			// This one we send to the running master server handler
			$rpc = $response;
			$rpc['role'] = $role;
			// This one we only send to the user
			// TODO
			/*
			$response['satellites'] = $sat1;
			$response['satellites2'] = $sat2;
			*/
		} else {
			$response['status'] = 'unregistered';
		}
		$response['id'] = $shibId;
		$response['url'] = 'https://bwlp-masterserver.ruf.uni-freiburg.de/webif/';
		@file_put_contents('/tmp/shib-unreg-' . time() . '-' . $_SERVER['REMOTE_ADDR'] . '.txt', print_r($_SERVER, true));
	} else {
		// Found, see if we got personal information, either temporarily through metadata, or from database
		$firstName = $user['firstname'];
		$lastName = $user['lastname'];
		$mail = $user['email'];
		if (empty($firstName) && isset($_SERVER['givenName']))
			$firstName = trim($_SERVER['givenName']);
		if (empty($lastName) && isset($_SERVER['sn']))
			$lastName = trim($_SERVER['sn']);
		if (empty($mail) && isset($_SERVER['mail']))
			$mail = trim($_SERVER['mail']);
		//
		$login = (empty($user['userid']) ? $shibId : $user['userid'] );
		if (empty($firstName) || empty($lastName) || empty($login)) {
			// This means the user did not provide personal information on signup, nor does the IdP send them
			$response['status'] = 'anonymous';
		} else {
			// Seems ok!
			// Determine satellite(s)
			$res = Database::simpleQuery("SELECT satellitename, addresses, certsha256 FROM satellite"
				. " WHERE organizationid = :organizationid AND userid IS NULL", array('organizationid' => $user['organizationid']));
			$sat1 = array(); // Legacy
			$sat2 = array();
			while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
				$addrs = json_decode($row['addresses'], true);
				if (!is_array($addrs) || empty($addrs))
					continue;
				$sat1[$row['satellitename']] = $addrs[0];
				$sat2[$row['satellitename']] = array(
					'addresses' => $addrs,
					'certHash' => $row['certsha256']
				);
			}
			//
			$response['status'] = 'ok';
			$response['firstName'] = $firstName;
			$response['lastName'] = $lastName;
			$response['mail'] = $mail;
			$response['userId'] = $user['userid'];
			$response['organizationId'] = $user['organizationid'];
			// This one we send to the running master server handler
			$rpc = $response;
			$rpc['userId'] = $login;
			$rpc['role'] = $role;
			// This one we only send to the user
			$response['satellites'] = $sat1;
			$response['satellites2'] = $sat2;
		}
	}
}

if (isset($rpc)) {
			$reply = RPC::submit($rpc);
			if (preg_match('/^TOKEN:(\w+) SESSIONID:(\w+)$/', $reply, $out)) {
				$response['token'] = $out[1];
				$response['sessionId'] = $out[2];
			} else {
				if (empty($rpc['mail'])) {
					$reply .= ' (No email given)';
				}
				if (empty($rpc['firstName'])) {
					$reply .= ' (No first name given)';
				}
				if (empty($rpc['lastName'])) {
					$reply .= ' (No last name given)';
				}
				if (empty($rpc['organizationId'])) {
					$reply .= ' (No organization id found)';
				}
				$response['error'] = $reply;
				$response['status'] = 'error';
			}
}

Header('Content-Type: text/plain; charset=utf-8');
echo json_encode($response, JSON_PRETTY_PRINT);