示例#1
0
        public async Task <IActionResult> Post(User newUser)
        {
            Console.WriteLine($"# # # UserController.Post newUser.Id={newUser.Id}");
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesAdmins);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            if (newUser.RoleId < 1)
            {
                newUser.RoleId = authRet.UserRole.Id;
            }
            if (newUser.RoleId != authRet.UserRole.Id && authRet.ApiUser.RoleId != authRet.AdminRole.Id)
            {
                return(BadRequest("Only Administrators can add users with Roles other than <User>"));
            }
            if (string.IsNullOrEmpty(newUser.Name))
            {
                return(BadRequest("User Name must be supplied"));
            }
            newUser.Id = 0;
            _context.Users.Add(newUser);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("Get", new User {
                Id = newUser.Id
            }, newUser));
        }
示例#2
0
        private async Task <IActionResult> _GetByFilterPaged(string filter = null, int?page = null, int?pageSize = null)
        {
            try
            {
                var ret     = (IEnumerable <Role>)null;
                var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesAdmins);

                if (authRet.ErrorMessage != null)
                {
                    return(BadRequest(authRet.ErrorMessage));
                }
                filter = ContextUtils.ConvertFilterToLinq(filter);

                if (page.HasValue)
                {
                    ret = string.IsNullOrEmpty(filter)
                        ? _context.Roles.ToPagedList(page.Value, pageSize ?? _defaultPageSize)
                        : _context.Roles.FromSqlRaw($"SELECT * FROM dbo.Role WHERE ({filter})").ToPagedList(page.Value, pageSize ?? _defaultPageSize);
                }
                else
                {
                    ret = string.IsNullOrEmpty(filter)
                        ? await _context.Roles.ToListAsync()
                        : await _context.Roles.FromSqlRaw($"SELECT * FROM dbo.Role WHERE ({filter})").ToListAsync();
                }

                return(Ok(ret));
            }
            catch (SqlException e)
            {
                var columns = typeof(Role).GetProperties().Select(p => p.Name);
                return(BadRequest("\nGetByFilter(filter) - Sql Exception: " + e.Message + "\n\n" + "Columns: " + String.Join(", ", columns)));
            }
        }
示例#3
0
        public async Task <IActionResult> GetById(int id)
        {
            try
            {
                var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesUsers);

                if (authRet.ErrorMessage != null)
                {
                    return(BadRequest(authRet.ErrorMessage));
                }
                var isAdmin = _authorizedRolesAdmins.Contains(authRet.ApiUserRole.Name);

                if (!isAdmin && id != authRet.ApiUser.Id)
                {
                    return(BadRequest("You are not authorized to view other users details"));
                }
                var ret = await _context.UserByIdAsync(id);

                if (ret == null)
                {
                    return(BadRequest($"Invalid User Identifier Id={id}"));
                }
                return(Ok(ret));
            }
            catch (SqlException e)
            {
                var columns = typeof(User).GetProperties().Select(p => p.Name);
                return(BadRequest("\nGet(id) - Sql Exception: " + e.Message + "\n\n" + "Columns: " + String.Join(", ", columns)));
            }
        }
示例#4
0
        private async Task <IActionResult> _InsertMeal(Meal newMeal)
        {
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesUsers);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            if (newMeal.Calories < 0)
            {
                newMeal.Calories = 0;
            }
            var erroMessage = await ValidateMealAsync(authRet.ApiUser, newMeal);

            if (erroMessage != null)
            {
                return(BadRequest(erroMessage));
            }
            var isAdmin = _authorizedRolesAdmins.Contains(authRet.ApiUserRole.Name);

            if (!isAdmin)
            {
                if (newMeal.UserId != authRet.ApiUser.Id)
                {
                    return(BadRequest($"Only User Managers and Administrators can add meals for other users. Please use your own UserId <authRet.ApiUser.Id>"));
                }
            }
            var newUser = newMeal.UserId == authRet.ApiUser.Id ? authRet.ApiUser : await _context.Users.FindAsync(newMeal.UserId);

            var newDailyUserCalories = await _context.DailyUserCalories.FirstOrDefaultAsync(duc => duc.UserId == newUser.Id && duc.Date.Date == newMeal.Date.Date);

            if (newDailyUserCalories == null)
            {
                newDailyUserCalories = new DailyUserCalories {
                    UserId = newUser.Id, Date = newMeal.Date.Date, Calories = newMeal.Calories
                };
                _context.DailyUserCalories.Add(newDailyUserCalories);
            }
            else
            {
                var origDailyUserCalories = newDailyUserCalories.Calories;

                newDailyUserCalories.Calories += newMeal.Calories;
                _context.Entry(newDailyUserCalories).State = EntityState.Modified; // Update database

                if (origDailyUserCalories < newUser.DailyCalories && newDailyUserCalories.Calories >= newUser.DailyCalories)
                {
                    await UpdateSameDayMealsWithinLimit(newMeal, withinLimit : false);
                }
            }
            newMeal.Id          = 0;
            newMeal.WithinLimit = newDailyUserCalories.Calories < newUser.DailyCalories;
            _context.Meals.Add(newMeal);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("Get", new Meal {
                Id = newMeal.Id
            }, newMeal));
        }
示例#5
0
        public async Task <IActionResult> PutIdMeal(int id, Meal meal)
        {
            Console.WriteLine($"# # # Put(id={id}, meal)");
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesUsers);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            return(await _UpdateIdMeal(authRet, id, meal));
        }
示例#6
0
        public async Task <IActionResult> GetRemaining()
        {
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesUsers);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            var userId = authRet.ApiUser.Id;
            var duc    = await _context.DailyUserCalories.FirstOrDefaultAsync(duc => duc.UserId == userId && duc.Date == DateTime.Now.Date);

            var ret = authRet.ApiUser.DailyCalories - (duc?.Calories ?? 0);

            return(Ok(ret > 0 ? ret : 0));
        }
示例#7
0
        public async Task <IActionResult> Delete(int id)
        {
            Console.WriteLine($"# # MealController.Delete(id={id})");
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesUsers);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            var oldMeal = _context.Meals.Find(id);

            if (oldMeal == null)
            {
                return(NotFound());
            }
            var isAdmin = _authorizedRolesAdmins.Contains(authRet.ApiUserRole.Name);

            if (!isAdmin)
            {
                if (oldMeal.UserId != authRet.ApiUser.Id)
                {
                    return(BadRequest($"Only User Managers and Administrators can delete other users deals"));
                }
            }
            var oldUser = oldMeal.UserId == authRet.ApiUser.Id ? authRet.ApiUser : await _context.UserByIdAsync(oldMeal.UserId);

            var oldDailyUserCalories = await _context.DailyUserCalories.FirstAsync(duc => duc.UserId == oldUser.Id && duc.Date.Date == oldMeal.Date.Date);

            var origOldDailyUserCalories = oldDailyUserCalories.Calories;

            oldDailyUserCalories.Calories -= oldMeal.Calories;
            _context.Entry(oldDailyUserCalories).State = EntityState.Modified; // Update database (locking DailyUserCalories table first)

            if (origOldDailyUserCalories >= oldUser.DailyCalories && oldDailyUserCalories.Calories < oldUser.DailyCalories)
            {
                await UpdateSameDayMealsWithinLimit(oldMeal, withinLimit : true); // Update other Deals on same day
            }
            oldMeal.WithinLimit = oldDailyUserCalories.Calories < oldUser.DailyCalories;
            _context.Meals.Remove(oldMeal);
            await _context.SaveChangesAsync();

            return(Ok(oldMeal));
        }
示例#8
0
        public async Task <IActionResult> Post(Role newRole)
        {
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesAdmins);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            if (string.IsNullOrEmpty(newRole.Name))
            {
                return(BadRequest("Role Name must be supplied"));
            }
            newRole.Id = 0;
            _context.Roles.Add(newRole);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("Post", new Role {
                Id = newRole.Id
            }, newRole));
        }
示例#9
0
        public async Task <IActionResult> PutIdCalories(int id, int calories)
        {
            Console.WriteLine($"# # # Put(id={id}, calories={calories})");
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesUsers);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            var existingMeal = _context.Meals.Find(id);

            if (existingMeal == null)
            {
                return(NotFound($"Id={id}"));
            }
            var newMeal = new Meal().AssignFrom(existingMeal);

            newMeal.Calories = calories;
            return(await _UpdateIdMeal(authRet, id, newMeal));
        }
示例#10
0
        public async Task <IActionResult> Delete(int id)
        {
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesAdmins);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            var oldUser = await _context.UserByIdAsync(id);

            if (oldUser == null)
            {
                return(NotFound());
            }
            if (_context.Meals.Any(u => u.UserId == id))
            {
                return(BadRequest($"Cannot delete User <{oldUser.Name}> with Id <{id}> until all their meals have been deleted"));
            }
            _context.Users.Remove(oldUser);
            await _context.SaveChangesAsync();

            return(Ok(oldUser));
        }
示例#11
0
        public async Task <IActionResult> Delete(int id)
        {
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesAdmins);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            var oldRole = await _context.RoleByIdAsync(id);

            if (oldRole == null)
            {
                return(NotFound());
            }
            if (_context.Users.Any(u => u.RoleId == id))
            {
                return(BadRequest($"Cannot delete Role with Id {id} - Some Users are still assigned this RoleId"));
            }
            _context.Roles.Remove(oldRole);
            await _context.SaveChangesAsync();

            return(Ok(oldRole));
        }
示例#12
0
        public async Task <IActionResult> Put(int id, Role newRole)
        {
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesAdmins);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            if (id != newRole.Id)
            {
                return(BadRequest($"Id={id} not equal to role.Id={newRole.Id}"));
            }
            var oldRole = await _context.RoleByIdAsync(id);

            if (oldRole == null)
            {
                return(NotFound());
            }
            oldRole.AssignFrom(newRole);
            _context.Entry(oldRole).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(NoContent());
        }
示例#13
0
        public async Task <IActionResult> DeleteAllByUserId(int userId)
        {
            Console.WriteLine($"# # MealController.DeleteAllByUserId(userId={userId})");
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesUsers);

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            var user = await _context.UserByIdAsync(userId);

            if (user == null)
            {
                return(BadRequest($"Unknown UserId <{userId}>"));
            }
            var isAdmin = _authorizedRolesAdmins.Contains(authRet.ApiUserRole.Name);

            if (!isAdmin)
            {
                if (userId != authRet.ApiUser.Id)
                {
                    return(BadRequest($"Only User Managers and Administrators can delete other users deals"));
                }
            }
            var userDucs = await _context.DailyUserCalories.Where(duc => duc.UserId == userId).ToListAsync();

            var userMeals = await _context.Meals.Where(m => m.UserId == userId).ToListAsync();

            var ret = userMeals.Count;

            _context.DailyUserCalories.RemoveRange(userDucs);
            _context.Meals.RemoveRange(userMeals);
            await _context.SaveChangesAsync();

            return(Ok($"Deleted {ret} meals for UserId {userId}"));
        }
示例#14
0
        private async Task <IActionResult> _GetByUserIdFilter(int?userId = null, string filter = null, int?page = null, int?pageSize = null)
        {
            try
            {
                var ret     = (IEnumerable <User>)null;
                var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesUsers);

                if (authRet.ErrorMessage != null)
                {
                    return(BadRequest(authRet.ErrorMessage));
                }
                var isAdmin = _authorizedRolesAdmins.Contains(authRet.ApiUserRole.Name);

                if (!isAdmin)
                {
                    if (userId.HasValue && userId.Value != authRet.ApiUser.Id)
                    {
                        return(BadRequest("You are not authorized to view other users details"));
                    }
                    userId = authRet.ApiUser.Id; // Only retrieve Users own meals
                }
                filter = ContextUtils.ConvertFilterToLinq(filter);

                if (userId.HasValue)
                {
                    if (page.HasValue)
                    {
                        ret = string.IsNullOrEmpty(filter)
                            ? _context.Users.Where(u => u.Id == userId).ToPagedList(page.Value, pageSize ?? _defaultPageSize)
                            : _context.Users.FromSqlRaw($"SELECT * FROM dbo.[User] WHERE Id = {userId} AND ({filter})").ToPagedList(page.Value, pageSize ?? _defaultPageSize);
                    }
                    else
                    {
                        ret = string.IsNullOrEmpty(filter)
                            ? await _context.Users.Where(u => u.Id == userId).ToListAsync()
                            : await _context.Users.FromSqlRaw($"SELECT * FROM dbo.[User] WHERE Id = {userId} AND ({filter})").ToListAsync();
                    }
                }
                else
                {
                    if (page.HasValue)
                    {
                        ret = string.IsNullOrEmpty(filter)
                            ? _context.Users.ToPagedList(page.Value, pageSize ?? _defaultPageSize)
                            : _context.Users.FromSqlRaw($"SELECT * FROM dbo.[User] WHERE ({filter})").ToPagedList(page.Value, pageSize ?? _defaultPageSize);
                    }
                    else
                    {
                        ret = string.IsNullOrEmpty(filter)
                            ? await _context.Users.ToListAsync()
                            : await _context.Users.FromSqlRaw($"SELECT * FROM dbo.[User] WHERE ({filter})").ToListAsync();
                    }
                }
                return(Ok(ret));
            }
            catch (SqlException e)
            {
                var columns = typeof(User).GetProperties().Select(p => p.Name);
                return(BadRequest("\nGetByFilter(filter) Sql Exception: " + e.Message + "\n\n" + "Columns: " + String.Join(", ", columns)));
            }
        }
示例#15
0
        public async Task <IActionResult> Put(int id, User newUser)
        {
            Console.WriteLine($"# # # UserController.Put id={id} newUser.Id={newUser.Id}");
            var authRet = await ControllerUtils.AuthorizeUserAsync(HttpContext, _context, _testUserName, _adminRoleName, _defaultRoleName, _authorizedRolesUsers);

            var allowModifyUserName = _configuration.GetValue <string>("UserController:AllowModifyUserName") == "true";

            if (authRet.ErrorMessage != null)
            {
                return(BadRequest(authRet.ErrorMessage));
            }
            var isAdmin = _authorizedRolesAdmins.Contains(authRet.ApiUserRole.Name);

            if (id != newUser.Id)
            {
                return(BadRequest($"Id={id} not equal to role.Id={newUser.Id}"));
            }
            var oldUser = await _context.UserByIdAsync(id);

            if (oldUser == null)
            {
                return(NotFound());
            }
            if (!isAdmin && id != authRet.ApiUser.Id)
            {
                return(BadRequest("You are not authorized to modify other users details"));
            }
            if (newUser.RoleId < 1)
            {
                newUser.RoleId = oldUser.RoleId;
            }
            if (newUser.RoleId != oldUser.RoleId && authRet.ApiUser.RoleId != authRet.AdminRole.Id)
            {
                return(BadRequest("Only Administrators can modify RoleId"));
            }
            if (newUser.Name == null || newUser.Name.Trim().Length < 1)
            {
                newUser.Name = oldUser.Name;
            }
            if (newUser.Name != oldUser.Name)
            {
                if (allowModifyUserName)
                {
                    if (_context.Users.FirstOrDefault(u => u.Name == newUser.Name) != null)
                    {
                        BadRequest($"UserName <{newUser.Name} Already taken, please choose another name");
                    }
                }
                else
                {
                    return(BadRequest("You cannot modify User Names"));
                }
            }
            if (newUser.DailyCalories > oldUser.DailyCalories)
            {
                var dailyUserCaloriesToUpdate = await _context.DailyUserCalories.Where(duc => duc.Calories >= oldUser.DailyCalories && duc.Calories < newUser.DailyCalories).ToListAsync();

                foreach (var duc in dailyUserCaloriesToUpdate)
                {
                    var sameDayMeals = await _context.Meals.Where(m => m.UserId == duc.UserId && m.Date.Date == duc.Date.Date).ToListAsync();

                    sameDayMeals.ForEach(m => m.WithinLimit = true); // Update meals for given day with broken limit
                    _context.Meals.UpdateRange(sameDayMeals);
                }
            }
            else if (newUser.DailyCalories < oldUser.DailyCalories)
            {
                var dailyUserCaloriesToUpdate = await _context.DailyUserCalories.Where(duc => duc.Calories >= newUser.DailyCalories && duc.Calories < oldUser.DailyCalories).ToListAsync();

                foreach (var duc in dailyUserCaloriesToUpdate)
                {
                    var sameDayMeals = await _context.Meals.Where(m => m.UserId == duc.UserId && m.Date.Date == duc.Date.Date).ToListAsync();

                    sameDayMeals.ForEach(m => m.WithinLimit = false); // Update meals for given day with broken limit
                    _context.Meals.UpdateRange(sameDayMeals);
                }
            }
            newUser.PasswordHash = oldUser.PasswordHash;
            newUser.PasswordSalt = oldUser.PasswordSalt;
            oldUser.AssignFrom(newUser);
            _context.Entry(oldUser).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(NoContent());
        }