auth.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 = 'Invalid Credentials';
  24. #$AUTH_ERR = 'Not Authorized';
  25. }
  26. }
  27. # Login on dual success
  28. if ($authenticated && $authorized) {
  29. $_SESSION['USER'] = $username;
  30. session_regenerate_id(true);
  31. } else {
  32. logout(false);
  33. }
  34. # Redirect, using the provided target if available
  35. if (authenticated()) {
  36. login_redirect();
  37. }
  38. }
  39. function login_redirect() {
  40. global $MAIN_PAGE;
  41. $url = $MAIN_PAGE;
  42. if (isset($_GET['dest'])) {
  43. $url = $_GET['dest'];
  44. }
  45. header('Location: ' . $url);
  46. }
  47. function logout($redirect = true) {
  48. unset($_SESSION['USER']);
  49. session_regenerate_id(true);
  50. if ($redirect) {
  51. global $MAIN_PAGE;
  52. header('Location: ' . $MAIN_PAGE);
  53. exit();
  54. }
  55. }
  56. function username() {
  57. return $_SESSION['USER'];
  58. }
  59. function authenticated() {
  60. return isset($_SESSION['USER']);
  61. }
  62. function require_authentication() {
  63. global $LOGIN_PAGE;
  64. if (!authenticated()) {
  65. # Provide the current URL for post-auth redirect, if possible
  66. $dest = '';
  67. if (!preg_match('/' . preg_quote($LOGIN_PAGE) . '/', $_SERVER['PHP_SELF'])) {
  68. $dest = $_SERVER['PHP_SELF'];
  69. if ($_GET['series']) {
  70. $dest .= '?series=' . $_GET['series'];
  71. }
  72. }
  73. $url = $LOGIN_PAGE;
  74. if (strlen($dest)) {
  75. $url .= '?dest=' . urlencode($dest);
  76. }
  77. header('Location: ' . $url);
  78. exit();
  79. }
  80. }
  81. function die_if_not_authenticated() {
  82. if (!authenticated) {
  83. die('Failure: Auth');
  84. }
  85. }
  86. ?>