86 lines
2.2 KiB
C#
86 lines
2.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.Linq;
|
|
using System.Security.Cryptography;
|
|
using System.Threading.Tasks;
|
|
using Interlinked.Shared.Model;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Interlinked.User.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/auth")]
|
|
public class AuthController : ControllerBase
|
|
{
|
|
public AuthController(StoreContext db)
|
|
{
|
|
_db = db;
|
|
}
|
|
private readonly StoreContext _db;
|
|
|
|
[AllowAnonymous]
|
|
[HttpPost("register")]
|
|
public async Task<IActionResult> Register([FromBody] string email, [FromBody] string username, [FromBody] string? name, [FromBody] string password)
|
|
{
|
|
email = email.ToLower().Trim();
|
|
username = username.Trim();
|
|
|
|
if (_db.Users.AsNoTracking().Any(u => u.Username.Equals(username, StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
return Conflict("Username taken.");
|
|
}
|
|
//VALID???
|
|
if (_db.Users.AsNoTracking().Any(u => u.Email == email))
|
|
{
|
|
return Conflict("Email taken.");
|
|
}
|
|
|
|
byte[] salt = new byte[16];
|
|
RandomNumberGenerator.Fill(salt);
|
|
byte[] hash = UserModel.HashPassword(password, salt.ToArray());
|
|
|
|
UserModel u = new()
|
|
{
|
|
Email = email,
|
|
Username = username,
|
|
Salt = salt,
|
|
Name = name,
|
|
Hash = hash
|
|
};
|
|
|
|
//throw new NotImplementedException();
|
|
await _db.Users.AddAsync(u);
|
|
await _db.SaveChangesAsync();
|
|
|
|
return Ok(u);
|
|
}
|
|
|
|
[AllowAnonymous]
|
|
[HttpPost("login")]
|
|
public async Task<IActionResult> Login([FromBody] string email, [FromBody] string password)
|
|
{
|
|
email = email.ToLower().Trim();
|
|
UserModel? u = _db.Users.AsNoTracking().FirstOrDefault(u => email.Equals(u.Email));
|
|
|
|
if (u is null || !u.CheckHash(password))
|
|
{
|
|
return Unauthorized();
|
|
}
|
|
|
|
|
|
//Create auth session
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpGet("logout")]
|
|
public async Task<IActionResult> Logout()
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
|
|
}
|