Exemplo n.º 1
0
 public static RoleDTO MapToDTO(Role  model )
 {
     RoleDTO dto = new RoleDTO();
     dto.RoleId = model.RoleId;
     dto.RoleName = model.RoleName;
     return dto;
 }
Exemplo n.º 2
0
 public static Role MapFromDTO(RoleDTO dto)
 {
     Role Role = new Role();
     Role.RoleId = dto.RoleId;
     Role.RoleName = dto.RoleName;
     return Role;
 }
Exemplo n.º 3
0
        public JsonResult Update(RoleDTO dto)
        {
            var manager = this.GetManagerFor<IRoleManager>();
            var result = manager.Update(dto);
            var resultDTO = new RoleDTO(result);

            return Json(resultDTO);
        }
Exemplo n.º 4
0
        public JsonResult DeleteRole(RoleDTO dto)
        {
            var manager = this.GetManagerFor<IRoleManager>();
            var role = manager.Delete(dto.Id);
            var result = new RoleDTO(role);

            return Json(result);
        }
Exemplo n.º 5
0
        public void CreateRoleMethodTest()
        {
            RoleDTO role = new RoleDTO() { Name = "Genenal User" };

            response = this.InvokeOperation(targetOperationId, "RetrieveAll", null);
            List<UserDTO> users = response.Result.Value as List<UserDTO>;
            foreach(var user in users)
            {
                role.Users.Add(user);
            }
            response = this.InvokeOperation(targetOperationId, "Create", new object[] { role });
        }
Exemplo n.º 6
0
        public JsonResult Save(RoleDTO.SaveModel model)
        {
            if (!ModelState.IsValid)
                return ModelState.GetAajaFirstErrorMessage();

            if (rolePrivoder.Count(c => c.Name == model.Name) > 0)
            {
                ModelState.AddModelError("Name", "角色名称已存在");
                return ModelState.GetAajaFirstErrorMessage();
            }

            rolePrivoder.Add(model.Source);

            return Json(new AjaxResult() { Success = true, Message = "操作成功" });
        }
Exemplo n.º 7
0
        public JsonResult GetRole(int id, IEnumerable<string> query)
        {
            var queries = new Query[] { };

            if (query != null)
            {
                queries = query.Select(q => new Query { Name = q }).ToArray();
            }

            var manager = this.GetManagerFor<IRoleManager>();
            var result = manager.GetById(id);
            var resultDTO = new RoleDTO(queries, result);

            return Json(resultDTO);
        }
Exemplo n.º 8
0
        // PUT api/BusinessAPI/Business/{businessId}/Role/{roleId}
        public HttpResponseMessage PutBusinessRole(Guid businessId, Guid roleId, RoleDTO roleDTO)
        {
            //Ensure user has "Put" manager permissions for the business which the request corresponds to
            if (!ClaimsAuthorization.CheckAccess("Put", "BusinessId", businessId.ToString()))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have permissions."));
            }

            if (ModelState.IsValid)
            {
                var role = MapperFacade.MapperConfiguration.Map <RoleDTO, Role>(roleDTO, db.Roles.Single(r => r.Id == roleId));

                db.Entry(role).State = EntityState.Modified;
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Exemplo n.º 9
0
        private static void AutoMapperIdentity123()
        {
            Console.WriteLine("\nApplication Identity DTO -> Data -> DTO\n");

            {
                Console.WriteLine("Role");
                Role    data = new Role();
                RoleDTO dto  = DIHelper.Mapper.Map <RoleDTO>(data);
                data = DIHelper.Mapper.Map <Role>(dto);
            }

            {
                Console.WriteLine("UserClaim");
                UserClaim    data = new UserClaim();
                UserClaimDTO dto  = DIHelper.Mapper.Map <UserClaimDTO>(data);
                data = DIHelper.Mapper.Map <UserClaim>(dto);
            }

            {
                Console.WriteLine("UserLogim");
                UserLogin    data = new UserLogin();
                UserLoginDTO dto  = DIHelper.Mapper.Map <UserLoginDTO>(data);
                data = DIHelper.Mapper.Map <UserLogin>(dto);
            }

            {
                Console.WriteLine("UserRole");
                UserRole    data = new UserRole();
                UserRoleDTO dto  = DIHelper.Mapper.Map <UserRoleDTO>(data);
                data = DIHelper.Mapper.Map <UserRole>(dto);
            }

            {
                Console.WriteLine("User");
                User    data = new User();
                UserDTO dto  = DIHelper.Mapper.Map <UserDTO>(data);
                data = DIHelper.Mapper.Map <User>(dto);
            }
        }
Exemplo n.º 10
0
        public RoleDTO GetRoleByName(string roleName)
        {
            if (string.IsNullOrWhiteSpace(roleName))
            {
                return(null);
            }

            var roleDTO = new RoleDTO();

            try
            {
                var role = _userRepository.GetRoleAsync(roleName).Result;
                roleDTO = _mapper.Map <Role, RoleDTO>(role);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ErrorMessageConstants.GetErrorMessage);
                return(null);
            }

            return(roleDTO);
        }
        public static DTOStatus UpdateRole(int id, RoleDTO RoleDTO, string ConnectionString)
        {
            // Status to return
            DTOStatus objDTOStatus = new DTOStatus();

            objDTOStatus.Success = true;

            var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();

            optionsBuilder.UseSqlServer(ConnectionString);

            using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
            {
                var existingRole = context.AdefHelpDeskRoles.SingleOrDefaultAsync(x => x.Id == id).Result;
                if (existingRole == null)
                {
                    objDTOStatus.StatusMessage = $"id #{id} Not Found";
                    objDTOStatus.Success       = false;
                    return(objDTOStatus);
                }

                // Update the Role
                existingRole.RoleName             = RoleDTO.roleName;
                context.Entry(existingRole).State = EntityState.Modified;

                try
                {
                    context.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    objDTOStatus.StatusMessage = ex.GetBaseException().Message;
                    objDTOStatus.Success       = false;
                }
            }

            return(objDTOStatus);
        }
Exemplo n.º 12
0
        public async Task <IActionResult> PutRole(string id, RoleDTO roleDTO)
        {
            if (id != roleDTO.Id)
            {
                return(BadRequest());
            }

            var role = await _roleManager.FindByIdAsync(id);

            if (role == null)
            {
                return(NotFound());
            }

            role.Name = roleDTO.Name;

            var result = await _roleManager.UpdateAsync(role);

            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }

                if (ModelState.IsValid)
                {
                    return(BadRequest());
                }

                return(BadRequest(ModelState));
            }

            return(Ok());
        }
Exemplo n.º 13
0
        // POST api/BusinessAPI/Business/{businessId}/Role/{roleId}
        public HttpResponseMessage PostBusinessRole(Guid businessId, Guid roleId, RoleDTO roleDTO)
        {
            //Ensure user has "Put" manager permissions for the business which the request corresponds to
            if (!ClaimsAuthorization.CheckAccess("Put", "BusinessId", businessId.ToString()))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have permissions."));
            }

            if (String.IsNullOrEmpty(roleDTO.Name))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Conflict, "Role name cannot be empty"));
            }

            if (db.Roles.Where(r => r.Name == roleDTO.Name && r.Business.Id == businessId).Count() > 0)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Conflict, "Role already exists"));
            }

            if (ModelState.IsValid)
            {
                var role = MapperFacade.MapperConfiguration.Map <RoleDTO, Role>(roleDTO);
                role.Id = Guid.NewGuid(); //Assign new ID on save.

                //Lookup Business and attach, so that no updates or inserts are performed on BusinessType lookup table
                role.Business = db.Businesses.Find(businessId);

                db.Roles.Add(role);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
                response.Headers.Location = new Uri(Url.Link("BusinessRole", new { businessId = businessId, roleId = role.Id }));
                return(response);
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Exemplo n.º 14
0
        public List <RoleDTO> GetAll()
        {
            List <RoleDTO> roleDTOs = new List <RoleDTO>();

            SqlCommand     cmd     = new SqlCommand("SELECT * FROM Administration.TblRole", DbConnector.Connect());
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet        dataSet = new DataSet();

            adapter.Fill(dataSet);

            DataTable dt = dataSet.Tables[0];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                RoleDTO roleDTO = new RoleDTO()
                {
                    Id        = Convert.ToInt32(dt.Rows[i]["Id"]),
                    Code      = Convert.ToString(dt.Rows[i]["Code"]),
                    Name      = Convert.ToString(dt.Rows[i]["Name"]),
                    CreatedOn = Convert.ToDateTime(dt.Rows[i]["CreatedOn"]),
                    CreatedBy = Convert.ToInt32(dt.Rows[i]["CreatedBy"]),
                    Active    = Convert.ToBoolean(dt.Rows[i]["Active"])
                };

                if (dt.Rows[i]["ModifiedOn"] != DBNull.Value)
                {
                    roleDTO.ModifiedOn = Convert.ToDateTime(dt.Rows[i]["ModifiedOn"]);
                }
                if (dt.Rows[i]["ModifiedBy"] != DBNull.Value)
                {
                    roleDTO.ModifiedBy = Convert.ToInt32(dt.Rows[i]["ModifiedBy"]);
                }

                roleDTOs.Add(roleDTO);
            }

            return(roleDTOs);
        }
        // "R - READ" of CRUD
        public List <RoleDTO> GetRoles()
        {
            List <RoleDTO> _list = new List <RoleDTO>();

            using (SqlConnection con = new SqlConnection(_conn))
            {
                using (SqlCommand _sqlCommand = new SqlCommand("uspGetRole", con))
                {
                    _sqlCommand.CommandType    = CommandType.StoredProcedure;
                    _sqlCommand.CommandTimeout = 10;
                    //_sqlCommand.Parameters.AddWithValue("@BookID", inOneParticularBook);

                    con.Open();
                    RoleDTO _role;
                    using (SqlDataReader reader = _sqlCommand.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            _role = new RoleDTO
                            {
                                RoleID           = reader.GetInt32(reader.GetOrdinal("RoleID")),
                                RoleName         = (string)reader["RoleName"],
                                Comment          = reader["Comment"] is DBNull ? "" : (string)reader["Comment"],
                                DateModified     = reader.GetDateTime(reader.GetOrdinal("DateModified")),
                                ModifiedByUserId = reader.GetInt32(reader.GetOrdinal("ModifiedByUserID"))
                                              //Price = reader.GetDecimal(reader.GetOrdinal("Book_Price")),
                                              //IsPaperback = (string)reader["Book_IsPaperBack"],
                                              //Author_FK = reader.GetInt32(reader.GetOrdinal("Book_AuthorID_FK")),
                                              //Genre_FK = reader.GetInt32(reader.GetOrdinal("GenreID_FK"))
                            };
                            _list.Add(_role); // add current object to the list object
                        }
                    }
                    con.Close();
                }
            }
            return(_list);
        }
Exemplo n.º 16
0
        public ActionResult RoleCreate(RoleDTO roleDTO, Guid?businessLocationId)
        {
            roleDTO.Enabled = true;

            if (ModelState.IsValid)
            {
                using (HttpClientWrapper httpClient = new HttpClientWrapper(Session))
                {
                    var responseMessage = httpClient.PostAsJsonAsync("api/BusinessAPI/Business/" + roleDTO.BusinessId.ToString() + "/Role/" + Guid.Empty.ToString(), roleDTO).Result;
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        //Invalidate dependant cache item
                        CacheManager.Instance.Remove(CacheManager.CACHE_KEY_BUSINESS + roleDTO.BusinessId.ToString());
                        if (businessLocationId.HasValue)
                        {
                            return(RedirectToAction("RoleIndex", new { businessid = roleDTO.BusinessId, businessLocationId = businessLocationId.Value }));
                        }
                        else
                        {
                            return(RedirectToAction("RoleIndex", new { businessid = roleDTO.BusinessId }));
                        }
                    }
                    else
                    {
                        //If and error occurred add details to model error.
                        var error = JsonConvert.DeserializeObject <System.Web.Http.HttpError>(responseMessage.Content.ReadAsStringAsync().Result);
                        ModelState.AddModelError(String.Empty, error.Message);
                    }
                }
            }


            ViewBag.IsNew = false;

            ViewBag.BusinessId = roleDTO.BusinessId;

            return(PartialView());
        }
Exemplo n.º 17
0
        public override bool IsUserInRole(string email, string roleName)
        {
            bool result = false;

            try
            {
                PersonDTO person = _authenticationRepository.GetPersonByEmail(email);
                if (person != null)
                {
                    RoleDTO PersonRole = _authenticationRepository.GetRoleById(person.Id);
                    if (PersonRole != null && PersonRole.Name == roleName)
                    {
                        result = true;
                    }
                }
            }
            catch
            {
                result = false;
            }

            return(result);
        }
        public ActionResult EditRole(Guid groupId, RoleDTO role)
        {
            return(HttpHandleExtensions.AjaxCallGetResult(() =>
            {
                role.RoleGroupId = groupId;
                if (role.Id == Guid.Empty)
                {
                    _roleService.Add(role);
                    this.JsMessage = MessagesResources.Add_Success;
                }
                else
                {
                    _roleService.Update(role);
                    this.JsMessage = MessagesResources.Update_Success;
                }

                return Json(new AjaxResponse
                {
                    Succeeded = true,
                    RedirectUrl = Url.Action("RoleList", new { groupId = groupId })
                });
            }));
        }
        public void TestDtoToUser()
        {
            RoleDTO roleDTO = new RoleDTO()
            {
                Id = 1, RoleName = "FakeName", Version = 0
            };
            UserDTO dto = new UserDTO()
            {
                Id = 1, UserName = "******", Password = "******", Version = 1
            };

            dto.Roles.Add(roleDTO);
            Assert.AreEqual(true, dto.IsValid);
            Assert.AreEqual(true, roleDTO.IsValid);

            User user = SecurityAdapter.DtoToUser(dto);

            Assert.AreEqual <int>(dto.Id, user.UserId);
            Assert.AreEqual <string>(dto.UserName, user.UserName);
            Assert.AreEqual <string>(dto.Password, user.Password);
            Assert.AreEqual(dto.Version, user.Version);
            Assert.AreEqual(true, user.IsValid);
        }
Exemplo n.º 20
0
        public Task RemoveFromRoleAsync(CustomIdentityUser user, string roleName)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (String.IsNullOrEmpty(roleName))
            {
                throw new ArgumentNullException("roleName");
            }

            RoleDTO roleDTO      = this.roleService.GetRoleByTitle(roleName);
            bool    userIsInRole = user.Roles.Any(role => role.Id == roleDTO.Id);

            if (roleDTO != null && userIsInRole)
            {
                user.Roles.Remove(roleDTO);
                this.userService.Update(user);
            }

            return(Task.FromResult <object>(null));
        }
Exemplo n.º 21
0
        public async Task <IHttpActionResult> PutUserMaster(Guid id, RoleDTO dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != dto.Id)
            {
                return(BadRequest());
            }

            int EntityStateId = (int)EntityState.Modified;

            Guid result = await _roleService.SaveStatus(dto, id, EntityStateId);

            if (result == Guid.Empty)
            {
                return(NotFound());
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 22
0
        //----------------------------------------- Gets -----------------------------------------
        public static List <RoleDTO> getRoles()
        {
            List <RoleDTO> roles = new List <RoleDTO>();

            using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connectionRRHHDatabase"].ConnectionString))
            {
                SqlCommand command = new SqlCommand("usp_get_roles", connection);
                command.CommandType = CommandType.StoredProcedure;

                command.Connection.Open();
                SqlDataReader rdr = command.ExecuteReader();
                while (rdr.Read())
                {
                    RoleDTO rollDTO = new RoleDTO();
                    rollDTO.id_role     = rdr["id_role"].ToString();
                    rollDTO.name        = rdr["name"].ToString();
                    rollDTO.description = rdr["description"].ToString();
                    rollDTO.permissions = rdr["permissions"].ToString();
                    roles.Add(rollDTO);
                }
            };
            return(roles);
        }
Exemplo n.º 23
0
        public SaveResult <RoleEntryModel> Save(RoleDTO roleDTO, DateTime dateStamp)
        {
            ModelValidationResult validationResult = roleValidator.Validate(roleDTO);
            bool           success = false;
            RoleEntryModel model   = null;

            if (validationResult.IsValid)
            {
                tblM_Role role = Insert(roleDTO, dateStamp);
                Db.SaveChanges();

                success = true;
                model   = roleEntryDataProvider.Get(role.Role_PK);
            }

            return(new SaveResult <RoleEntryModel>
            {
                Success = success,
                Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.",
                Model = model,
                ValidationResult = validationResult
            });
        }
Exemplo n.º 24
0
        public bool SuaRole(string Id, string Ten, string SPhong, string IPhong, string UPhong, string DPhong, string UTen, string ITen, string UGia, string IGia)
        {
            RoleDTO role = new RoleDTO();

            try
            {
                role.Id     = Id;
                role.Ten    = Ten;
                role.SPhong = SPhong;
                role.IPhong = IPhong;
                role.UPhong = UPhong;
                role.DPhong = DPhong;
                role.UTen   = UTen;
                role.ITen   = ITen;
                role.UGia   = UGia;
                role.IGia   = IGia;
            }
            catch (Exception)
            {
                return(false);
            }
            return(RoleDAO.Instance.SuaRole(role));
        }
Exemplo n.º 25
0
        public async Task <GetRolesResponse> Handle(GetRolesRequest request, CancellationToken cancellationToken)
        {
            try
            {
                var records = await _context.Roles
                              .AsNoTracking()
                              .ToListAsync(cancellationToken);

                List <RoleDTO> listOfDTO = new List <RoleDTO>();

                if (records.Count > 0)
                {
                    foreach (var record in records)
                    {
                        var data = new RoleDTO
                        {
                            RoleID = record.RoleID,
                            Name   = record.Name
                        };

                        if (data != null)
                        {
                            listOfDTO.Add(data);
                        }
                    }
                }

                return(new GetRolesResponse
                {
                    Data = listOfDTO
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 26
0
 public async Task <IActionResult> Update(int id, RoleDTO roleDTO)
 {
     if (roleDTO.RoleId != id)
     {
         return(BadRequest());
     }
     try
     {
         var role = _mapper.Map <RoleDTO, Role>(roleDTO);
         await _unitOfWork.Roles.Update(id, role);
     }
     catch (DbUpdateConcurrencyException)
     {
         if (!await RoleExists(id))
         {
             return(NotFound());
         }
         else
         {
             throw;
         }
     }
     return(NoContent());
 }
Exemplo n.º 27
0
        public static List <RoleDTO> getUserRoles(string pUser)
        {
            List <RoleDTO> roleDTOList = new List <RoleDTO>();

            using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connectionRRHHDatabase"].ConnectionString))
            {
                SqlCommand command = new SqlCommand("usp_get_userRoles", connection);
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.Parameters.Add("@user_id", SqlDbType.Int);
                command.Parameters["@user_id"].Value = pUser;
                command.Connection.Open();
                SqlDataReader rdr = command.ExecuteReader();
                while (rdr.Read())
                {
                    RoleDTO roleDTO = new RoleDTO();
                    roleDTO.id_role     = rdr["id_role"].ToString();
                    roleDTO.name        = rdr["name"].ToString();
                    roleDTO.description = rdr["description"].ToString();
                    roleDTO.user_id     = rdr["user_id"].ToString();
                    roleDTOList.Add(roleDTO);
                }
            };
            return(roleDTOList);
        }
Exemplo n.º 28
0
        public async Task <ActionResult <RoleDTO> > PostRole(RoleDTO roleDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var role = new IdentityRole()
            {
                Name = roleDTO.Name
            };

            IdentityResult result = await _roleManager.CreateAsync(role);

            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }

                if (ModelState.IsValid)
                {
                    return(BadRequest());
                }

                return(BadRequest(ModelState));
            }

            var roles = RoleToRoleDTO(role);

            return(CreatedAtAction("GetRoles", new { id = role.Id }, roles));
        }
Exemplo n.º 29
0
        public async Task <IActionResult> CreateRole(RoleDTO roleDTO)
        {
            if (!await RoleExists(roleDTO.Name))
            {
                IdentityRole identityRole = new IdentityRole
                {
                    Name = roleDTO.Name
                };

                IdentityResult result = await _roleManager.CreateAsync(identityRole);

                if (result.Succeeded)
                {
                    return(CreatedAtAction("GetRole", new { id = identityRole.Id }, roleDTO));
                }
                foreach (IdentityError error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }

            ModelState.AddModelError(string.Empty, "Role ja existent");
            return(BadRequest(ModelState));
        }
Exemplo n.º 30
0
        public async Task <IActionResult> EditRole(int accountId, [FromBody] RoleDTO role)
        {
            try
            {
                var accountFromDb = await _repo.GetAccountDetail(accountId);

                if (accountFromDb == null)
                {
                    return(NotFound());
                }
                if (accountFromDb.Roles.Any(r => r.Role.Name == role.RoleName))
                {
                    var removeResult = await _userManager.RemoveFromRoleAsync(accountFromDb, role.RoleName);

                    if (removeResult.Succeeded)
                    {
                        return(Ok());
                    }
                }
                else
                {
                    var result = await _userManager.AddToRoleAsync(accountFromDb, role.RoleName);

                    if (result.Succeeded)
                    {
                        return(Ok());
                    }
                }

                return(NoContent());
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 31
0
        public ActionResult AddRole(RoleDTO paramRoleDTO)
        {
            GetCurrentUserInViewBag();
            try
            {
                if (paramRoleDTO == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }

                var RoleName = paramRoleDTO.RoleName.Trim();

                if (RoleName == "")
                {
                    throw new Exception("No RoleName");
                }

                // Create Role
                var roleManager =
                    new RoleManager <IdentityRole>(
                        new RoleStore <IdentityRole>(new ApplicationDbContext())
                        );

                if (!roleManager.RoleExists(RoleName))
                {
                    roleManager.Create(new IdentityRole(RoleName));
                }

                return(Redirect("~/Admin/ViewAllRoles"));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                return(View("AddRole"));
            }
        }
Exemplo n.º 32
0
        public ActionResult RoleEdit(RoleDTO roleDTO, Guid?businessLocationId)
        {
            if (ModelState.IsValid)
            {
                //Replace with updated role
                using (HttpClientWrapper httpClient = new HttpClientWrapper(Session))
                {
                    var responseMessage = httpClient.PutAsJsonAsync("api/BusinessAPI/Business/" + roleDTO.BusinessId.ToString() + "/Role/" + roleDTO.Id.ToString(), roleDTO).Result;
                    responseMessage.EnsureSuccessStatusCode();

                    //Invalidate dependant cache item
                    CacheManager.Instance.Remove(CacheManager.CACHE_KEY_BUSINESS + roleDTO.BusinessId.ToString());
                    if (businessLocationId.HasValue)
                    {
                        return(RedirectToAction("RoleIndex", new { businessid = roleDTO.BusinessId, businessLocationId = businessLocationId.Value }));
                    }
                    else
                    {
                        return(RedirectToAction("RoleIndex", new { businessid = roleDTO.BusinessId }));
                    }
                }
            }
            return(PartialView(roleDTO));
        }
Exemplo n.º 33
0
        public RoleDTO Add(RoleDTO roleDTO)
        {
            var role = roleDTO.ToModel();

            role.Id      = IdentityGenerator.NewSequentialGuid();
            role.Created = DateTime.UtcNow;

            if (role.Name.IsNullOrBlank())
            {
                throw new DataExistsException(UserSystemResource.Common_Name_Empty);
            }

            if (_Repository.Exists(role))
            {
                throw new DataExistsException(UserSystemResource.Role_Exists);
            }

            _Repository.Add(role);

            //commit the unit of work
            _Repository.UnitOfWork.Commit();

            return(role.ToDto());
        }
Exemplo n.º 34
0
        public async Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
        {
            UserDTO user = filterContext.HttpContext.GetCurrentUser();

            if (user == null)
            {
                if (filterContext.Controller is Controller controller)
                {
                    controller.TempData["login_error"] = "You are not authenticated.";
                }

                filterContext.Result = new RedirectToActionResult("Index", "Login", new { @area = "" });
                return;
            }

            RoleDTO role = user.Role;

            if (role != null)
            {
                if ((_superuser && role.RoleName == "Super User") ||
                    (_admin && role.RoleName == "Admin") ||
                    (_user && role.RoleName == "User"))
                {
                    await next();

                    return;
                }
            }


            if (filterContext.Controller is Controller c1)
            {
                c1.TempData["login_error"] = "You are not authorized.";
            }
            filterContext.Result = new RedirectToActionResult("Index", "Login", new { @area = "" });
        }
        public ActionResult Delete(RoleDTO role)
        {
            MethodBase method = MethodBase.GetCurrentMethod();

            try
            {
                if (role.Id > 0)
                {
                    Role delRole = Mapper.Map <Role>(role);
                    RoleRepo.Delete(delRole);
                    CreateLog(Enums.Success, GetMethodCode(method), LogLevel.Information);
                    return(Ok(true));
                }
                else
                {
                    CreateLog(Enums.BadRequest, GetMethodCode(method), LogLevel.Information);
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                return(HandleError(ex.Message, GetMethodCode(method)));
            }
        }
Exemplo n.º 36
0
        public async Task <string> CreateRole(RoleDTO roleDTO)
        {
            var role = _mapper.Map <RoleDTO, Role>(roleDTO);

            RoleValidator validator = new RoleValidator();

            ValidationResult results = validator.Validate(role);

            if (!results.IsValid)
            {
                foreach (var failure in results.Errors)
                {
                    string error = ("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
                    return(error);
                }
                return("Error");
            }
            else
            {
                await _eFUnitOfWork.RoleManager.CreateAsync(role);

                return("Роль успішно добавлено!");
            }
        }
Exemplo n.º 37
0
        public HttpResponseMessage Search(string q, string role, [FromUri] int pageSize, [FromUri] int pageNumber)
        {
            if (q == null)
            {
                q = "";
            }
            RoleDTO criteria = roleService.GetByName(role);

            string[] lines          = q.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            int?     searchParametr = null;

            if (role == "blocked")
            {
                searchParametr = -1;
            }
            if (lines.Length > 2)
            {
                lines = lines.Take(2).ToArray();
            }
            PagedListDTO <UserDTO> users = criteria != null?userService.Search(lines, pageSize, pageNumber, criteria.Id) :
                                               userService.Search(lines, pageSize, pageNumber, searchParametr);

            return(Request.CreateResponse <PagedListDTO <UserDTO> >(HttpStatusCode.OK, users));
        }
        public HttpResponseMessage LeaveGroup(RoleDTO postData)
        {
            var success = false;

            try
            {
                if (UserInfo.UserID >= 0 && postData.RoleId > 0)
                {
                    var roleController = new RoleController();
                    _roleInfo = roleController.GetRole(postData.RoleId, PortalSettings.PortalId);

                    if (_roleInfo != null)
                    {
                        if (UserInfo.IsInRole(_roleInfo.RoleName))
                        {
                            RoleController.DeleteUserRole(UserInfo, _roleInfo, PortalSettings, false);
                        }
                        success = true;
                    }
                }
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
            }

            if(success)
            {
                return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"});
            }
            
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error");
        }
        public HttpResponseMessage JoinGroup(RoleDTO postData)
        {
            try
            {
                if (UserInfo.UserID >= 0 && postData.RoleId > 0)
                {
                    var roleController = new RoleController();
                    _roleInfo = roleController.GetRole(postData.RoleId, PortalSettings.PortalId);
                    if (_roleInfo != null)
                    {

                        var requireApproval = false;

                        if(_roleInfo.Settings.ContainsKey("ReviewMembers"))
                            requireApproval = Convert.ToBoolean(_roleInfo.Settings["ReviewMembers"]);


                        if ((_roleInfo.IsPublic || UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) && !requireApproval)
                        {
                            roleController.AddUserRole(PortalSettings.PortalId, UserInfo.UserID, _roleInfo.RoleID, Null.NullDate);
                            roleController.UpdateRole(_roleInfo);

                            var url = Globals.NavigateURL(postData.GroupViewTabId, "", new[] { "groupid=" + _roleInfo.RoleID });
                            return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", URL = url });
                        
                        }
                        if (_roleInfo.IsPublic && requireApproval)
                        {
                            roleController.AddUserRole(PortalSettings.PortalId, UserInfo.UserID, _roleInfo.RoleID, RoleStatus.Pending, false, Null.NullDate, Null.NullDate);
                            var notifications = new Notifications();
                            notifications.AddGroupOwnerNotification(Constants.MemberPendingNotification, _tabId, _moduleId, _roleInfo, UserInfo);
                            return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", URL = string.Empty });
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
            }

            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error");
        }
Exemplo n.º 40
0
 public static RoleDTO CreateRoleDTO(int ID, global::System.DateTime createDate, bool isSystemRole, global::System.Collections.ObjectModel.ObservableCollection<RoleFunctionDTO> roleFunctions)
 {
     RoleDTO roleDTO = new RoleDTO();
     roleDTO.Id = ID;
     roleDTO.CreateDate = createDate;
     roleDTO.IsSystemRole = isSystemRole;
     if ((roleFunctions == null))
     {
         throw new global::System.ArgumentNullException("roleFunctions");
     }
     roleDTO.RoleFunctions = roleFunctions;
     return roleDTO;
 }
Exemplo n.º 41
0
 public void AddToRoles(RoleDTO roleDTO)
 {
     base.AddObject("Roles", roleDTO);
 }