Search code examples
inno-setuppascalscript

Verify permissions to run Inno Setup installer online


I am looking for a code for Inno Setup, that I can use to make my setup verify my permission to install the program. This code must check a text file on a web server.

  • If the file has the value "False", the setup has to cancel an installation and save the value in a registry file to cancel it always when Internet connection is not available.
  • If the file has the value "True", the setup will continue to install, and it will delete the registry file value if it exists.
  • If there is no Internet and the registry value does not exist the setup will continue to install.

Solution

  • Use InitializeSetup event function to trigger your check using HTTP request.

    [Code]
    
    const
      SubkeyName = 'Software\My Program';
      AllowInstallationValue = 'Allow Installation';
    
    function IsInstallationAllowed: Boolean;
    var
      Url: string;
      WinHttpReq: Variant;
      S: string;
      ResultDWord: Cardinal;
    begin
      try
        WinHttpReq := CreateOleObject('WinHttp.WinHttpRequest.5.1');
        Url := 'https://www.example.com/can_install.txt';
        WinHttpReq.Open('GET', Url, False);
        WinHttpReq.Send('');
        if WinHttpReq.Status <> 200 then
        begin
          RaiseException(
            'HTTP Error: ' + IntToStr(WinHttpReq.Status) + ' ' + WinHttpReq.StatusText);
        end
          else
        begin
          S := Trim(WinHttpReq.ResponseText);
          Log('HTTP Response: ' + S);
    
          Result := (CompareText(S, 'true') = 0);
    
          if RegWriteDWordValue(
               HKLM, SubkeyName, AllowInstallationValue, Integer(Result)) then
            Log('Cached response to registry')
          else
            Log('Error caching response to registry');
        end;
      except
        Log('Error: ' + GetExceptionMessage);
        if RegQueryDWordValue(HKLM, SubkeyName, AllowInstallationValue, ResultDWord) then
        begin
          Log('Online check failed, using cached result');
          Result := (ResultDWord <> 0);
        end
          else
        begin
          Log('Online check failed, no cached result, allowing installation by default');
          Result := True;
        end;
      end;
    
      if Result then Log('Can install')
        else Log('Cannot install');
    end;
    
    function InitializeSetup(): Boolean;
    begin
      Result := True;
      if not IsInstallationAllowed then
      begin
        MsgBox('You cannot install this', mbError, MB_OK);
        Result := False;
      end;
    end;