public static void ClassCleanup()
        {
            Mock<IUserHelper> UserHelper = new Mock<IUserHelper>(); ;
            UserHelper.Setup(x => x.GetLoggedUserRole(It.IsAny<HttpRequestMessage>())).Returns(new Role { Id = 1, Name = "Administrator" });

            var userController = new UserController(UserHelper.Object);

            using (var context = new TravelPlannerEntities())
            {
                var users = context.User.Where(x => x.Username == TestUserAdmnistratorName
                    || x.Username == TestUserManagerName
                    || x.Username == TestUserRegularUserName
                    || x.Username.Contains(RegisterUserTestName));

                /// Remove trips
                foreach (var user in users)
                {
                    var trips = context.Trip.Where(x => x.UserId == user.Id);
                    context.Trip.RemoveRange(trips);
                }

                /// Remove users
                context.User.RemoveRange(users);
                context.SaveChanges();
            }
        }
Exemplo n.º 2
0
        public int CreateOrUpdateUser([FromUri]User user)
        {
            using (var context = new TravelPlannerEntities())
            {
                var loggedUser = UserHelper.GetLoggedUser(Request);

                var loggedRole = context.Role.First(x => x.Id == loggedUser.RoleId);

                if (loggedRole.Name == RolesEnum.User.ToString())
                {
                    throw new WebException(Messages.Unauthorized);
                }

                var validationMessage = ValidateUserData(user);
                if (!string.IsNullOrEmpty(validationMessage))
                {
                    throw new WebException(validationMessage);
                }

                if (user.Id == 0)
                {
                    context.User.Add(user);
                }
                else
                {
                    context.Entry(user).State = EntityState.Modified;
                }
                context.SaveChanges();
                return user.Id;
            }
        }
Exemplo n.º 3
0
        public Role GetLoggedUserRole(HttpRequestMessage request)
        {
            var token = GetUserToken(request);

            using (var context = new TravelPlannerEntities())
            {
                var tokenUser = context.User.FirstOrDefault(x => x.Token == token);
                if (tokenUser == null)
                {
                    throw new UnauthorizedAccessException();
                }
                return tokenUser.Role;
            }
        }
Exemplo n.º 4
0
        public bool DeleteUser(int userId)
        {
            using (var context = new TravelPlannerEntities())
            {
                var user = GetUserIfAuthorized(userId, context);

                if (context.Trip.Any(x => x.UserId == userId))
                {
                    throw new WebException(Messages.UserWithTrips);
                }

                context.User.Remove(user);
                context.SaveChanges();
            }
            return true;
        }
Exemplo n.º 5
0
        // GET api/User/GetAllRoles
        public IEnumerable<Role> GetAllRoles()
        {
            var roles = new List<Role>();
            using (var context = new TravelPlannerEntities())
            {
                var userId = UserHelper.GetLoggedUser(Request).Id;
                var role = context.Role.FirstOrDefault(x => x.User.Any(y => y.Id == userId));

                if (role != null && (role.Name == RolesEnum.Manager.ToString() || role.Name == RolesEnum.Administrator.ToString()))
                {
                    roles = context.Role.ToList();
                }
            }
            return roles.Select(x => new Role
            {
                Id = x.Id,
                Name = x.Name
            }).Distinct();
        }
Exemplo n.º 6
0
        private User GetUserIfAuthorized(int userId, TravelPlannerEntities context)
        {
            var loggedUser = UserHelper.GetLoggedUser(Request);

            var role = context.Role.FirstOrDefault(x => x.Id == loggedUser.RoleId);

            if (role.Name == RolesEnum.User.ToString())
            {
                throw new WebException(Messages.Unauthorized);
            }

            var user = context.User.FirstOrDefault(x => x.Id == userId);

            if (user == null)
            {
                throw new WebException(Messages.UserNotFound);
            }
            return user;
        }
Exemplo n.º 7
0
        private TokenResponse CreateToken(User user, TravelPlannerEntities context)
        {
            var dateTime = DateTime.UtcNow;
            var time = BitConverter.GetBytes(dateTime.ToBinary());
            var key = Guid.NewGuid().ToByteArray();
            var token = Convert.ToBase64String(time.Concat(key).ToArray());

            user.Token = token;
            context.Entry(user).State = EntityState.Modified;
            context.SaveChanges();
            return new TokenResponse
            {
                Token = token,
                ExpirationDate = dateTime.AddHours(24).ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture),
                Role = user.Role.Name
            };
        }
Exemplo n.º 8
0
        public TokenResponse RegisterUser([FromUri]User user)
        {
            using (var context = new TravelPlannerEntities())
            {
                var validationMessage = ValidateUserData(user);
                if (!string.IsNullOrEmpty(validationMessage))
                {
                    throw new WebException(validationMessage);
                }

                if (context.User.Any(x => x.Username == user.Username))
                {
                    throw new WebException(Messages.DuplicatedUser);
                }

                var role = context.Role.FirstOrDefault(x => x.Id == user.RoleId);
                if (role == null)
                {
                    throw new WebException(Messages.RoleNotFound);
                }

                context.User.Add(user);
                context.SaveChanges();

                return CreateToken(user, context);
            }
        }
Exemplo n.º 9
0
 public bool Logout()
 {
     using (var context = new TravelPlannerEntities())
     {
         var loggedUserId = UserHelper.GetLoggedUser(Request).Id;
         context.User.First(x => x.Id == loggedUserId).Token = string.Empty;
         context.SaveChanges();
     }
     return true;
 }
Exemplo n.º 10
0
        public TokenResponse Login(string username, string password)
        {
            using (var context = new TravelPlannerEntities())
            {
                var user = context.User.FirstOrDefault(x => x.Username == username);
                if (user == null)
                {
                    throw new WebException(Messages.UserNotFound);
                }

                if (user.Password != password)
                {
                    throw new WebException(Messages.BadCredentials);
                }

                return CreateToken(user, context);
            }
        }
Exemplo n.º 11
0
 // GET api/User/GetUser
 public User GetUser(int userId)
 {
     using (var context = new TravelPlannerEntities())
     {
         var user = GetUserIfAuthorized(userId, context);
         return new User
         {
             Id = user.Id,
             Username = user.Username,
             RoleId = user.RoleId
         };
     }
 }
Exemplo n.º 12
0
        // GET api/User/GetAllUsers
        public IEnumerable<User> GetAllUsers()
        {
            var users = new List<User>();
            using (var context = new TravelPlannerEntities())
            {
                var userId = UserHelper.GetLoggedUser(Request).Id;
                var role = context.Role.FirstOrDefault(x => x.User.Any(y => y.Id == userId));

                if (role == null || role.Name == RolesEnum.User.ToString())
                {
                    throw new WebException(Messages.Unauthorized);
                }

                users = context.User.Where(x => x.Id != userId).ToList();
            }
            return users.Select(x => new User
            {
                Id = x.Id,
                Username = x.Username,
                RoleId = x.RoleId
            });
        }
Exemplo n.º 13
0
        internal User GetCreatedRegularUserTestUser()
        {
            if (RegularUserTestUser != null)
            {
                return RegularUserTestUser;
            }
            using (var context = new TravelPlannerEntities())
            {

                return context.User.First(x => x.Username == TestUserRegularUserName);
            }
        }
Exemplo n.º 14
0
        internal User GetCreatedAdministratorTestUser()
        {
            if (AdminTestUser != null)
            {
                return AdminTestUser;
            }
            using (var context = new TravelPlannerEntities())
            {

                return context.User.First(x => x.Username == TestUserAdmnistratorName);
            }
        }
Exemplo n.º 15
0
        public static void ClassSetup(TestContext context)
        {
            Mock<IUserHelper> UserHelper = new Mock<IUserHelper>(); ;
            UserHelper.Setup(x => x.GetLoggedUser(It.IsAny<HttpRequestMessage>())).Returns(GetInitialAdminUser());
            UserHelper.Setup(x => x.GetLoggedUserRole(It.IsAny<HttpRequestMessage>())).Returns(new Role { Id = 1, Name = "Administrator" });

            var userController = new UserController(UserHelper.Object);

            using (var entityContext = new TravelPlannerEntities())
            {
                if (!entityContext.User.Any(x => x.Username == TestUserAdmnistratorName))
                {
                    userController.CreateOrUpdateUser(GetAdministratorTestUser());
                }
                if (!entityContext.User.Any(x => x.Username == TestUserManagerName))
                {
                    userController.CreateOrUpdateUser(GetManagerTestUser());
                }
                if (!entityContext.User.Any(x => x.Username == TestUserRegularUserName))
                {
                    userController.CreateOrUpdateUser(GetRegularUserTestUser());
                }
            }
        }