summaryrefslogtreecommitdiff
path: root/PrincipalProviders/LocalPrincipalProvider.cs
blob: 5c27518cd6f775f50a1fbe05940c1b584dc849ee (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
80
using HyperBooru.Services;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.EntityFrameworkCore;

namespace HyperBooru.PrincipalProviders;

public class LocalPrincipalProvider : PrincipalProvider {
    private IDbContextFactory<HBContext> dbFactory;

    public LocalPrincipalProvider(IDbContextFactory<HBContext> dbFactory) =>
        this.dbFactory = dbFactory;

    public override IPrincipal? GetPrincipal(string name) {
        using var db = dbFactory.CreateDbContext();
        return db.Principals.FirstOrDefault(p => p.Name == name);
    }

    public override IPrincipal[]? SearchPrincipals(string name) {
        using var db = dbFactory.CreateDbContext();
        return db.Principals
            .Where(p => p.Name.ToLower().Contains(name))
            .Cast<IPrincipal>()
            .ToArray();
    }

    public override IUser? GetUser(string name) {
        using var db = dbFactory.CreateDbContext();
        return db.Users.FirstOrDefault(p => p.Name == name);
    }

    public override IGroup? GetGroup(string name) {
        using var db = dbFactory.CreateDbContext();
        return db.Groups.FirstOrDefault(p => p.Name == name);
    }

    public override IGroup[] GetGroups(SecurityIdentifier sid, bool recurse) {
        using var db = dbFactory.CreateDbContext();

        List<LocalGroup> groups = db.Principals
            .First(p => p.Sid == sid)
            .MemberOf;

        if(!recurse)
            return groups.ToArray();

        var allGroups = db.Groups
            .Include(g => g.MemberOf)
            .ToArray();

        groups = allGroups
            .IntersectBy(groups.Select(g => g.Sid), g => g.Sid)
            .ToList();

        while(true) {
            var toAdd = groups
                .SelectMany(g => g.MemberOf)
                .ExceptBy(groups.Select(g => g.Sid), g => g.Sid)
                .ToArray();

            if(toAdd.Count() == 0)
                break;

            groups.AddRange(toAdd);
        }

        return groups.ToArray();
    }

    public override bool ValidatePassword(IUser user, string password) =>
        ((LocalUser) user).PasswordHash == HashPassword(password); 

    public static string HashPassword(string password) =>
        Convert.ToBase64String(
            KeyDerivation.Pbkdf2(
                password,
                Array.Empty<byte>(),
                KeyDerivationPrf.HMACSHA512,
                100_000,
                512 / 8));
}