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> CreateUser(AuthenticateUser authenticateUserRequest) { bool result; if (authenticateUserRequest.UserName.Any(char.IsWhiteSpace)) return new Result(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, 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, message: "Could not create user!"); } return new Result(user, result, "Ok"); } public async Task>> GetUsers(int take = 50, int skip = 0) { if (take is 0 or > 50) take = 50; await using DbAccess access = new DbAccess(_configuration); IEnumerable users = access.Users.Skip(skip).Take(take).ToList(); if (!users.Any()) return new Result>(users, false, "No users found!"); return new Result>(users, true, "Ok"); } public async Task UserCount() { await using DbAccess access = new DbAccess(_configuration); return access.Users.Count(); } } }