sso-functions.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. <?php
  2. trait SSOFunctions
  3. {
  4. public function ssoCookies()
  5. {
  6. $cookies = array(
  7. 'myPlexAccessToken' => $_COOKIE['mpt'] ?? false,
  8. 'id_token' => $_COOKIE['Auth'] ?? false,
  9. 'jellyfin_credentials' => $_COOKIE['jellyfin_credentials'] ?? false,
  10. 'komga_token' => $_COOKIE['komga_token'] ?? false
  11. );
  12. // Jellyfin cookie
  13. foreach (array_keys($_COOKIE) as $k => $v) {
  14. if (strpos($v, 'user-') !== false) {
  15. $cookiesToAdd = [
  16. $v => $_COOKIE[$v]
  17. ];
  18. $cookies = array_merge($cookies, $cookiesToAdd);
  19. }
  20. }
  21. return $cookies;
  22. }
  23. public function getSSOList($enabledOnly = false)
  24. {
  25. $searchTerm = 'sso';
  26. $list = array_filter($this->config, function ($k) use ($searchTerm) {
  27. return stripos($k, $searchTerm) !== false;
  28. }, ARRAY_FILTER_USE_KEY);
  29. foreach ($list as $key => $sso) {
  30. if (stripos(substr($key, 0, 3), $searchTerm) === false) {
  31. unset($list[$key]);
  32. continue;
  33. }
  34. if (gettype($sso) !== 'boolean') {
  35. unset($list[$key]);
  36. }
  37. if ($enabledOnly) {
  38. if (!$sso) {
  39. unset($list[$key]);
  40. }
  41. }
  42. }
  43. return $list;
  44. }
  45. public function getSSOEnabledCount()
  46. {
  47. $count = count($this->getSSOList(true));
  48. return ($count <= 0) ? 1 : $count;
  49. }
  50. public function getSSOTimeout()
  51. {
  52. return (60000 / $this->getSSOEnabledCount());
  53. }
  54. public function getSSOUserFor($app, $userobj)
  55. {
  56. $map = array(
  57. 'jellyfin' => 'username',
  58. 'ombi' => 'username',
  59. 'overseerr' => 'email',
  60. 'tautulli' => 'username',
  61. 'petio' => 'username',
  62. 'komga' => 'email'
  63. );
  64. return (gettype($userobj) == 'string') ? $userobj : $userobj[$map[$app]];
  65. }
  66. public function ssoCheck($userobj, $password, $token = null)
  67. {
  68. $this->setCurrentUser(false);
  69. $this->setLoggerChannel('Authentication', $this->user['username']);
  70. $this->logger->debug('Starting SSO check function');
  71. if ($this->config['ssoPlex'] && $token) {
  72. $this->logger->debug('Setting Plex SSO cookie');
  73. $this->coookie('set', 'mpt', $token, $this->config['rememberMeDays'], false);
  74. }
  75. if ($this->config['ssoOmbi']) {
  76. $this->logger->debug('Starting Ombi SSO check function');
  77. $fallback = ($this->config['ombiFallbackUser'] !== '' && $this->config['ombiFallbackPassword'] !== '');
  78. $ombiToken = $this->getOmbiToken($this->getSSOUserFor('ombi', $userobj), $password, $token, $fallback);
  79. if ($ombiToken) {
  80. $this->logger->debug('Setting Ombi SSO cookie');
  81. $this->coookie('set', 'Auth', $ombiToken, $this->config['rememberMeDays'], false);
  82. } else {
  83. $this->logger->debug('No Ombi token received from backend');
  84. }
  85. }
  86. if ($this->config['ssoTautulli'] && $this->qualifyRequest($this->config['ssoTautulliAuth'])) {
  87. $this->logger->debug('Starting Tautulli SSO check function');
  88. $tautulliToken = $this->getTautulliToken($this->getSSOUserFor('tautulli', $userobj), $password, $token);
  89. if ($tautulliToken) {
  90. foreach ($tautulliToken as $key => $value) {
  91. $this->logger->debug('Setting Tautulli SSO cookie');
  92. $this->coookie('set', 'tautulli_token_' . $value['uuid'], $value['token'], $this->config['rememberMeDays'], true, $value['path']);
  93. }
  94. } else {
  95. $this->logger->debug('No Tautulli token received from backend');
  96. }
  97. }
  98. if ($this->config['ssoJellyfin']) {
  99. $this->logger->debug('Starting Jellyfin SSO check function');
  100. $jellyfinToken = $this->getJellyfinToken($this->getSSOUserFor('jellyfin', $userobj), $password);
  101. if ($jellyfinToken) {
  102. foreach ($jellyfinToken as $k => $v) {
  103. $this->logger->debug('Setting Jellyfin SSO cookie');
  104. $this->coookie('set', $k, $v, $this->config['rememberMeDays'], false);
  105. }
  106. } else {
  107. $this->logger->debug('No Jellyfin token received from backend');
  108. }
  109. }
  110. if ($this->config['ssoOverseerr']) {
  111. $this->logger->debug('Starting Overseerr SSO check function');
  112. $fallback = ($this->config['overseerrFallbackUser'] !== '' && $this->config['overseerrFallbackPassword'] !== '');
  113. $overseerrToken = $this->getOverseerrToken($this->getSSOUserFor('overseerr', $userobj), $password, $token, $fallback);
  114. if ($overseerrToken) {
  115. $this->logger->debug('Setting Overseerr SSO cookie');
  116. $this->coookie('set', 'connect.sid', $overseerrToken, $this->config['rememberMeDays'], false);
  117. } else {
  118. $this->logger->debug('No Overseerr token received from backend');
  119. }
  120. }
  121. if ($this->config['ssoPetio']) {
  122. $this->logger->debug('Starting Petio SSO check function');
  123. $fallback = ($this->config['petioFallbackUser'] !== '' && $this->config['petioFallbackPassword'] !== '');
  124. $petioToken = $this->getPetioToken($this->getSSOUserFor('petio', $userobj), $password, $token, $fallback);
  125. if ($petioToken) {
  126. $this->logger->debug('Setting Petio SSO cookie');
  127. $this->coookie('set', 'petio_jwt', $petioToken, $this->config['rememberMeDays'], false);
  128. } else {
  129. $this->logger->debug('No Petio token received from backend');
  130. }
  131. }
  132. if ($this->config['ssoKomga'] && $this->qualifyRequest($this->config['ssoKomgaAuth'])) {
  133. $this->logger->debug('Starting Komga SSO check function');
  134. $fallback = ($this->config['komgaFallbackUser'] !== '' && $this->config['komgaFallbackPassword'] !== '');
  135. $komga = $this->getKomgaToken($this->getSSOUserFor('komga', $userobj), $password, $fallback);
  136. if ($komga) {
  137. $this->logger->debug('Setting Komga SSO cookie');
  138. $this->coookie('set', 'komga_token', $komga, $this->config['rememberMeDays'], false);
  139. } else {
  140. $this->logger->debug('No Komga token received from backend');
  141. }
  142. }
  143. return true;
  144. }
  145. public function getKomgaToken($email, $password, $fallback = false)
  146. {
  147. $token = null;
  148. $useMaster = false;
  149. try {
  150. if ($password) {
  151. if ($password == '') {
  152. $useMaster = true;
  153. }
  154. } else {
  155. $useMaster = true;
  156. }
  157. if ($useMaster) {
  158. if ($this->config['komgaSSOMasterPassword'] !== '') {
  159. $password = $this->decrypt($this->config['komgaSSOMasterPassword']);
  160. }
  161. }
  162. $credentials = array('auth' => new Requests_Auth_Digest(array($email, $password)));
  163. $url = $this->qualifyURL($this->config['komgaURL']);
  164. $options = $this->requestOptions($url, $this->getSSOTimeout(), true, false, $credentials);
  165. $response = Requests::get($url . '/api/v2/users/me', ['X-Auth-Token' => 'organizrSSO'], $options);
  166. if ($response->success) {
  167. if ($response->headers['x-auth-token']) {
  168. $this->setLoggerChannel('Komga')->info('Grabbed token');
  169. $token = $response->headers['x-auth-token'];
  170. } else {
  171. $this->setLoggerChannel('Komga')->warning('Komga did not return Token');
  172. }
  173. } else {
  174. if ($fallback) {
  175. $this->setLoggerChannel('Komga')->warning('Komga did not return Token - Will retry using fallback credentials');
  176. } else {
  177. $this->setLoggerChannel('Komga')->warning('Komga did not return Token');
  178. }
  179. }
  180. } catch (Requests_Exception $e) {
  181. $this->setLoggerChannel('Komga')->error($e);
  182. }
  183. if ($token) {
  184. return $token;
  185. } elseif ($fallback) {
  186. return $this->getKomgaToken($this->config['komgaFallbackUser'], $this->decrypt($this->config['komgaFallbackPassword']), false);
  187. } else {
  188. return false;
  189. }
  190. }
  191. public function getJellyfinToken($username, $password)
  192. {
  193. $token = null;
  194. try {
  195. $url = $this->qualifyURL($this->config['jellyfinURL']);
  196. $ssoUrl = $this->qualifyURL($this->config['jellyfinSSOURL']);
  197. $headers = array(
  198. 'X-Emby-Authorization' => 'MediaBrowser Client="Organizr Jellyfin Tab", Device="Organizr_PHP", DeviceId="Organizr_SSO", Version="1.0"',
  199. "Accept" => "application/json",
  200. "Content-Type" => "application/json",
  201. "X-Forwarded-For" => $this->userIP()
  202. );
  203. $data = array(
  204. "Username" => $username,
  205. "Pw" => $password
  206. );
  207. $endpoint = '/Users/authenticatebyname';
  208. $options = $this->requestOptions($url, $this->getSSOTimeout());
  209. $response = Requests::post($url . $endpoint, $headers, json_encode($data), $options);
  210. if ($response->success) {
  211. $token = json_decode($response->body, true);
  212. $this->setLoggerChannel('JellyFin')->info('Grabbed token');
  213. $key = 'user-' . $token['User']['Id'] . '-' . $token['ServerId'];
  214. $jellyfin[$key] = json_encode($token['User']);
  215. $jellyfin['jellyfin_credentials'] = '{"Servers":[{"ManualAddress":"' . $ssoUrl . '","Id":"' . $token['ServerId'] . '","UserId":"' . $token['User']['Id'] . '","AccessToken":"' . $token['AccessToken'] . '"}]}';
  216. return $jellyfin;
  217. } else {
  218. $this->setLoggerChannel('JellyFin')->warning('JellyFin did not return Token');
  219. }
  220. } catch (Requests_Exception $e) {
  221. $this->setLoggerChannel('Jellyfin')->error($e);
  222. }
  223. return false;
  224. }
  225. public function getOmbiToken($username, $password, $oAuthToken = null, $fallback = false)
  226. {
  227. $token = null;
  228. try {
  229. $url = $this->qualifyURL($this->config['ombiURL']);
  230. $headers = array(
  231. "Accept" => "application/json",
  232. "Content-Type" => "application/json",
  233. "X-Forwarded-For" => $this->userIP()
  234. );
  235. $data = array(
  236. "username" => ($oAuthToken ? "" : $username),
  237. "password" => ($oAuthToken ? "" : $password),
  238. "rememberMe" => "true",
  239. "plexToken" => $oAuthToken
  240. );
  241. $endpoint = ($oAuthToken) ? '/api/v1/Token/plextoken' : '/api/v1/Token';
  242. $options = $this->requestOptions($url, $this->getSSOTimeout());
  243. $response = Requests::post($url . $endpoint, $headers, json_encode($data), $options);
  244. if ($response->success) {
  245. $token = json_decode($response->body, true)['access_token'];
  246. $this->setLoggerChannel('Ombi')->info('Grabbed token');
  247. } else {
  248. if ($fallback) {
  249. $this->setLoggerChannel('Ombi')->warning('Ombi did not return Token - Will retry using fallback credentials');
  250. } else {
  251. $this->setLoggerChannel('Ombi')->warning('Ombi did not return Token');
  252. }
  253. }
  254. } catch (Requests_Exception $e) {
  255. $this->setLoggerChannel('Ombi')->error($e);
  256. }
  257. if ($token) {
  258. return $token;
  259. } elseif ($fallback) {
  260. return $this->getOmbiToken($this->config['ombiFallbackUser'], $this->decrypt($this->config['ombiFallbackPassword']), null, false);
  261. } else {
  262. return false;
  263. }
  264. }
  265. public function getTautulliToken($username, $password, $plexToken = null)
  266. {
  267. $token = null;
  268. $tautulliURLList = explode(',', $this->config['tautulliURL']);
  269. if (count($tautulliURLList) !== 0) {
  270. foreach ($tautulliURLList as $key => $value) {
  271. try {
  272. $url = $this->qualifyURL($value);
  273. $headers = array(
  274. "Accept" => "application/json",
  275. "Content-Type" => "application/x-www-form-urlencoded",
  276. "User-Agent" => $_SERVER ['HTTP_USER_AGENT'] ?? null,
  277. "X-Forwarded-For" => $this->userIP()
  278. );
  279. $data = array(
  280. "username" => ($plexToken ? "" : $username),
  281. "password" => ($plexToken ? "" : $password),
  282. "token" => $plexToken,
  283. "remember_me" => 1,
  284. );
  285. $options = $this->requestOptions($url, $this->getSSOTimeout());
  286. $response = Requests::post($url . '/auth/signin', $headers, $data, $options);
  287. if ($response->success) {
  288. $qualifiedURL = $this->qualifyURL($url, true);
  289. $path = ($qualifiedURL['path']) ? $qualifiedURL['path'] : '/';
  290. $token[$key]['token'] = json_decode($response->body, true)['token'];
  291. $token[$key]['uuid'] = json_decode($response->body, true)['uuid'];
  292. $token[$key]['path'] = $path;
  293. $this->setLoggerChannel('Tautulli')->info('Grabbed token from: ' . $url);
  294. } else {
  295. $this->setLoggerChannel('Tautulli')->warning('Error on URL: ' . $url);
  296. }
  297. } catch (Requests_Exception $e) {
  298. $this->setLoggerChannel('Tautulli')->error($e);
  299. }
  300. }
  301. }
  302. return ($token) ? $token : false;
  303. }
  304. public function getOverseerrToken($email, $password, $oAuthToken = null, $fallback = false)
  305. {
  306. $token = null;
  307. try {
  308. $url = $this->qualifyURL($this->config['overseerrURL']);
  309. $headers = array(
  310. "Content-Type" => "application/json",
  311. "X-Forwarded-For" => $this->userIP()
  312. );
  313. $data = array(
  314. "email" => ($oAuthToken ? "" : $email), // not needed yet
  315. "password" => ($oAuthToken ? "" : $password), // not needed yet
  316. "authToken" => $oAuthToken
  317. );
  318. $endpoint = ($oAuthToken ? '/api/v1/auth/plex' : '/api/v1/auth/local');
  319. $options = $this->requestOptions($url, $this->getSSOTimeout());
  320. $response = Requests::post($url . $endpoint, $headers, json_encode($data), $options);
  321. if ($response->success) {
  322. $user = json_decode($response->body, true); // not really needed yet
  323. $token = $response->cookies['connect.sid']->value;
  324. $this->setLoggerChannel('Overseerr')->info('Grabbed token');
  325. } else {
  326. if ($fallback) {
  327. $this->setLoggerChannel('Overseerr')->warning('Overseerr did not return Token - Will retry using fallback credentials');
  328. } else {
  329. $this->setLoggerChannel('Overseerr')->warning('Overseerr did not return Token');
  330. }
  331. }
  332. } catch (Requests_Exception $e) {
  333. $this->setLoggerChannel('Overseerr')->error($e);
  334. }
  335. if ($token) {
  336. return urldecode($token);
  337. } elseif ($fallback) {
  338. return $this->getOverseerrToken($this->config['overseerrFallbackUser'], $this->decrypt($this->config['overseerrFallbackPassword']), null, false);
  339. } else {
  340. return false;
  341. }
  342. }
  343. public function getPetioToken($username, $password, $oAuthToken = null, $fallback = false)
  344. {
  345. $token = null;
  346. try {
  347. $url = $this->qualifyURL($this->config['petioURL']);
  348. $headers = array(
  349. "Content-Type" => "application/json",
  350. "X-Forwarded-For" => $this->userIP()
  351. );
  352. $data = array(
  353. 'user' => [
  354. 'username' => ($oAuthToken ? '' : $username),
  355. 'password' => ($oAuthToken ? '' : $password),
  356. 'type' => 1,
  357. ],
  358. 'authToken' => false,
  359. 'token' => $oAuthToken
  360. );
  361. $endpoint = ($oAuthToken) ? '/api/login/plex_login' : '/api/login';
  362. $options = $this->requestOptions($url, $this->getSSOTimeout());
  363. $response = Requests::post($url . $endpoint, $headers, json_encode($data), $options);
  364. if ($response->success) {
  365. $user = json_decode($response->body, true)['user'];
  366. $token = json_decode($response->body, true)['token'];
  367. $this->setLoggerChannel('Petio')->info('Grabbed token');
  368. } else {
  369. if ($fallback) {
  370. $this->setLoggerChannel('Petio')->warning('Petio did not return Token - Will retry using fallback credentials');
  371. } else {
  372. $this->setLoggerChannel('Petio')->warning('Petio did not return Token');
  373. }
  374. }
  375. } catch (Requests_Exception $e) {
  376. $this->setLoggerChannel('Petio')->error($e);
  377. }
  378. if ($token) {
  379. return $token;
  380. } elseif ($fallback) {
  381. return $this->getPetioToken($this->config['petioFallbackUser'], $this->decrypt($this->config['petioFallbackPassword']), null, false);
  382. } else {
  383. return false;
  384. }
  385. }
  386. }