summaryrefslogtreecommitdiff
path: root/Services/UserService.cs
blob: 1a2bd8ff8fbe83ba9ecab84b1ae3e18521f7571e (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
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.EntityFrameworkCore;

namespace HyperBooru.Services;

public interface IUserService {
    public bool ShowNsfw { get; set; }

    public event EventHandler<bool> ShowNsfwChanged;

    public User User { get; }
}

public class UserService : IUserService {
    public bool ShowNsfw {
        get => showNsfw;
        set {
            showNsfw = value;
            ShowNsfwChanged?.Invoke(this, value);
        }
    }

    public User User {
        get {
            if(user is not null)
                return user;
            using var db = dbFactory.CreateDbContext();
            int id = int.Parse(httpContextAccessor
                .HttpContext!.User.Claims
                .First(c => c.Type == "ObjectId")
                .Value);
            return user = db.Users.Find(id)!;
        }
    }

    public event EventHandler<bool> ShowNsfwChanged;

    private bool showNsfw = false;

    private User? user;

    private IDbContextFactory<HBContext> dbFactory;
    private IHttpContextAccessor         httpContextAccessor;

    public UserService(
        IDbContextFactory<HBContext> dbFactory,
        IHttpContextAccessor httpContextAccessor) {

        this.dbFactory           = dbFactory;
        this.httpContextAccessor = httpContextAccessor;
    }

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