sso-functions.php 13 KB

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