summaryrefslogtreecommitdiff
path: root/Acl.cs
blob: a16d08ab7563b7dafa19457d2a7edd493ff84641 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System.ComponentModel.DataAnnotations.Schema;

namespace HyperBooru;

public enum AclRuleAction {
    Allow,
    Deny
}

public class Acl {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int           AclId   { get; set; }
    public HBObject      Subject { get; set; }
    public List<AclRule> Rules   { get; set; }

    public static Type GetAclType(HBObject obj) {
        var attrib = Attribute.GetCustomAttribute(obj.GetType(), typeof(AclTypeAttribute), true);

        return (attrib as AclTypeAttribute)?.Type ?? typeof(ObjectPermissions);
    }

    public static IEnumerable<KeyValuePair<string, ulong>> GetPermissionDescriptions(HBObject obj) {
        var aclType = GetAclType(obj);

        foreach(var val in Enum.GetValues(aclType)) {
            var attrib = (AclPermissionAttribute?) Attribute.GetCustomAttribute(
                aclType.GetMember(val.ToString()!).First(),
                typeof(AclPermissionAttribute));

            yield return new(attrib?.Name ?? val.ToString()!, (ulong) val);
        }
    }
}

public class Acl<T> : Acl where T : Enum {
    public Type Type => typeof(T);

    public new List<AclRule<T>> Rules {
        get => base.Rules.Cast<AclRule<T>>().ToList();
        set => base.Rules = value.Cast<AclRule>().ToList();
    }
}

public class AclRule {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int                AclRuleId   { get; set; }
    public SecurityIdentifier Principal   { get; set; }
    public AclRuleAction      Action      { get; set; }
    [Column(TypeName = "bigint")]
    public ulong              Permissions { get; set; }
}

public class AclRule<T> : AclRule where T : Enum {
    public Type Type => typeof(T);

    public new T Permissions {
        get => (T) (object) base.Permissions;
        set => base.Permissions = (ulong) (object) value;
    }
}

public class AclTypeAttribute : Attribute {
    public Type Type { get; private init; }

    public AclTypeAttribute(Type aclType) {
        if(!aclType.IsEnum)
            throw new ArgumentException();
        Type = aclType;
    }
}

public class AclPermissionAttribute : Attribute {
    public string? Name { get; set; }

    public AclPermissionAttribute() {}

    public AclPermissionAttribute(string name) =>
        Name = name;
}