-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdiscourse-sso.php
271 lines (241 loc) · 7.69 KB
/
discourse-sso.php
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
<?php
/*
This is single-file SSO client for Discourse.
# Latest version on Github:
https://github.com/ArseniyShestakov/singlefile-discourse-sso-php
# Discourse How-To about setting SSO provider:
https://meta.discourse.org/t/using-discourse-as-a-sso-provider/32974
# Based off paxmanchris example:
https://gist.github.com/paxmanchris/e93018a3e8fbdfced039
*/
define('SSO_DB_HOST', 'localhost');
define('SSO_DB_USERNAME', '');
define('SSO_DB_PASSWORD', '');
define('SSO_DB_SCHEMA', '');
define('SSO_DB_TABLE', 'sso_login');
define('SSO_URL_LOGGED', 'https://'.$_SERVER['HTTP_HOST']);
define('SSO_URL_SCRIPT', 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']);
define('SSO_URL_DISCOURSE', 'https://example.com');
// "sso secret" from Discourse admin panel
// Good way to generate one on Linux: pwgen -syc
define('SSO_SECRET', '<CHANGE_ME>');
// Another secret used for sign local cookie
define('SSO_LOCAL_SECRET', '<CHANGE_ME>');
// Seconds before new nonce expire
define('SSO_TIMEOUT', 60);
// Seconds before SSO authentication expire
define('SSO_EXPIRE', 2592000);
define('SSO_COOKIE', '__discourse_sso');
define('SSO_COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);
define('SSO_COOKIE_SECURE', true);
define('SSO_COOKIE_HTTPONLY', true);
// We'll only redirect to Discrouse if script executed directly
if(basename(__FILE__) === basename($_SERVER['SCRIPT_NAME']))
{
$DISCOURSE_SSO = new DiscourseSSOClient(true);
$status = $DISCOURSE_SSO->getAuthentication();
if(false !== $status && true == $status['logged'])
{
if(isset($_GET['logout']))
{
$hashedNonce = hash('sha512', $status["nonce"]);
if($hashedNonce === $_GET['logout'])
{
$DISCOURSE_SSO->logoutUser($status["nonce"]);
}
else
{
die("invalid logout request");
}
}
else
{
header('Location: '.URL_LOGGEDREDIRECT);
}
}
else if(empty($_GET) || !isset($_GET['sso']) || !isset($_GET['sig']))
{
$DISCOURSE_SSO->authenticate();
}
else
{
$DISCOURSE_SSO->verify($_GET['sso'], $_GET['sig']);
}
}
class DiscourseSSOClient
{
private $mysqli;
private $sqlStructure = 'CREATE TABLE IF NOT EXISTS `%s` (
`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`nonce` text NOT NULL,
`logged` Tinyint(1) NOT NULL,
`name` text,
`username` text,
`email` text,
`admin` Tinyint(1) NOT NULL,
`moderator` Tinyint(1) NOT NULL,
`expire` int(11) NOT NULL
)';
public function __construct($createTableIfNotExist = false)
{
$this->mysqli = new mysqli(SSO_DB_HOST, SSO_DB_USERNAME, SSO_DB_PASSWORD, SSO_DB_SCHEMA);
if(mysqli_connect_errno())
{
exit('Discourse SSO: could not connect to MySQL database!');
}
if($createTableIfNotExist)
$this->createTableIfNotExist();
if(rand(0, 10) === 50)
$this->removeExpiredNonces();
}
public function getAuthentication()
{
if(empty($_COOKIE) || !isset($_COOKIE[SSO_COOKIE]))
return false;
$cookie_nonce = explode(',', $_COOKIE[SSO_COOKIE], 2);
if($cookie_nonce[1] !== $this->signCookie($cookie_nonce[0]))
return false;
$status = $this->getStatus($this->clear($cookie_nonce[0]));
if(false === $status)
return false;
return $status;
}
public function authenticate()
{
$nonce = hash('sha512', mt_rand().time());
$nonceExpire = time() + SSO_TIMEOUT;
$this->addNonce($nonce, $nonceExpire);
$this->setCookie($nonce, $nonceExpire);
$payload = base64_encode(http_build_query(array(
'nonce' => $nonce,
'return_sso_url' => SSO_URL_SCRIPT
)));
$request = array(
'sso' => $payload,
'sig' => hash_hmac('sha256', $payload, SSO_SECRET)
);
$url = $this->getUrl($request);
header('Location: '.$url);
echo '<a href='.$url.'>Sign in with Discourse</a><pre>';
}
public function verify($sso, $signature)
{
$sso = urldecode($sso);
if(hash_hmac('sha256', $sso, SSO_SECRET) !== $signature)
{
header('HTTP/1.1 404 Not Found');
exit();
}
$query = array();
parse_str(base64_decode($sso), $query);
$query['nonce'] = $this->clear($query['nonce']);
if(false === $this->getStatus($query['nonce'])){
header('HTTP/1.1 404 Not Found');
exit();
}
$loginExpire = time() + SSO_EXPIRE;
$this->loginUser($query, $loginExpire);
$this->setCookie($query['nonce'], $loginExpire);
header('Access-Control-Allow-Origin: *');
header('Location: '.SSO_URL_LOGGED);
}
public function logoutUser($nonce)
{
$this->removeNonce($nonce);
$this->unSetCookie();
header('Location: ' . SSO_URL_LOGGED);
}
public function removeNonce($nonce)
{
$nonce = $this->mysqli->escape_string($nonce);
$this->mysqli->query('DELETE FROM '.SSO_DB_TABLE.' WHERE nonce = "'.$nonce.'"');
}
private function removeExpiredNonces()
{
$this->mysqli->query('DELETE FROM '.SSO_DB_TABLE.' WHERE expire < UNIX_TIMESTAMP()');
}
private function addNonce($nonce, $expire)
{
$nonce = $this->mysqli->escape_string($nonce);
$this->mysqli->query("INSERT INTO ".SSO_DB_TABLE." (`id`, `nonce`, `logged`, `expire`,`admin`,`moderator`) VALUES (NULL, '$nonce', '0', '".$expire."',0,0);");
}
private function getStatus($nonce)
{
$return = array(
'nonce' => $nonce,
'logged' => false,
'data' => array(
'name' => '',
'username' => '',
'email' => '',
'admin' => false,
'moderator' => false
)
);
$nonce = $this->mysqli->escape_string($nonce);
if($result = $this->mysqli->query("SELECT * FROM ".SSO_DB_TABLE." WHERE `nonce`='$nonce' AND `expire` > UNIX_TIMESTAMP()"))
{
if($result->num_rows === 1)
{
$row = $result->fetch_assoc();
$return['logged'] = intval($row['logged']) == 1;
$return['data']['name'] = $row['name'];
$return['data']['username'] = $row['username'];
$return['data']['email'] = $row['email'];
$return['data']['admin'] = intval($row['admin']) == 1;
$return['data']['moderator'] = intval($row['admin']) == 1;
}
return $return;
}
return false;
}
private function loginUser($data, $expire)
{
$isAdmin = $data['admin'] === 'true' ? '1' : '0';
$isModerator = $data['moderator'] === 'true' ? '1' : '0';
$this->mysqli->query("UPDATE `".SSO_DB_TABLE."`
SET
`logged` = 1,
`expire` = ".$expire.",
`name` = '".$this->mysqli->escape_string($data['name'])."',
`username` = '".$this->mysqli->escape_string($data['username'])."',
`email` = '".$this->mysqli->escape_string($data['email'])."',
`admin` = '".$isAdmin."',
`moderator` = '".$isModerator."'
WHERE `nonce` = '".$this->mysqli->escape_string($data['nonce'])."'");
}
private function setCookie($value, $expire)
{
setcookie(SSO_COOKIE, $value.','.$this->signCookie($value), $expire, "/", SSO_COOKIE_DOMAIN, SSO_COOKIE_SECURE, SSO_COOKIE_HTTPONLY);
}
private function unSetCookie()
{
setcookie(SSO_COOKIE, '', time() - 3600, "/", SSO_COOKIE_DOMAIN, SSO_COOKIE_SECURE, SSO_COOKIE_HTTPONLY);
}
private function getUrl($request)
{
return SSO_URL_DISCOURSE.'/session/sso_provider?'.http_build_query($request);
}
private function signCookie($string)
{
return hash_hmac('sha256', $string, SSO_LOCAL_SECRET);
}
private function clear($string)
{
return preg_replace('[^A-Za-z0-9_]', '', trim($string));
}
private function createTableIfNotExist()
{
if($result = $this->mysqli->query(sprintf("SHOW TABLES LIKE '%s'", SSO_DB_TABLE)))
{
if($result->num_rows != 1)
{
$this->mysqli->query(sprintf($this->sqlStructure, SSO_DB_TABLE));
}
}
}
public function dropTable()
{
$this->mysqli->query("DROP TABLE IF EXISTS ".SSO_DB_TABLE);
}
}