File: basicauthentication.pp

package info (click to toggle)
fpc 3.2.0%2Bdfsg-12
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, bullseye-backports
  • size: 338,552 kB
  • sloc: pascal: 3,794,737; xml: 191,997; ansic: 9,637; asm: 8,482; java: 5,346; sh: 4,664; yacc: 3,751; makefile: 2,688; lex: 2,538; javascript: 2,375; sql: 929; php: 473; cpp: 145; perl: 134; sed: 132; csh: 34; tcl: 7
file content (70 lines) | stat: -rw-r--r-- 1,969 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
(* Feel free to use this example code in any way
   you see fit (Public Domain) *)

// Original example: https://gnunet.org/svn/libmicrohttpd/doc/examples/basicauthentication.c

program basicauthentication;

{$mode objfpc}{$H+}

uses
  libmicrohttpd, SysUtils;

const
  PORT = 8888;

  function AnswerToConnection(ACls: Pointer; AConnection: PMHD_Connection;
    AUrl: Pcchar; AMethod: Pcchar; AVersion: Pcchar; AUploadData: Pcchar;
    AUploadDataSize: Psize_t; AConCls: PPointer): cint; cdecl;
  var
    VPage: Pcchar;
    VUser: Pcchar;
    VPass: Pcchar;
    VReturn: cint;
    VFail: Boolean;
    VResponse: PMHD_Response;
  begin
    if StrComp(AMethod, 'GET') <> 0 then
      Exit(MHD_NO);
    if not Assigned(AConCls^) then
    begin
      AConCls^ := AConnection;
      Exit(MHD_YES);
    end;
    VPass := nil;
    VUser := MHD_basic_auth_get_username_password(AConnection, @VPass);
    VFail := (VUser = nil) or (StrComp(VUser, 'root') <> 0) or
      (StrComp(VPass, 'pa$$w0rd') <> 0);
    if VUser <> nil then
      VUser := nil;
    if VPass <> nil then
      VPass := nil;
    if VFail then
    begin
      VPage := '<html><body>Go away.</body></html>';
      VResponse := MHD_create_response_from_buffer(Length(VPage),
        Pointer(VPage), MHD_RESPMEM_PERSISTENT);
      VReturn := MHD_queue_basic_auth_fail_response(AConnection,
        'my realm', VResponse);
    end
    else
    begin
      VPage := '<html><body>A secret.</body></html>';
      VResponse := MHD_create_response_from_buffer(Length(VPage),
        Pointer(VPage), MHD_RESPMEM_PERSISTENT);
      VReturn := MHD_queue_response(AConnection, MHD_HTTP_OK, VResponse);
    end;
    MHD_destroy_response(VResponse);
    Result := VReturn;
  end;

var
  VDaemon: PMHD_Daemon;
begin
  VDaemon := MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, PORT, nil,
    nil, @AnswerToConnection, nil, MHD_OPTION_END);
  if not Assigned(VDaemon) then
    Halt(1);
  ReadLn;
  MHD_stop_daemon(VDaemon);
end.