예제 #1
0
        public async Task <ActionResult <UULResponse> > GetTimeSlots(int year, int month, int day)
        {
            UULResponse response;

            try {
                var rulesDto = await RulesDao.GetCurrentRulesDTOOrDefault(_context);

                if (rulesDto == null)
                {
                    return(Error.RulesNotFound.CreateErrorResponse(_logger, "GetTimeSlots"));
                }
                DateOperations.GetTimeSlotsBoundsUtc(rulesDto.TimeSlotSpan, year, month, day, out DateTime start, out DateTime end);
                var slots = await TimeSlotsDao.GetTimeSlotsByUtcBounds(_context, start, end);

                var data = new ScheduleDTO()
                {
                    Date = year + "/" + month + "/" + day, GymId = null, TimeSlots = slots
                };
                response = new UULResponse()
                {
                    Success = true, Message = year + "/" + month + "/" + day, Data = data
                };
            } catch (Exception e) {
                response = Error.TimeSlotsGetFailed.CreateErrorResponse(_logger, "GetTimeSlots", e);
            }
            return(response);
        }
예제 #2
0
        public async Task <ActionResult <UULResponse> > GetNews(int id)
        {
            UULResponse response;
            var         currentUser = HttpContext.User;

            try {
                var auditory = Auditory.GUESTS;
                if (currentUser.Identity.IsAuthenticated)
                {
                    auditory = (await UserDao.GetUserFromClaimsOrThrow(_context, currentUser)).IsActivated ? Auditory.ACTIVATED : Auditory.REGISTERED;
                }
                var newsDTO = await NewsDao.GetNewsByIdAsync(_context, auditory, id);

                response = new UULResponse()
                {
                    Success = true, Message = "News item", Data = new NewsWebDTO(newsDTO)
                };
            } catch (Exception e) {
                response = new UULResponse()
                {
                    Success = false, Message = e.Message, Data = null
                };
            }
            return(response);
        }
예제 #3
0
        public async Task <UULResponse> UpdateUsertAsync(UserWebInfoDTO dto)
        {
            UULResponse result;

            try {
                var data          = JsonConvert.SerializeObject(dto);
                var stringContent = new StringContent(data, UnicodeEncoding.UTF8, "application/json");
                using var httpResponse = await _httpClient.PostAsync("/api/webusers/update", stringContent);

                httpResponse.EnsureSuccessStatusCode();

                var jsonString = await httpResponse.Content.ReadAsStringAsync();

                var output = JsonConvert.DeserializeObject <UserWebInfoDTO>(jsonString);

                result = new UULResponse()
                {
                    Success = true, Data = output, Message = ""
                };
            } catch (Exception e) {
                result = new UULResponse()
                {
                    Success = false, Data = null, Message = e.Message
                };
            }
            return(result);
        }
예제 #4
0
        public async Task <ActionResult <UULResponse> > DeleteNews(long id)
        {
            UULResponse response;
            var         currentUser = HttpContext.User;

            try {
                var user = await UserDao.GetUserFromClaimsOrThrow(_context, HttpContext.User);

                if (!SecHelper.IsAdmin(user))
                {
                    throw new Exception("Access denied");
                }
                var news = await _context.News.FindAsync(id);

                _context.News.Remove(news);
                await _context.SaveChangesAsync();

                response = new UULResponse()
                {
                    Success = true, Message = "News item was deleted", Data = null
                };
            } catch (Exception e) {
                response = new UULResponse()
                {
                    Success = false, Message = e.Message, Data = null
                };
            }
            return(response);
        }
예제 #5
0
        public async Task <ActionResult <UULResponse> > GetNews()
        {
            UULResponse response;
            var         currentUser = HttpContext.User;

            try {
                var auditory = Auditory.GUESTS;
                if (currentUser.Identity.IsAuthenticated)
                {
                    var user = (await UserDao.GetUserFromClaimsOrDefault(_context, currentUser));
                    if (user == null)
                    {
                        return(Error.ProfileNotFound.CreateErrorResponse(_logger, "GetNews"));
                    }
                    auditory = user.IsActivated ? Auditory.ACTIVATED : Auditory.REGISTERED;
                }
                var newsListDTO = await NewsDao.GetNewsAsync(_context, auditory);

                response = new UULResponse()
                {
                    Success = true, Message = "News list", Data = new NewsPaperDTO()
                    {
                        News = newsListDTO.Select(n => new NewsDTO(n)).ToList()
                    }
                };
            } catch (Exception e) {
                response = Error.NewsGetFailed.CreateErrorResponse(_logger, "GetNews", e);
            }
            return(response);
        }
예제 #6
0
        public async Task <ActionResult <UULResponse> > DeleteHabitant(HabitantDTO habitantDTO)
        {
            var         currentUser = HttpContext.User;
            UULResponse response;

            try {
                var userInfo = SecHelper.GetUserInfo(currentUser.Claims);
                var user     = await _context.Users.Where(u => u.Login.Equals(userInfo.Login) && u.ApartmentCode.Equals(userInfo.ApartmentCode)).FirstAsync();

                var existentHabitants = await _context.Habitants.Where(h => h.User.ID == user.ID).Select(h => new HabitantDTO(h)).ToListAsync();

                if (existentHabitants.Count <= 1)
                {
                    return(Error.ProfileLastHabitantDeletion.CreateErrorResponse(_logger, "DeleteHabitant"));
                }
                var habitant = await _context.Habitants.FindAsync(habitantDTO.ID);

                _context.Habitants.Remove(habitant);
                await _context.SaveChangesAsync();

                var habitants = await _context.Habitants.Where(h => h.User.ID == user.ID).Select(h => new HabitantDTO(h)).ToListAsync();

                userInfo.IsActivated = user.IsActivated;
                userInfo.Habitants   = habitants;
                response             = new UULResponse()
                {
                    Success = true, Message = "Habitant was deleted", Data = userInfo
                };
            } catch (Exception e) {
                response = Error.ProfileDeleteHabitantFailed.CreateErrorResponse(_logger, "DeleteHabitant", e);
            }
            return(response);
        }
예제 #7
0
        public async Task <ActionResult <UULResponse> > AddHabitant(HabitantDTO habitantDTO) // TODO check rules before adding
        {
            var         currentUser = HttpContext.User;
            UULResponse response;

            try {
                var userInfo = SecHelper.GetUserInfo(currentUser.Claims);
                var user     = await _context.Users.Where(u => u.Login.Equals(userInfo.Login) && u.ApartmentCode.Equals(userInfo.ApartmentCode)).SingleOrDefaultAsync();

                if (user == null)
                {
                    return(Error.ProfileNotFound.CreateErrorResponse(_logger, "AddHabitant"));
                }
                var habitant = new Habitant(habitantDTO)
                {
                    User = user
                };
                _context.Habitants.Add(habitant);
                await _context.SaveChangesAsync();

                var habitants = await _context.Habitants.Where(h => h.User.ID == user.ID).Select(h => new HabitantDTO(h)).ToListAsync();

                userInfo.IsActivated = user.IsActivated;
                userInfo.Habitants   = habitants;
                response             = new UULResponse()
                {
                    Success = true, Message = "Habitant was added", Data = userInfo
                };
            } catch (Exception e) {
                response = Error.ProfileAddHabitantFailed.CreateErrorResponse(_logger, "AddHabitant", e);
            }
            return(response);
        }
예제 #8
0
        public async Task <ActionResult <UULResponse> > DeleteUser(UserLoginInfoDTO loginInfoDTO)
        {
            UULResponse response;

            try {
                var userInfoDTO = await AuthenticateUserOrThrow(loginInfoDTO);

                var user = await UserDao.GetUserByDetailsOrThrow(_context, userInfoDTO.Login, userInfoDTO.ApartmentCode);

                _context.Users.Remove(user);
                await _context.SaveChangesAsync();

                response = new UULResponse()
                {
                    Success = true, Message = "Profile was deleted", Data = null
                };
            } catch (AuthException e) {
                response = Error.AuthFailed.CreateErrorResponse(_logger, "DeleteProfile", e);
            } catch (UserProfileNotFoundException e) {
                response = Error.ProfileNotFound.CreateErrorResponse(_logger, "DeleteProfile", e);
            } catch (Exception e) {
                response = Error.ProfileDeletionFailed.CreateErrorResponse(_logger, "DeleteProfile", e);
            }
            return(response);
        }
예제 #9
0
        public async Task <ActionResult <UULResponse> > NewUser(NewUserDTO newUser)
        {
            UULResponse response;

            try {
                if (!newUser.isValid(out var msg))
                {
                    return(Error.ProfileValidationFailed.CreateErrorResponse(_logger, "NewProfile", new Exception(msg)));
                }
                var exist = await _context.Users.AnyAsync(u => u.Login.Equals(newUser.Login) && u.ApartmentCode == newUser.ApartmentCode);

                if (exist)
                {
                    return(Error.ProfileAlreadyExists.CreateErrorResponse(_logger, "NewProfile"));
                }

                var user = UserDao.AddFromDto(_context, newUser);
                await _context.SaveChangesAsync();

                var userInfo    = new UserInfoDTO(user);
                var tokenString = SecHelper.GenerateJSONWebToken(userInfo.Login, userInfo.ApartmentCode, _config);

                response = new UULResponse()
                {
                    Success = true, Message = tokenString, Data = userInfo
                };
            } catch (Exception e) {
                response = Error.ProfileCreationFailed.CreateErrorResponse(_logger, "NewProfile", e);
            }
            return(response);
        }
예제 #10
0
        public async Task <ActionResult <UULResponse> > ChangePassword(UserUpdatePasswordDTO userPwdsDTO)
        {
            if (!userPwdsDTO.isValid(out var msg))
            {
                return(Error.ProfileValidationFailed.CreateErrorResponse(_logger, "ChangePassword", new Exception(msg)));
            }
            UULResponse response;

            try {
                var userInfoDTO = await AuthenticateUserOrThrow(userPwdsDTO.toLoginInfoDTO());

                var user = await UserDao.GetUserByDetailsOrThrow(_context, userInfoDTO.Login, userInfoDTO.ApartmentCode);

                var salt = SecHelper.CreateSalt();
                user.Salt = salt;
                user.Hash = SecHelper.SaltAndHashPwd(userPwdsDTO.NewPwd, salt);
                _context.Users.Update(user);
                await _context.SaveChangesAsync();

                var tokenString = SecHelper.GenerateJSONWebToken(userInfoDTO.Login, userInfoDTO.ApartmentCode, _config);
                var habitants   = await _context.Habitants.Where(h => h.User.ID == user.ID).Select(h => new HabitantDTO(h)).ToListAsync();

                response = new UULResponse()
                {
                    Success = true, Message = tokenString, Data = new UserInfoDTO(user, habitants)
                };
            } catch (UserProfileNotFoundException e) {
                response = Error.ProfileNotFound.CreateErrorResponse(_logger, "ChangePassword", e);
            } catch (AuthException e) {
                response = Error.AuthFailed.CreateErrorResponse(_logger, "ChangePassword", e);
            } catch (Exception e) {
                response = Error.ProfileChangePwdFailed.CreateErrorResponse(_logger, "ChangePassword", e);
            }
            return(response);
        }
예제 #11
0
        public async Task <ActionResult <UULResponse> > GetRules()
        {
            UULResponse response;

            try {
                var rulesDTO = await RulesDao.GetCurrentRulesDTOOrDefault(_context);

                response = new UULResponse()
                {
                    Success = true, Message = "Active Rules", Data = rulesDTO
                };
            } catch (Exception e) {
                response = Error.RulesGetFailed.CreateErrorResponse(_logger, "GetRules", e);
            }
            return(response);
        }
예제 #12
0
        public async Task <ActionResult <UULResponse> > CreateOrUpdateNews(NewsWebDTO dto)
        {
            UULResponse response;

            try {
                var user = await UserDao.GetUserFromClaimsOrThrow(_context, HttpContext.User);

                if (!SecHelper.IsAdmin(user))
                {
                    throw new Exception("Access denied");
                }
                var news = new News(dto);
                var now  = DateOperations.Now();
                if (news.ID == null)
                {
                    news.CreatedAt = now;
                }
                else
                {
                    news.UpdatedAt = now;
                }
                string message = "News was created";
                if (news.ID == null)
                {
                    _context.News.Add(news);
                }
                else
                {
                    _context.News.Update(news);
                    message = "News was upadted";
                }
                await _context.SaveChangesAsync();

                response = new UULResponse()
                {
                    Success = true, Message = message, Data = new NewsWebDTO(news)
                };
            } catch (Exception e) {
                response = new UULResponse()
                {
                    Success = false, Message = e.Message, Data = null
                };
            }
            return(response);
        }
예제 #13
0
        public async Task <ActionResult <UULResponse> > LoginUser(UserLoginInfoDTO loginInfoDTO)
        {
            UULResponse response;

            try {
                var userInfoDTO = await AuthenticateUserOrThrow(loginInfoDTO);

                var tokenString = SecHelper.GenerateJSONWebToken(userInfoDTO.Login, userInfoDTO.ApartmentCode, _config);
                response = new UULResponse()
                {
                    Success = true, Message = "Login success", Data = tokenString
                };
            } catch (AuthException e) {
                response = Error.AuthFailed.CreateErrorResponse(_logger, "Login", e);
            } catch (Exception e) {
                response = Error.ProfileLoginFailed.CreateErrorResponse(_logger, "Login", e);
            }
            return(response);
        }
예제 #14
0
        public async Task <UULResponse> DeleteNewsByIdAsync(long?id)
        {
            UULResponse result;

            try {
                using var httpResponse = await _httpClient.DeleteAsync("/api/webnews/" + id);

                httpResponse.EnsureSuccessStatusCode();

                var jsonString = await httpResponse.Content.ReadAsStringAsync();

                result = JsonConvert.DeserializeObject <UULResponse>(jsonString);
            } catch (Exception e) {
                result = new UULResponse()
                {
                    Success = false, Data = null, Message = e.Message
                };
            }
            return(result);
        }
예제 #15
0
        public async Task <UULResponse <List <NewsWebDTO> > > GetNewsListAsync()
        {
            UULResponse <List <NewsWebDTO> > result;

            try {
                using var httpResponse = await _httpClient.GetAsync("/api/webnews/list");

                httpResponse.EnsureSuccessStatusCode();

                var jsonString = await httpResponse.Content.ReadAsStringAsync();

                result = JsonConvert.DeserializeObject <UULResponse <List <NewsWebDTO> > >(jsonString);
            } catch (Exception e) {
                result = new UULResponse <List <NewsWebDTO> >()
                {
                    Success = false, Data = null, Message = e.Message
                };
            }
            return(result);
        }
예제 #16
0
        public async Task <UULResponse <NewsWebDTO> > UpsertNewsAsync(NewsWebDTO dto)
        {
            UULResponse <NewsWebDTO> result;

            try {
                var data          = JsonConvert.SerializeObject(dto);
                var stringContent = new StringContent(data, Encoding.UTF8, "application/json");
                using var httpResponse = await _httpClient.PostAsync("/api/webnews/news", stringContent);

                httpResponse.EnsureSuccessStatusCode();

                var jsonString = await httpResponse.Content.ReadAsStringAsync();

                result = JsonConvert.DeserializeObject <UULResponse <NewsWebDTO> >(jsonString);
            } catch (Exception e) {
                result = new UULResponse <NewsWebDTO>()
                {
                    Success = false, Data = null, Message = e.Message
                };
            }
            return(result);
        }
예제 #17
0
        public async Task <ActionResult <UULResponse> > EditHabitant(HabitantDTO habitantDTO)
        {
            var         currentUser = HttpContext.User;
            UULResponse response;

            try {
                var userInfo = SecHelper.GetUserInfo(currentUser.Claims);
                var user     = await _context.Users.Where(u => u.Login.Equals(userInfo.Login) && u.ApartmentCode.Equals(userInfo.ApartmentCode)).SingleOrDefaultAsync();

                if (user == null)
                {
                    return(Error.ProfileNotFound.CreateErrorResponse(_logger, "EditHabitant"));
                }
                var habitant = await _context.Habitants.FindAsync(habitantDTO.ID);

                if (habitant == null)
                {
                    return(Error.ProfileHabitantLookupFailed.CreateErrorResponse(_logger, "EditHabitant"));
                }
                habitant.Name      = habitantDTO.Name;
                habitant.AvatarSrc = habitantDTO.AvatarSrc;
                _context.Habitants.Update(habitant);
                await _context.SaveChangesAsync();

                var habitants = await _context.Habitants.Where(h => h.User.ID == user.ID).Select(h => new HabitantDTO(h)).ToListAsync();

                userInfo.IsActivated = user.IsActivated;
                userInfo.Habitants   = habitants;
                response             = new UULResponse()
                {
                    Success = true, Message = "Habitant was updated", Data = userInfo
                };
            } catch (Exception e) {
                response = Error.ProfileEditHabitantFailed.CreateErrorResponse(_logger, "EditHabitant", e);
            }
            return(response);
        }
예제 #18
0
        public async Task <UULResponse> LoginAsync(UserLoginInfoDTO loginInfoDTO)
        {
            var loginItemJson = new StringContent(
                JsonSerializer.Serialize(loginInfoDTO, _jsonSerializerOptions),
                Encoding.UTF8,
                "application/json");
            UULResponse result;

            try {
                using var httpResponse = await _httpClient.PostAsync("/api/users/login", loginItemJson);

                httpResponse.EnsureSuccessStatusCode();

                using var httpResponseStream = await httpResponse.Content.ReadAsStreamAsync();

                result = await JsonSerializer.DeserializeAsync <UULResponse>(httpResponseStream, _jsonSerializerOptions);
            } catch (Exception e) {
                result = new UULResponse()
                {
                    Success = false, Data = null, Message = e.Message
                };
            }
            return(result);
        }
예제 #19
0
        public async Task <ActionResult <UULResponse> > GetMyUserInfo()
        {
            var         currentUser = HttpContext.User;
            UULResponse response;

            try {
                var userInfo = SecHelper.GetUserInfo(currentUser.Claims);
                var user     = await UserDao.GetUserByDetailsOrThrow(_context, userInfo.Login, userInfo.ApartmentCode);

                var habitants = await _context.Habitants.Where(h => h.User.ID == user.ID).Select(h => new HabitantDTO(h)).ToListAsync();

                userInfo.IsActivated = user.IsActivated;
                userInfo.Habitants   = habitants;
                response             = new UULResponse()
                {
                    Success = true, Message = "", Data = userInfo
                };
            } catch (UserProfileNotFoundException e) {
                response = Error.ProfileNotFound.CreateErrorResponse(_logger, "ProfileInfo", e);
            } catch (Exception e) {
                response = Error.ProfileGetInfoFailed.CreateErrorResponse(_logger, "ProfileInfo", e);
            }
            return(response);
        }
예제 #20
0
        private async Task <ActionResult <UULResponse> > BookTimeSlotByGym(BookTimeSlotDTO dto, int gymId)
        {
            UULResponse response; // TODO refactor to use exceptions
            var         currentUser = HttpContext.User;

            try {
                var userInfo = SecHelper.GetUserInfo(currentUser.Claims);
                var user     = await _context.Users.Where(u => u.Login.Equals(userInfo.Login) && u.ApartmentCode.Equals(userInfo.ApartmentCode)).SingleOrDefaultAsync();

                if (user is null)
                {
                    return(Error.ProfileNotFound.CreateErrorResponse(_logger, "BookTimeSlotsByGym"));
                }
                if (!user.IsActivated)
                {
                    return(Error.ProfileNotActivated.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                var timeSlot = await _context.TimeSlots
                               .Include(t => t.OccupiedBy)
                               .Include(t => t.Gym)
                               .FirstOrDefaultAsync(t => t.ID == dto.TimeslotId);

                if (timeSlot is null)
                {
                    return(Error.TimeSlotNotFound.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                var rulesDto = await RulesDao.GetCurrentRulesDTOOrDefault(_context);

                if (rulesDto is null)
                {
                    return(Error.RulesNotFound.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                DateOperations.GetTodayTimeSlotsBoundsUtc(rulesDto.TimeSlotSpan, out DateTime todayStart, out DateTime todayEnd);

                if (!timeSlot.Gym.IsOpen)
                {
                    return(Error.GymClosed.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                if (!(timeSlot.Start.IsWithinBounds(todayStart, todayEnd)))
                {
                    return(Error.TimeSlotNotToday.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                if (timeSlot.OccupiedBy.Count >= rulesDto.PersonsPerTimeSlot)
                {
                    return(Error.TimeSlotFull.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                if (await AlreadyBookedInBoundsUTC(dto.HabitantId, todayStart, todayEnd))
                {
                    return(Error.TimeSlotOverbooking.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }

                Habitant habitant = await _context.Habitants.FindAsync(dto.HabitantId);

                if (habitant is null)
                {
                    return(Error.ProfileHabitantLookupFailed.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                timeSlot.OccupiedBy.Add(habitant);
                habitant.LastGymVisit = timeSlot.Start;
                _context.TimeSlots.Update(timeSlot);
                _context.Habitants.Update(habitant);
                var success = await _context.SaveChangesAsync() != 0;

                var slots = gymId == -1 ? await TimeSlotsDao.GetTimeSlotsByUtcBounds(_context, todayStart, todayEnd) : await TimeSlotsDao.GetTimeSlotsByUtcBounds(_context, gymId, todayStart, todayEnd);

                var data = new ScheduleDTO()
                {
                    Date = todayStart.Year + "/" + todayStart.Month + "/" + todayStart.Day, GymId = gymId == -1 ? null : gymId, TimeSlots = slots
                };
                response = new UULResponse()
                {
                    Success = success, Message = "Booked", Data = data
                };
            } catch (Exception e) {
                response = Error.TimeSlotsBookingFailed.CreateErrorResponse(_logger, "BookTimesSlotsByGym", e);
            }
            return(response);
        }