basicauthentication.pp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. (* Feel free to use this example code in any way
  2. you see fit (Public Domain) *)
  3. // Original example: https://gnunet.org/svn/libmicrohttpd/doc/examples/basicauthentication.c
  4. program basicauthentication;
  5. {$mode objfpc}{$H+}
  6. uses
  7. libmicrohttpd, SysUtils;
  8. const
  9. PORT = 8888;
  10. function AnswerToConnection(ACls: Pointer; AConnection: PMHD_Connection;
  11. AUrl: Pcchar; AMethod: Pcchar; AVersion: Pcchar; AUploadData: Pcchar;
  12. AUploadDataSize: Psize_t; AConCls: PPointer): cint; cdecl;
  13. var
  14. VPage: Pcchar;
  15. VUser: Pcchar;
  16. VPass: Pcchar;
  17. VReturn: cint;
  18. VFail: Boolean;
  19. VResponse: PMHD_Response;
  20. begin
  21. if StrComp(AMethod, 'GET') <> 0 then
  22. Exit(MHD_NO);
  23. if not Assigned(AConCls^) then
  24. begin
  25. AConCls^ := AConnection;
  26. Exit(MHD_YES);
  27. end;
  28. VPass := nil;
  29. VUser := MHD_basic_auth_get_username_password(AConnection, @VPass);
  30. VFail := (VUser = nil) or (StrComp(VUser, 'root') <> 0) or
  31. (StrComp(VPass, 'pa$$w0rd') <> 0);
  32. if VUser <> nil then
  33. VUser := nil;
  34. if VPass <> nil then
  35. VPass := nil;
  36. if VFail then
  37. begin
  38. VPage := '<html><body>Go away.</body></html>';
  39. VResponse := MHD_create_response_from_buffer(Length(VPage),
  40. Pointer(VPage), MHD_RESPMEM_PERSISTENT);
  41. VReturn := MHD_queue_basic_auth_fail_response(AConnection,
  42. 'my realm', VResponse);
  43. end
  44. else
  45. begin
  46. VPage := '<html><body>A secret.</body></html>';
  47. VResponse := MHD_create_response_from_buffer(Length(VPage),
  48. Pointer(VPage), MHD_RESPMEM_PERSISTENT);
  49. VReturn := MHD_queue_response(AConnection, MHD_HTTP_OK, VResponse);
  50. end;
  51. MHD_destroy_response(VResponse);
  52. Result := VReturn;
  53. end;
  54. var
  55. VDaemon: PMHD_Daemon;
  56. begin
  57. VDaemon := MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, PORT, nil,
  58. nil, @AnswerToConnection, nil, MHD_OPTION_END);
  59. if not Assigned(VDaemon) then
  60. Halt(1);
  61. ReadLn;
  62. MHD_stop_daemon(VDaemon);
  63. end.