summaryrefslogtreecommitdiffstats
path: root/src/Controllers/AccountController.cs
blob: e1f694604bf2d9209c9d4fea576a248d1063f998 (plain) (blame)
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using IOL.Fagprove.Data;
using IOL.Fagprove.Data.DTOs;
using IOL.Fagprove.Services.Interfaces;
using IOL.Fagprove.Utilities;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace IOL.Fagprove.Controllers
{
    public class AccountController : BaseController
    {
        private readonly AppDbContext _context;
        private readonly IUserService _userService;

        public AccountController(AppDbContext context, IUserService userService)
        {
            _context = context;
            _userService = userService;
        }

        [HttpPost("login")]
        [ValidateAntiForgeryToken]
        [AllowAnonymous]
        public async Task<ActionResult> Login(LoginDto data)
        {
            if (data.Password.IsMissing() || data.Username.IsMissing()) return BadRequest("Ett eller flere felt er ikke fylt inn.");
            if (data.Username.IsEmail() == false) return BadRequest("Det ser ikke ut som en e-postadresse");
            var user = _context.Users.SingleOrDefault(u => u.Email == data.Username);
            var passwordMatches = PasswordHasher.PasswordMatches(user?.Password ?? string.Empty, data.Password ?? string.Empty);
            if (user == default || passwordMatches == false) return BadRequest("E-postadresse eller passord er feil");

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Role, user.Role.ToString())
            };
            
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authenticationProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                IssuedUtc = DateTimeOffset.UtcNow
            };

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                          new ClaimsPrincipal(claimsIdentity), authenticationProperties);
            return Ok();
        }

        [HttpGet("logout")]
        public async Task<ActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Redirect("/");
        }

        [AllowAnonymous]
        [HttpPost("forgot")]
        public ActionResult StartForgotPasswordFlow(string email)
        {
            var user = _context.Users.SingleOrDefault(u => u.Email == email);
            if (user == default) return Ok();
            var task = _userService.SetNewTemporaryPasswordAndNotifyUser(user);
            if (task) return Ok();
            return StatusCode(500);
        }

        [HttpPut("password")]
        public ActionResult SetPasswordAfterTemporary(UpdatePasswordDto data)
        {
            var user = _context.Users.SingleOrDefault(u => u.Id == LoggedInUser.Id);
            if (user == default)
            {
                SignOut();
                return Unauthorized(new { error = "Vi fant deg ikke i våre systemer." });
            }

            if (data.Password.IsMissing() || data.Password.IsMissing())
            {
                return BadRequest(new { error = "Ett eller flere felt er ikke fylt inn." });
            }
            if (data.Password.Length <= 5) return BadRequest(new { error = "Passordet er ikke langt nok." });
            if (data.Password != data.PasswordOnceMore) return BadRequest(new { error = "Passordene er forksjellige" });
            var passwordIsUpdated = _userService.UpdatePassword(user, data.Password);
            if (passwordIsUpdated) return Ok();
            return StatusCode(500, new { error = "Noe gikk galt, vennligst prøv igjen senere." });
        }
    }
}