auth.php 1.8 KB

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