summaryrefslogtreecommitdiff
path: root/backend/Elements.Backend/Controllers/AuthController.cs
blob: e9dae00703f6090ee9b10ab417e2d5251176ad04 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System.Runtime.Serialization;
using System.Security.Claims;
using System.Text.Json;
using Elements.Data;
using Elements.Data.Models;
using Google.Apis.Auth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Elements.Backend.Controllers;

[ApiController]
[Route("[controller]/[action]")]
public class AuthController : ControllerBase
{
    private readonly IConfiguration _config;
    private readonly ApplicationDbContext _dbContext;

    public AuthController(IConfiguration config, ApplicationDbContext dbContext)
    {
        _config = config;
        _dbContext = dbContext;
    }

    public class LoginModel
    {
        public required string GoogleToken { get; init; }
    }

    [HttpPost]
    public async Task<IActionResult> Login([FromBody] LoginModel model)
    {
        GoogleJsonWebSignature.Payload? payload = await VerifyGoogleIdToken(model.GoogleToken);
        if (payload == null)
            return Unauthorized();

        User? user = await _dbContext.Users.SingleOrDefaultAsync(u => u.GoogleId == payload.Subject);
        if (user != null)
        {
            //Check if user's name changed and update if it did
            if (user.Name != payload.Name)
                user.Name = payload.Name;
        }
        else
        {
            user = new User()
            {
                Name = payload.Name,
                GoogleId = payload.Subject
            };

            await _dbContext.Users.AddAsync(user);
        }

        await _dbContext.SaveChangesAsync();

        List<Claim> claims = new()
        {
            new Claim("id", user.Id.ToString()),
            new Claim(ClaimTypes.Role, "User")
        };
        ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);

        AuthenticationProperties authProperties = new()
        {
            IsPersistent = true,
            AllowRefresh = true
        };

        await HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimsIdentity),
            authProperties);

        var response = new
        {
            Id = user.Id.ToString()
        };
        
        var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
        return Ok(JsonSerializer.Serialize(response, serializeOptions));
    }
    
    [HttpPost]
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return Ok();
    }

    private async Task<GoogleJsonWebSignature.Payload?> VerifyGoogleIdToken(string token)
    {
        try
        {
            GoogleJsonWebSignature.Payload? payload = await GoogleJsonWebSignature.ValidateAsync(token);
            return payload;
        }
        catch (InvalidJwtException)
        {
            return null;
        }
    }
}