82 lines
2.6 KiB
C#
82 lines
2.6 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Http;
|
|
using System;
|
|
using System.Web;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using SecureCore.Services;
|
|
|
|
namespace SecureCore.Controllers
|
|
{
|
|
[Route("[controller]")]
|
|
[ApiController]
|
|
public class AuthController : Controller
|
|
{
|
|
[HttpPost("login")]
|
|
[AcceptVerbs("POST")]
|
|
public IActionResult Login(LoginInfo info)
|
|
{
|
|
var (password, saltHash) = UserDataService.GetUserPasswordHash(info.UserName);
|
|
|
|
if (Authentication.PasswordIsValid(info.Password, saltHash, password))
|
|
{
|
|
if (HttpContext.Request.Cookies.ContainsKey("Session"))
|
|
{
|
|
if(UserDataService.IsSessionTokenValid(HttpContext.Request.Cookies["Session"]))//, info.UserName))
|
|
return Ok($"Session is live{Environment.NewLine}");
|
|
}
|
|
|
|
var sessionToken = Authentication.CreateSessionToken();
|
|
|
|
UserDataService.SetUserSessionToken(UserDataService.GetUserId(info.UserName), sessionToken, DateTime.Now.AddDays(7));
|
|
|
|
HttpContext.Response.Cookies.Append("Session", sessionToken, GetCookieOptions());
|
|
|
|
return Ok($"Logged in success{Environment.NewLine}");
|
|
}
|
|
else
|
|
{
|
|
return Unauthorized();
|
|
}
|
|
}
|
|
|
|
[HttpPost("Register")]
|
|
[AcceptVerbs("POST")]
|
|
public IActionResult Register(LoginInfo info)
|
|
{
|
|
var (hash, salt) = Authentication.HashPassword(info.Password);
|
|
var sessionToken = Authentication.CreateSessionToken();
|
|
|
|
try
|
|
{
|
|
var i = UserDataService.RegisterNewUser(info.UserName, info.Email, hash, salt, sessionToken, DateTime.Now.AddDays(7));
|
|
|
|
HttpContext.Response.Cookies.Append("Session", sessionToken, GetCookieOptions());
|
|
|
|
return Ok($"New User ID: {i}");
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
return Unauthorized(e.Message);
|
|
}
|
|
}
|
|
|
|
private CookieOptions GetCookieOptions()
|
|
{
|
|
return new CookieOptions
|
|
{
|
|
//Domain = "copyrightcrusader.org",
|
|
Expires = DateTime.Now.AddDays(7),
|
|
//HttpOnly = true,
|
|
//Secure = true,
|
|
Path = "/",
|
|
SameSite = SameSiteMode.Strict
|
|
};
|
|
}
|
|
}
|
|
|
|
//TODO: Read more https://www.valentinog.com/blog/cookies/
|
|
// And this https://blog.webf.zone/ultimate-guide-to-http-cookies-2aa3e083dbae
|
|
}
|