summaryrefslogtreecommitdiff
path: root/Services/UserService.cs
blob: 96f5b5f9a893755903b65f1fcd68e97d3a1f0acf (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
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Security.Principal;

namespace HyperBooru.Services;

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

    public event EventHandler<bool> ShowNsfwChanged;

    public bool Login(string username, string password);
    public void Logout();
}

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

    public event EventHandler<bool> ShowNsfwChanged;

    private bool showNsfw = false;

    private IGlobalUserService   globalUserService;
    private IHttpContextAccessor httpContextAccessor;

    public UserService(
        IGlobalUserService globalUserService,
        IHttpContextAccessor httpContextAccessor) {

        this.globalUserService   = globalUserService;
        this.httpContextAccessor = httpContextAccessor;
    }

    public bool Login(string username, string password) {
        var claims = new Claim[] {
        };

        var claimsIdentity = new ClaimsIdentity(
            claims,
            CookieAuthenticationDefaults.AuthenticationScheme);

        var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

        if(httpContextAccessor.HttpContext is null)
            return false;

        httpContextAccessor.HttpContext.SignInAsync(claimsPrincipal)
            .GetAwaiter()
            .GetResult();

        return true;
    }

    public void Logout() {
        httpContextAccessor.HttpContext?.SignOutAsync()
            .GetAwaiter()
            .GetResult();
    }
}