public GenericObjectResponse <UserResponse> ChangeUserData(ChangeUserDataPayload payload, long userId)
        {
            UserValidationService service            = new UserValidationService();
            GenericStatusMessage  validationResponse = service.ValidateUserData(payload, false);

            if (validationResponse.Success)
            {
                using (ReservationDataContext context = new ReservationDataContext())
                {
                    User user = context.Users.Single(x => x.Id == userId);
                    user.FirstName      = payload.FirstName ?? user.FirstName;
                    user.LastName       = payload.LastName ?? user.LastName;
                    user.Country        = payload.Country ?? user.Country;
                    user.City           = payload.City ?? user.City;
                    user.Street         = payload.Street ?? user.Street;
                    user.BuildingNumber = payload.BuildingNumber ?? user.BuildingNumber;
                    context.SaveChanges();
                    return(new GenericObjectResponse <UserResponse>(ConvertUserToUserResponse(user)));
                }
            }
            else
            {
                return(new GenericObjectResponse <UserResponse>(validationResponse.Message));
            }
        }
        public GenericStatusMessage ChangeRoomActivation(long roomId, bool activate, bool force)
        {
            DateTime now = DateTime.Now;

            using (ReservationDataContext context = new ReservationDataContext())
            {
                Room room = context.Rooms.Include(x => x.Reservations).Single(x => x.Id == roomId);
                if (!activate)
                {
                    bool hasFutureReservations = room.Reservations.Any(x => x.RentStart >= now && x.Status != ReservationStatus.Rejected);
                    if (hasFutureReservations)
                    {
                        if (!force)
                        {
                            return(new GenericStatusMessage(false, "Could not complete operation, room has future reservations."));
                        }

                        IEnumerable <ReservationRequest> futureReservations = room.Reservations.Where(x => x.RentStart >= now && x.Status != ReservationStatus.Rejected);
                        foreach (ReservationRequest reservation in futureReservations)
                        {
                            reservation.Status = ReservationStatus.Rejected;
                        }
                    }
                }

                room.IsActive = activate;
                context.SaveChanges();
                return(new GenericStatusMessage(true));
            }
        }
示例#3
0
        public LoginResponse ValidateLogin(string username, string password)
        {
            using (ReservationDataContext context = new ReservationDataContext())
            {
                User user = context.Users.FirstOrDefault(x => x.Username == username);
                if (user == null)
                {
                    Logger.Debug($"Username {username} does not exist.");
                    return(null);
                }

                bool correctPassword = PasswordHasher.Validate(password, user.PasswordHash);
                if (!correctPassword)
                {
                    Logger.Debug($"{username} failed to login due to incorrect password.");
                    return(null);
                }

                user.Token           = Guid.NewGuid();
                user.TokenExpiryDate = DateTime.UtcNow + TokenExpiryWindow;
                context.SaveChanges();
                return(new LoginResponse()
                {
                    Token = user.Token
                });
            }
        }
示例#4
0
        public GenericObjectResponse <List <WorkingHoursPayload> > ChangeWorkingHoursForRoom(long roomId, List <WorkingHoursPayload> workingHours, bool shouldValidate = true)
        {
            if (shouldValidate)
            {
                WorkingHoursValidationService workingHoursValidationService = new WorkingHoursValidationService();
                GenericStatusMessage          validationMessage             = workingHoursValidationService.ValidateWorkingHoursData(workingHours);
                if (!validationMessage.Success)
                {
                    return(new GenericObjectResponse <List <WorkingHoursPayload> >(validationMessage.Message));
                }
            }

            try
            {
                using (ReservationDataContext context = new ReservationDataContext())
                {
                    List <WorkingHours> workingHoursToRemove = context.WorkingHours.Where(x => x.RoomId == roomId).ToList();
                    context.WorkingHours.RemoveRange(workingHoursToRemove);
                    List <WorkingHours> workingHoursToAdd = workingHours.Select(x => ConvertWorkingHoursFromPayload(roomId, x)).ToList();
                    context.WorkingHours.AddRange(workingHoursToAdd);
                    context.SaveChanges();
                    List <WorkingHoursPayload> savedWorkingHours = context.WorkingHours
                                                                   .Where(x => x.RoomId == roomId)
                                                                   .Select(ConvertWorkingHoursToPayload)
                                                                   .ToList();
                    return(new GenericObjectResponse <List <WorkingHoursPayload> >(savedWorkingHours));
                }
            }
            catch (DbEntityValidationException e)
            {
                string exceptionMessage = e.EntityValidationErrors.FirstOrDefault()?.ValidationErrors.FirstOrDefault()?.ErrorMessage;
                Logger.Error($"Failed to create working hours. Error: '{exceptionMessage}'");
                return(new GenericObjectResponse <List <WorkingHoursPayload> >("Failed to add working hours, please contact support."));
            }
        }
 public void ExpireToken(long userId)
 {
     using (ReservationDataContext context = new ReservationDataContext())
     {
         User user = context.Users.Single(x => x.Id == userId);
         user.TokenExpiryDate = DateTime.UtcNow;
         context.SaveChanges();
     }
 }
示例#6
0
        public GenericStatusMessage ChangeReservationApproval(long requestId, ReservationStatus status)
        {
            using (ReservationDataContext context = new ReservationDataContext())
            {
                ReservationRequest reservationRequest = context.ReservationRequests.Single(x => x.Id == requestId);
                reservationRequest.Status = status;
                context.SaveChanges();

                return(new GenericStatusMessage(true));
            }
        }
        public async Task <GenericObjectResponse <RoomResponse> > AddRoom(CreateRoomPayload payload, long?userId)
        {
            try
            {
                Logger.Debug($"Attempting to create new room for user {userId}");
                RoomResponse          roomResponse     = null;
                RoomValidationService service          = new RoomValidationService();
                GenericStatusMessage  validationResult = service.ValidateRoomData(payload);
                if (!validationResult.Success)
                {
                    return(new GenericObjectResponse <RoomResponse>(validationResult.Message));
                }

                using (ReservationDataContext context = new ReservationDataContext())
                {
                    Room room = ConvertRoomFromPayload(payload, userId);
                    context.Rooms.Add(room);
                    context.SaveChanges();
                    roomResponse = ConvertRoomToResponse(room, userId);
                }

                Logger.Debug($"Attempting to create working hours for room {roomResponse.Id}");
                WorkingHoursManipulationService workingHoursService = new WorkingHoursManipulationService();
                GenericObjectResponse <List <WorkingHoursPayload> > workingHours = workingHoursService.ChangeWorkingHoursForRoom(roomResponse.Id, payload.WorkingHours);
                if (!workingHours.Status.Success)
                {
                    Logger.Error($"failed to create working hours for room {roomResponse.Id}, Deleting created room.");
                    using (ReservationDataContext context = new ReservationDataContext())
                    {
                        Room room = context.Rooms.Single(x => x.Id == roomResponse.Id);
                        context.Rooms.Remove(room);
                        context.SaveChanges();
                    }
                    return(new GenericObjectResponse <RoomResponse>($"Failed to add room due to faulty working hours: {workingHours.Status.Message}"));
                }
                roomResponse.WorkingHours = workingHours.Object;
                Logger.Debug($"Room created for user {userId}.");
                LatLon latLon = await AddLatLonForRoom(roomResponse.Id);

                if (latLon != null)
                {
                    roomResponse.Lat = latLon.Lat;
                    roomResponse.Lon = latLon.Lon;
                }
                return(new GenericObjectResponse <RoomResponse>(roomResponse));
            }
            catch (DbEntityValidationException e)
            {
                string exceptionMessage = e.EntityValidationErrors.FirstOrDefault()?.ValidationErrors.FirstOrDefault()?.ErrorMessage;
                Logger.Error($"Failed to create room. Error: '{exceptionMessage}'");
                return(new GenericObjectResponse <RoomResponse>("Failed to add the room, please contact support."));
            }
        }
 public GenericStatusMessage AddUser(CreateUserPayload payload, UserRole role)
 {
     try
     {
         Logger.Debug($"Attempting to create new user {payload.Username}");
         using (ReservationDataContext context = new ReservationDataContext())
         {
             User user = ConvertUserFromPayload(payload, role);
             context.Users.Add(user);
             context.SaveChanges();
         }
         Logger.Debug($"{payload.Username} was created successfully.");
         return(new GenericStatusMessage(true));
     }
     catch (DbEntityValidationException e)
     {
         string exceptionMessage = e.EntityValidationErrors.FirstOrDefault()?.ValidationErrors.FirstOrDefault()?.ErrorMessage;
         Logger.Error($"Failed to create user {payload.Username}. Error: '{exceptionMessage}'");
         return(new GenericStatusMessage(false, "Failed to add user, please contact support."));
     }
 }
        public GenericStatusMessage ChangePassword(PasswordChangePayload payload, long userId)
        {
            using (ReservationDataContext context = new ReservationDataContext())
            {
                User user            = context.Users.Single(x => x.Id == userId);
                bool correctPassword = PasswordHasher.Validate(payload.CurrentPassword, user.PasswordHash);
                if (!correctPassword)
                {
                    Logger.Debug($"{user.Username} failed to change password due to incorrect password.");
                    return(new GenericStatusMessage(false, "Password incorrect."));
                }
                else if (payload.NewPassword != payload.NewPasswordAgain)
                {
                    Logger.Debug($"{user.Username} failed to change password due to mismatching passwords.");
                    return(new GenericStatusMessage(false, "Passwords do not match."));
                }

                user.PasswordHash = PasswordHasher.Create(payload.NewPassword);
                context.SaveChanges();
                return(new GenericStatusMessage(true));
            }
        }
示例#10
0
        /// <summary>
        /// Returns the user's ID if token is valid, the user exists, and the role is correct.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="token"></param>
        /// <param name="requiredRoles"></params
        /// <returns></returns>
        public long?ValidateUserToken(string username, Guid token, UserRole[] requiredRoles)
        {
            using (ReservationDataContext context = new ReservationDataContext())
            {
                User user = context.Users.SingleOrDefault(x => x.Username == username && x.Token == token && requiredRoles.Contains(x.Role));
                if (user == null)
                {
                    Logger.Debug($"{username} does not exist.");
                    return(null);
                }

                if (user.TokenExpiryDate < DateTime.UtcNow)
                {
                    Logger.Debug($"{username}'s token has expired.");
                    return(null);
                }

                user.TokenExpiryDate = DateTime.UtcNow + TokenExpiryWindow;
                context.SaveChanges();
                return(user.Id);
            }
        }
        private async Task <LatLon> AddLatLonForRoom(long roomId)
        {
            using (ReservationDataContext context = new ReservationDataContext())
            {
                Room room = context.Rooms.Single(x => x.Id == roomId);
                IGeolocationClient geolocationClient = new MapQuestClient();
                try
                {
                    LatLon latLon = await geolocationClient.ForwardGeolocation(room.Country, room.City, room.Street, room.BuildingNumber);

                    room.Lat = latLon.Lat;
                    room.Lon = latLon.Lon;
                    context.SaveChanges();
                    return(latLon);
                }
                catch (Exception e)
                {
                    Logger.Error($"Failed to extract lat lon information for {roomId}: {e.Message}");
                    return(null);
                }
            }
        }
        public async Task <GenericObjectResponse <RoomResponse> > ChangeRoomData(CreateRoomPayload payload, long roomId)
        {
            RoomValidationService service            = new RoomValidationService();
            GenericStatusMessage  validationResponse = service.ValidateRoomData(payload, false);
            RoomResponse          roomResponse       = null;

            if (validationResponse.Success)
            {
                using (ReservationDataContext context = new ReservationDataContext())
                {
                    Room room = context.Rooms.Include(x => x.WorkingHours).Single(x => x.Id == roomId);
                    room.Name = payload.Name ?? room.Name;
                    room.Size = payload.Size ?? room.Size;
                    room.MaxNumberOfPeople = payload.MaxNumberOfPeople ?? room.MaxNumberOfPeople;
                    room.Country           = payload.Country ?? room.Country;
                    room.City           = payload.City ?? room.City;
                    room.Street         = payload.Street ?? room.Street;
                    room.BuildingNumber = payload.BuildingNumber ?? room.BuildingNumber;
                    context.SaveChanges();
                    roomResponse = ConvertRoomToResponse(room, room.OwnerId);
                }

                LatLon latLon = await AddLatLonForRoom(roomResponse.Id);

                if (latLon != null)
                {
                    roomResponse.Lat = latLon.Lat;
                    roomResponse.Lon = latLon.Lon;
                }

                return(new GenericObjectResponse <RoomResponse>(roomResponse));
            }
            else
            {
                return(new GenericObjectResponse <RoomResponse>(validationResponse.Message));
            }
        }
示例#13
0
        public GenericObjectResponse <ReservationRequestResponse> AddReservation(long roomId, long requesterId, ReservationRequestPayload payload)
        {
            ReservationValidationService reservationValidationService = new ReservationValidationService();

            using (ReservationDataContext context = new ReservationDataContext())
            {
                Room               room = context.Rooms.Include(x => x.WorkingHours).Single(x => x.Id == roomId);
                WorkingHours       matchedWorkingHours = reservationValidationService.GetMatchingWorkingHours(payload, room);
                ReservationRequest reservationRequest  = new ReservationRequest()
                {
                    RentStart   = payload.RentStart,
                    RentEnd     = payload.RentEnd,
                    Status      = ReservationStatus.Pending,
                    Description = payload.Description,
                    FinalPrice  = PriceHelper.CalculatePrice(matchedWorkingHours.PriceForHour, payload.RentStart, payload.RentEnd),
                    RoomId      = roomId,
                    UserId      = requesterId
                };
                context.ReservationRequests.Add(reservationRequest);
                context.SaveChanges();

                return(new GenericObjectResponse <ReservationRequestResponse>(ConvertToResponse(reservationRequest)));
            }
        }