1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.security.network;
7 
8 import diamond.core.apptype;
9 
10 static if (isWeb)
11 {
12   import diamond.core.webconfig;
13   import diamond.http;
14 
15   /**
16   * Validates the client ip against the "restrictedIPs" field in the web configuration file.
17   * Params:
18   *   client = The client to validate the ip of.
19   */
20   void validateRestrictedIPs(HttpClient client)
21   {
22     if (webConfig.restrictedIPs)
23     {
24       validateRestrictedIPs(webConfig.restrictedIPs, client);
25     }
26   }
27 
28   /**
29   * Validates the client ip against the "globalRestrictedIPs" field in the web configuration file.
30   * Params:
31   *   client = The client to validate the ip of.
32   */
33   void validateGlobalRestrictedIPs(HttpClient client)
34   {
35     if (webConfig.globalRestrictedIPs)
36     {
37       validateRestrictedIPs(webConfig.globalRestrictedIPs, client);
38     }
39   }
40 
41   /**
42   * Validates the client ip against the passed restricted ips.
43   * Params:
44   *   restrictedIPs = The restricted ips to validate with.
45   *   client =       The client to validate the ip of.
46   */
47   private void validateRestrictedIPs
48   (
49     const(string[]) restrictedIPs, HttpClient client
50   )
51   {
52     bool allowed;
53 
54     foreach (ip; restrictedIPs)
55     {
56       if (client.ipAddress == ip)
57       {
58         allowed = true;
59         break;
60       }
61     }
62 
63     if (!allowed)
64     {
65       client.error(HttpStatus.unauthorized);
66     }
67   }
68 }