using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Tsi1.BusinessLayer.Dtos; using Tsi1.BusinessLayer.Helpers; using Tsi1.BusinessLayer.Interfaces; using Tsi1.DataLayer; using Tsi1.DataLayer.Entities; namespace Tsi1.BusinessLayer.Services { public class UserService : IUserService { private readonly Tsi1Context _context; public UserService(Tsi1Context context) { _context = context; } public async Task<ServiceResult<User>> Authenticate(string username, string password) { var result = new ServiceResult<User>(); var user = await _context.Users .Include(x => x.UserType) .FirstOrDefaultAsync(x => x.Username == username); if (user == null) { result.HasError = true; result.Message = string.Format(ErrorMessages.UserDoesNotExist, username); return result; } if (user.Password != password) { result.HasError = true; result.Message = ErrorMessages.IncorrectPassword; return result; } result.Data = user; return result; } public async Task<ServiceResult<User>> Create(UserRegisterDto dto, string type) { var result = new ServiceResult<User>(); var user = new User() { UserTypeId = dto.UserTypeId, Username = dto.Username, Password = dto.Password, Email = dto.Email, FirstName = dto.FirstName, LastName = dto.LastName }; if (type == UserTypes.Student) { user.Student = new Student() { IdentityCard = dto.IdentityCard, Age = dto.Age }; } if (type == UserTypes.Professor) { user.Professor = new Professor() { IdentityCard = dto.IdentityCard }; } _context.Users.Add(user); await _context.SaveChangesAsync(); result.Data = user; return result; } } }