Newer
Older
using AutoMapper;
using Microsoft.EntityFrameworkCore;
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;
private readonly IMapper _mapper;
public UserService(Tsi1Context context, IMapper mapper)
public async Task<ServiceResult<User>> Authenticate(string username, string password, int tenantId)
var user = await _context.Users
.Include(x => x.UserType)
.FirstOrDefaultAsync(x => x.Username == username && x.TenantId == tenantId);
result.HasError = true;
result.Message = string.Format(ErrorMessages.UserDoesNotExist, username);
return result;
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>();
if (type == UserTypes.Student)
{
user.Student = new Student()
{
IdentityCard = dto.IdentityCard,
};
}
if (type == UserTypes.Professor)
{
user.Professor = new Professor()
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
result.Data = user;
return result;
public async Task<ServiceResult<List<UserPreviewDto>>> GetAll(int tenantId)
{
var result = new ServiceResult<List<UserPreviewDto>>();
var users = await _context.Users
.Where(x => x.UserType.Name != UserTypes.FacultyAdmin && x.TenantId == tenantId)
.ToListAsync();
var usersDto = _mapper.Map<List<UserPreviewDto>>(users);
result.Data = usersDto;
return result;
}
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
public async Task<ServiceResult<UserPreviewDto>> GetById(int userId)
{
var result = new ServiceResult<UserPreviewDto>();
var user = await _context.Users
.Include(x => x.UserType)
.Include(x => x.Student)
.Include(x => x.Professor)
.FirstOrDefaultAsync(x => x.Id == userId);
if (user == null)
{
result.HasError = true;
result.Message = string.Format(ErrorMessages.UserDoesNotExist, userId);
return result;
}
var userType = user.UserType.Name;
if (userType == UserTypes.Student && user.Student == null)
{
result.HasError = true;
result.Message = string.Format(ErrorMessages.StudentDoesNotExist, userId);
return result;
}
else if(userType == UserTypes.Professor && user.Professor == null)
{
result.HasError = true;
result.Message = string.Format(ErrorMessages.ProffesorDoesNotExist, userId);
return result;
}
var userDto = _mapper.Map<UserPreviewDto>(user);
result.Data = userDto;
return result;
}