Guest User

Untitled

a guest
Dec 20th, 2019
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. <?php
  2. /*
  3. NGINX sends headers as
  4. Auth-User: somuser
  5. Auth-Pass: somepass
  6. On my php app server these are seen as
  7. HTTP_AUTH_USER and HTTP_AUTH_PASS
  8. */
  9. if (!isset($_SERVER["HTTP_AUTH_USER"] ) || !isset($_SERVER["HTTP_AUTH_PASS"] )){
  10. fail();
  11. }
  12.  
  13. $username=$_SERVER["HTTP_AUTH_USER"] ;
  14. $userpass=$_SERVER["HTTP_AUTH_PASS"] ;
  15. $protocol=$_SERVER["HTTP_AUTH_PROTOCOL"] ;
  16.  
  17. // default backend port
  18. $backend_port=110;
  19.  
  20. if ($protocol=="imap") {
  21. $backend_port=143;
  22. }
  23.  
  24. if ($protocol=="smtp") {
  25. $backend_port=25;
  26. }
  27.  
  28. // NGINX likes ip address so if your
  29. // application gives back hostname, convert it to ip address here
  30. $backend_ip["old"] ="37.221.164.7";
  31. $backend_ip["new"] ="37.221.164.192";
  32.  
  33. // Authenticate the user or fail
  34. if (!authuser($username,$userpass)){
  35. fail();
  36. exit;
  37. }
  38.  
  39. // Get the server for this user if we have reached so far
  40. $userserver=getmailserver($username);
  41.  
  42. // Get the ip address of the server
  43. // We are assuming that you backend returns hostname
  44. // We try to get the ip else return what we got back
  45. $server_ip=(isset($backend_ip[$userserver]))?$backend_ip[$userserver] :$userserver;
  46.  
  47. // Pass!
  48. pass($server_ip, $backend_port);
  49.  
  50. //END
  51.  
  52. function authuser($user,$pass){
  53. // password characters encoded by nginx:
  54. // " " 0x20h (SPACE)
  55. // "%" 0x25h
  56. // see nginx source: src/core/ngx_string.c:ngx_escape_uri(...)
  57. $pass = str_replace('%20',' ', $pass);
  58. $pass = str_replace('%25','%', $pass);
  59.  
  60. // put your logic here to authen the user to any backend
  61. // you want (datbase, ldap, etc)
  62. // for example, we will just return true;
  63. return true;
  64. }
  65.  
  66. function getmailserver($user){
  67. // put the logic here to get the mailserver
  68. // backend for the user. You can get this from
  69. // some database or ldap etc
  70. $new_users = array("foo@example.com","bar@example.com");
  71. if (in_array($user, $new_users)) {
  72. return "new";
  73. } else {
  74. return "old";
  75. }
  76. }
  77.  
  78. function fail(){
  79. header("Auth-Status: Invalid login or password");
  80. exit;
  81. }
  82.  
  83. function pass($server,$port){
  84. header("Auth-Status: OK");
  85. header("Auth-Server: $server");
  86. header("Auth-Port: $port");
  87. exit;
  88. }
Add Comment
Please, Sign In to add comment