Esempio n. 1
0
        // [Authorize(AppConst.AccessPolicies.Secret)]  /// Done
        public async Task <IActionResult> Post([FromBody] Role newRole)
        {
            try
            {
                int langId = AppFunc.GetLanguageId();
                /// if model validation failed
                if (!TryValidateModel(newRole))
                {
                    AppFunc.ExtractErrors(ModelState, ref ErrorsList);
                    /// return Unprocessable Entity with all the errors
                    return(UnprocessableEntity(ErrorsList));
                }



                /// check the database to see if a role with the same name exists
                if (await AppDbContext.Roles.Include(r => r.RoleTranslates).Select(p => new Role
                {
                    Name = p.RoleTranslates.FirstOrDefault(e => e.LangId == langId).Name,
                    AccessClaim = p.AccessClaim,
                    Id = p.Id
                }).AnyAsync(d => d.Name.Equals(newRole.Name) && d.AccessClaim.Equals(newRole.AccessClaim)).ConfigureAwait(false))
                {
                    /// extract the errors and return bad request containing the errors
                    AppFunc.Error(ref ErrorsList, _localizer["Role already exists."].Value);
                    return(StatusCode(412, ErrorsList));
                }
                foreach (string lang in AppConst.SupportLanguages)
                {
                    newRole.RoleTranslates.Add(new RoleTranslate()
                    {
                        LangId = AppFunc.GetLanguageId(lang), Name = newRole.Name
                    });
                }
                /// else role object is made without any errors
                /// Add the new role to the EF context
                await AppDbContext.Roles.AddAsync(newRole).ConfigureAwait(false);

                /// save the changes to the data base
                await AppDbContext.SaveChangesAsync().ConfigureAwait(false);

                /// return 201 created status with the new object
                /// and success message
                return(Created(_localizer["Success"].Value, newRole));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
                return(StatusCode(417, ErrorsList));
            }
        }
Esempio n. 2
0
        //[Authorize(AppConst.AccessPolicies.Secret)]  /// First Level Test Pass
        public async Task <IActionResult> Put([FromBody] User modifiedUser)
        {
            try
            {
                int langId = AppFunc.GetLanguageId();
                /// Try to validate the model
                TryValidateModel(modifiedUser);
                /// remove the passwordHash and confrimPassword since
                /// the password update gets handled by another method in this class
                ModelState.Remove("PasswordHash");
                if (!ModelState.IsValid)
                {
                    /// extract the errors and return bad request containing the errors
                    AppFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }
                /// if the user record with the same id is not found
                if (!AppDbContext.Users.Any(u => u.Id == modifiedUser.Id))
                {
                    AppFunc.Error(ref ErrorsList, _localizer["User not found."].Value);
                    return(StatusCode(412, ErrorsList));
                }
                /// find the current user details from the database
                User userDetails = AppDbContext.Users.Find(modifiedUser.Id);
                userDetails.UserTranslates = await AppDbContext.UserTranslate.AsTracking().Where(ut => ut.User.Id == userDetails.Id)
                                             .ToListAsync().ConfigureAwait(false);

                UserTranslate userTranslate = userDetails.UserTranslates.SingleOrDefault(ut => ut.LangId == langId);

                /// update the user details with the new details
                userTranslate.FirstName = modifiedUser.FirstName;
                userTranslate.Surname   = modifiedUser.Surname;
                userDetails.Email       = modifiedUser.Email;
                userDetails.PhoneNumber = modifiedUser.PhoneNumber;
                userDetails.Role        = modifiedUser.Role;
                /// thus update user in the context
                AppDbContext.Users.Update(userDetails);
                /// save the changes to the database
                await AppDbContext.SaveChangesAsync().ConfigureAwait(false);

                /// thus return 200 ok status with the updated object
                return(Ok(userDetails));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
                return(StatusCode(417, ErrorsList));
            }
        }
Esempio n. 3
0
        // [Authorize(AppConst.AccessPolicies.Secret)]  /// Done
        public async Task <IActionResult> Put([FromBody] Role modifiedRole)
        {
            try
            {
                int langId = AppFunc.GetLanguageId();
                /// if model validation failed
                if (!TryValidateModel(modifiedRole))
                {
                    AppFunc.ExtractErrors(ModelState, ref ErrorsList);
                    /// return Unprocessable Entity with all the errors
                    return(UnprocessableEntity(ErrorsList));
                }

                /// check the database to see if a Category with the same name exists
                if (await AppDbContext.Roles.Include(r => r.RoleTranslates).Select(p => new Role
                {
                    Name = p.RoleTranslates.FirstOrDefault(e => e.LangId == langId).Name,
                    AccessClaim = p.AccessClaim,
                    Id = p.Id
                }).AnyAsync(d => d.Name == modifiedRole.Name &&
                            d.AccessClaim.Equals(modifiedRole.AccessClaim) &&
                            d.Id != modifiedRole.Id).ConfigureAwait(false))
                {
                    /// extract the errors and return bad request containing the errors
                    AppFunc.Error(ref ErrorsList, _localizer["Role already exists."].Value);
                    return(StatusCode(412, ErrorsList));
                }
                modifiedRole.RoleTranslates = await AppDbContext.RolesTranslate
                                              .Where(rt => rt.Role.Id == modifiedRole.Id).ToListAsync().ConfigureAwait(false);

                modifiedRole.RoleTranslates.SingleOrDefault(rt => rt.LangId == langId).Name = modifiedRole.Name;
                /// else Role object is made without any errors
                /// Update the current Role on EF context
                AppDbContext.Roles.Update(modifiedRole);

                /// save the changes to the data base
                await AppDbContext.SaveChangesAsync().ConfigureAwait(false);

                /// return 200 OK (Update) status with the modified object
                /// and success message
                return(Ok(modifiedRole));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
                return(StatusCode(417, ErrorsList));
            }
        }
Esempio n. 4
0
        // [Authorize(AppConst.AccessPolicies.Secret)] /// Done
        public async Task <IActionResult> Get(
            int selectedPage,
            int maxItemsPerPage,
            string searchValue       = "",
            string filterAccessClaim = "",
            bool isSortAsce          = true,
            string sortName          = "Role.Name")
        {
            try
            {
                int langId = AppFunc.GetLanguageId();

                int totalCount = await AppDbContext.Roles.Where(r => filterAccessClaim.Equals(AppConst.GetAllRecords)?true : r.AccessClaim.Equals(filterAccessClaim))
                                 .Include(r => r.RoleTranslates).Select(p => new Role
                {
                    Name        = p.RoleTranslates.FirstOrDefault(e => e.LangId == langId).Name,
                    AccessClaim = p.AccessClaim,
                    Id          = p.Id
                })
                                 .CountAsync(r => searchValue.Equals(AppConst.GetAllRecords) ? true : (r.Name.Contains(searchValue)))
                                 .ConfigureAwait(false);

                List <Role> list = await AppDbContext.Roles
                                   .Where(r => filterAccessClaim.Equals(AppConst.GetAllRecords)?true : r.AccessClaim.Equals(filterAccessClaim)).Include(r => r.RoleTranslates).Select(p => new Role
                {
                    Name        = p.RoleTranslates.FirstOrDefault(e => e.LangId == langId).Name,
                    AccessClaim = p.AccessClaim,
                    Id          = p.Id
                })
                                   .Where(r => searchValue.Equals(AppConst.GetAllRecords) ? true : (r.Name.Contains(searchValue)))
                                   .OrderByDynamic(sortName, isSortAsce)
                                   .Skip((selectedPage - 1) * maxItemsPerPage)
                                   .Take(maxItemsPerPage)
                                   .ToListAsync()
                                   .ConfigureAwait(false);

                /// return the list of Roles
                return(Ok(new { list, totalCount }));
            }
            catch (Exception) //ArgumentNullException
            {
                /// in the case any exceptions return the following error
                AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
                return(StatusCode(417, ErrorsList));
            }
        }
Esempio n. 5
0
 // [Authorize(AppConst.AccessPolicies.Secret)] /// Done
 public async Task <IActionResult> Get()
 {
     try
     {
         int langId = AppFunc.GetLanguageId();
         /// return the list of All Roles
         return(Ok(await AppDbContext.Roles.Include(r => r.RoleTranslates).Select(p => new Role
         {
             Name = p.RoleTranslates.FirstOrDefault(e => e.LangId == langId).Name,
             AccessClaim = p.AccessClaim,
             Id = p.Id
         }).ToListAsync().ConfigureAwait(false)));
     }
     catch (Exception) //ArgumentNullException
     {
         /// in the case any exceptions return the following error
         AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
         return(StatusCode(417, ErrorsList));
     }
 }
Esempio n. 6
0
        //[Authorize(AppConst.AccessPolicies.Secret)] /// First Level Test Pass
        public async Task <IActionResult> Get(
            int selectedPage    = 1,
            int maxItemsPerPage = 5,
            string searchValue  = AppConst.GetAllRecords,
            string filterRole   = AppConst.GetAllRecords,
            bool isSortAsce     = true,
            string sortName     = "Name"
            )
        {
            try
            {
                //1.Check the search parameter and filters and return the appropriate user list
                //      a.If search value is empty or null then return the filtered users
                //          Note(Default value for parameters)
                //                    searchValue = null
                //ALL OTHER PARAMETERS = ***GET - ALL ***
                int.TryParse(filterRole, out int filterRoleId);
                int langId = AppFunc.GetLanguageId();

                int totalCount = await AppDbContext.Users.Include(r => r.UserTranslates).Include(u => u.Role).Select(u => new User
                {
                    Id          = u.Id,
                    FirstName   = u.UserTranslates.FirstOrDefault(e => e.LangId == langId).FirstName,
                    Surname     = u.UserTranslates.FirstOrDefault(e => e.LangId == langId).Surname,
                    Email       = u.Email,
                    UserName    = u.UserName,
                    PhoneNumber = u.PhoneNumber,
                    Role        = u.Role
                })
                                 .Where(u => filterRole.Equals(AppConst.GetAllRecords) ? true : u.Role.Id == filterRoleId)
                                 .CountAsync(u => searchValue.Equals(AppConst.GetAllRecords) ? true :
                                             u.FirstName.Contains(searchValue) ||
                                             u.Surname.Contains(searchValue) ||
                                             u.Email.Contains(searchValue) ||
                                             u.UserName.Contains(searchValue) ||
                                             u.PhoneNumber.Contains(searchValue)
                                             ).ConfigureAwait(false);

                List <User> list = await AppDbContext.Users.Include(r => r.UserTranslates).Include(u => u.Role).
                                   ThenInclude(r => r.RoleTranslates).Select(u => new User
                {
                    Id          = u.Id,
                    FirstName   = u.UserTranslates.FirstOrDefault(e => e.LangId == langId).FirstName,
                    Surname     = u.UserTranslates.FirstOrDefault(e => e.LangId == langId).Surname,
                    Email       = u.Email,
                    UserName    = u.UserName,
                    PhoneNumber = u.PhoneNumber,
                    Role        = new Role()
                    {
                        Id          = u.Role.Id,
                        AccessClaim = u.Role.AccessClaim,
                        Name        = u.Role.RoleTranslates.FirstOrDefault(e => e.LangId == langId).Name
                    }
                })
                                   .Where(u => filterRole.Equals(AppConst.GetAllRecords) ? true : u.Role.Id == filterRoleId)
                                   .Where(u => searchValue.Equals(AppConst.GetAllRecords) ? true :
                                          u.FirstName.Contains(searchValue) ||
                                          u.Surname.Contains(searchValue) ||
                                          u.Email.Contains(searchValue) ||
                                          u.UserName.Contains(searchValue) ||
                                          u.PhoneNumber.Contains(searchValue)
                                          )
                                   .OrderByDynamic(sortName, isSortAsce)
                                   .Skip((selectedPage - 1) * maxItemsPerPage)
                                   .Take(maxItemsPerPage)
                                   .ToListAsync()
                                   .ConfigureAwait(false);

                /// return the list of Role ordered by name
                return(Ok(new { list, totalCount }));
            }
            catch (Exception) //ArgumentNullException
            {
                /// in the case any exceptions return the following error
                AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
                return(StatusCode(417, ErrorsList));
            }
        }
Esempio n. 7
0
        /// <summary>
        ///     Create a new User
        /// </summary>
        private async Task <IActionResult> CreateUser(User newUser)
        {
            try
            {
                newUser.PasswordHash = newUser.TempPassword;
                newUser.TempPassword = string.Empty;
                ModelState.Clear();
                TryValidateModel(newUser);
                ModelState.Remove("Role.Name");
                /// if model validation failed
                if (!ModelState.IsValid)
                {
                    AppFunc.ExtractErrors(ModelState, ref ErrorsList);
                    /// return bad request with all the errors
                    return(UnprocessableEntity(ErrorsList));
                }
                /// check the database to see if a user with the same email exists
                if (AppDbContext.Users.AsNoTracking().Any(d => d.UserName == newUser.UserName))
                {
                    /// extract the errors and return bad request containing the errors
                    AppFunc.Error(ref ErrorsList, _localizer["UserName already exists."].Value, "UserName");
                    return(StatusCode(412, ErrorsList));
                }
                /// Create the new user
                IdentityResult newUserResult = await _UserManager.CreateAsync(newUser, newUser.PasswordHash)
                                               .ConfigureAwait(false);

                /// If result failed
                if (!newUserResult.Succeeded)
                {
                    /// Add the error below to the error list and return bad request
                    foreach (var error in newUserResult.Errors)
                    {
                        AppFunc.Error(ref ErrorsList, error.Description, error.Code);
                    }
                    return(StatusCode(417, ErrorsList));
                }
                /// else result is successful the try to add the access claim for the user
                IdentityResult addedClaimResult = await _UserManager.AddClaimAsync(
                    newUser,
                    new Claim(AppConst.AccessClaimType, newUser.Role.AccessClaim)
                    ).ConfigureAwait(false);

                /// if claim failed to be created
                if (!addedClaimResult.Succeeded)
                {
                    /// remove the user account and return appropriate error
                    AppDbContext.Users.Remove(newUser);
                    await AppDbContext.SaveChangesAsync().ConfigureAwait(false);

                    AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
                    return(StatusCode(417, ErrorsList));
                }
                foreach (string lang in AppConst.SupportLanguages)
                {
                    await AppDbContext.UserTranslate.AddAsync(new UserTranslate()
                    {
                        LangId    = AppFunc.GetLanguageId(lang),
                        User      = newUser,
                        FirstName = newUser.FirstName,
                        Surname   = newUser.Surname
                    });
                }
                /// save the changes to the data base
                await AppDbContext.SaveChangesAsync().ConfigureAwait(false);

                isUserCreated = true;
                /// return 201 created status with the new object
                /// and success message
                return(Created(_localizer["Success"].Value, newUser));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
                return(StatusCode(417, ErrorsList));
            }
        }