SharpRSS/SharpRSS.API/Data/AuthService.cs

77 lines
2.8 KiB
C#
Raw Normal View History

2023-09-10 21:32:25 +02:00
using System;
2023-09-17 21:41:31 +02:00
using System.Collections.Generic;
2023-09-10 21:32:25 +02:00
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
2023-09-17 21:41:31 +02:00
using SharpRSS.API.Contracts.Models.User;
2023-09-10 21:32:25 +02:00
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;
2023-09-17 21:41:31 +02:00
public async Task<Result<User>> CreateUser(AuthenticateUser authenticateUserRequest)
2023-09-10 21:32:25 +02:00
{
2023-09-17 21:41:31 +02:00
bool result;
if (authenticateUserRequest.UserName.Any(char.IsWhiteSpace))
return new Result<User>(null, message: "Username should not contain space/whitespaces!");
2023-09-10 21:32:25 +02:00
await using DbAccess access = new DbAccess(_configuration);
2023-09-17 21:41:31 +02:00
var user = access.Users.FirstOrDefault(u => u.UserName == authenticateUserRequest.UserName);
2023-09-10 21:32:25 +02:00
if (user != null)
return new Result<User>(user, message:"User name already exists!");
2023-09-17 21:41:31 +02:00
byte[] hashedPwdBytes = Hasher.HashPassword(authenticateUserRequest.Password, out byte[] salt);
2023-09-10 21:32:25 +02:00
user = new User()
{
2023-09-17 21:41:31 +02:00
UserName = authenticateUserRequest.UserName,
Mail = "",
2023-09-10 21:32:25 +02:00
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!");
}
2023-09-17 21:41:31 +02:00
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();
2023-09-10 21:32:25 +02:00
}
}
}