SharpRSS/SharpRSS.API/Data/AuthService.cs
2023-09-17 21:41:31 +02:00

77 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using SharpRSS.API.Contracts.Models.User;
using SharpRSS.API.Cryptography;
using SharpRSS.API.Models;
using SharpRSS.API.Models.Auth;
using ToolQit;
using ToolQit.Logging;
namespace SharpRSS.API.Data
{
public class AuthService
{
public AuthService(IConfiguration configuration)
{
_configuration = configuration;
_log = LogManager.CreateLogger(typeof(AuthService));
_log.Information("Setting up service...");
}
private readonly IConfiguration _configuration;
private readonly ILog _log;
public async Task<Result<User>> CreateUser(AuthenticateUser authenticateUserRequest)
{
bool result;
if (authenticateUserRequest.UserName.Any(char.IsWhiteSpace))
return new Result<User>(null, message: "Username should not contain space/whitespaces!");
await using DbAccess access = new DbAccess(_configuration);
var user = access.Users.FirstOrDefault(u => u.UserName == authenticateUserRequest.UserName);
if (user != null)
return new Result<User>(user, message:"User name already exists!");
byte[] hashedPwdBytes = Hasher.HashPassword(authenticateUserRequest.Password, out byte[] salt);
user = new User()
{
UserName = authenticateUserRequest.UserName,
Mail = "",
Password = hashedPwdBytes,
Salt = salt
};
access.Users.Add(user);
try
{
int entries = await access.SaveChangesAsync();
result = entries > 0;
}
catch (Exception e)
{
_log.Error(e, "Error creating user: {UserName}", user.UserName);
return new Result<User>(user, message: "Could not create user!");
}
return new Result<User>(user, result, "Ok");
}
public async Task<Result<IEnumerable<User>>> GetUsers(int take = 50, int skip = 0)
{
if (take is 0 or > 50)
take = 50;
await using DbAccess access = new DbAccess(_configuration);
IEnumerable<User> users = access.Users.Skip(skip).Take(take).ToList();
if (!users.Any())
return new Result<IEnumerable<User>>(users, false, "No users found!");
return new Result<IEnumerable<User>>(users, true, "Ok");
}
public async Task<int> UserCount()
{
await using DbAccess access = new DbAccess(_configuration);
return access.Users.Count();
}
}
}