auth.php 1.6 KB

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