summaryrefslogtreecommitdiffstats
path: root/modules/systemd.nix
blob: 20b1d739c998dbd7e0a1feacc1c69818cf9ef1fa (plain)
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
{ config, lib, ... }: let
  normalUsers =
    lib.filterAttrs (_: builtins.getAttr "isNormalUser") config.users.users;
in {
  options = {
    tv.systemd.services = lib.mkOption {
      type = lib.types.attrsOf (lib.types.submodule (self: {
        options = {
          operators = lib.mkOption {
            type =
              lib.types.listOf
                (lib.types.enum (builtins.attrNames normalUsers));
            default = [];
          };
        };
      }));
      default = {};
    };
  };
  config = {
    security.polkit.extraConfig = let
      access =
        lib.mapAttrs'
          (name: cfg:
            lib.nameValuePair "${name}.service"
                              (lib.genAttrs cfg.operators (_: true))
          )
          config.tv.systemd.services;
    in lib.optionalString (access != {}) /* js */ ''
      polkit.addRule(function () {
        const access = ${builtins.toJSON access};
        return function (action, subject) {
          if (action.id === "org.freedesktop.systemd1.manage-units") {
            const unit = action.lookup("unit");
            if (
              (access[unit]||{})[subject.user] ||
              (
                unit.includes("@") &&
                (access[unit.replace(/@[^.]+/, "@")]||{})[subject.user]
              )
            ) {
              return polkit.Result.YES;
            }
          }
        }
      }());
    '';
  };
}