auth.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?
  2. $AUTH_ERR = '';
  3. # Always start a session, unless we're on the CLI
  4. if (php_sapi_name() != 'cli') {
  5. session_set_cookie_params(30 * 86400, '/tv', $_SERVER['HTTP_HOST'], true, true);
  6. session_start();
  7. }
  8. function login($username, $password) {
  9. global $AUTH_ERR;
  10. $authenticated = false;
  11. $authorized = false;
  12. # Auth against MyPlex
  13. $token = myplexToken($username, $password);
  14. if ($token !== false) {
  15. $authenticated = true;
  16. } else {
  17. $AUTH_ERR = 'Invalid Credentials';
  18. }
  19. # Authorize against MyPlex
  20. if ($authenticated) {
  21. $authorized = myplexAuthorize($token);
  22. if (!$authorized) {
  23. $AUTH_ERR = 'Not Authorized';
  24. }
  25. }
  26. # Login on dual success
  27. if ($authenticated && $authorized) {
  28. $_SESSION['USER'] = $username;
  29. session_regenerate_id(true);
  30. } else {
  31. logout(false);
  32. }
  33. # Redirect, using the provided target if available
  34. if (authenticated()) {
  35. login_redirect();
  36. }
  37. }
  38. function login_redirect() {
  39. global $MAIN_PAGE;
  40. $url = $MAIN_PAGE;
  41. if (isset($_GET['dest'])) {
  42. $url = $_GET['dest'];
  43. }
  44. header('Location: ' . $url);
  45. }
  46. function logout($redirect = true) {
  47. unset($_SESSION['USER']);
  48. session_regenerate_id(true);
  49. if ($redirect) {
  50. global $MAIN_PAGE;
  51. header('Location: ' . $MAIN_PAGE);
  52. exit();
  53. }
  54. }
  55. function username() {
  56. return $_SESSION['USER'];
  57. }
  58. function authenticated() {
  59. return isset($_SESSION['USER']);
  60. }
  61. function require_authentication() {
  62. global $LOGIN_PAGE;
  63. if (!authenticated()) {
  64. # Provide the current URL for post-auth redirect, if possible
  65. $dest = '';
  66. if (!preg_match('/' . preg_quote($LOGIN_PAGE) . '/', $_SERVER['PHP_SELF'])) {
  67. $dest = $_SERVER['PHP_SELF'];
  68. if ($_GET['series']) {
  69. $dest .= '?series=' . $_GET['series'];
  70. }
  71. }
  72. $url = $LOGIN_PAGE;
  73. if (strlen($dest)) {
  74. $url .= '?dest=' . urlencode($dest);
  75. }
  76. header('Location: ' . $url);
  77. exit();
  78. }
  79. }
  80. function die_if_not_authenticated() {
  81. if (!authenticated) {
  82. die('Failure: Auth');
  83. }
  84. }
  85. ?>