Esempio n. 1
0
        public async Task <IActionResult> EditUsersInRole(string roleId)
        {
            ViewBag.roleId = roleId;
            var role = await roleManager.FindByIdAsync(roleId);

            if (role != null)
            {
                var model = new List <UserRoleVM>();

                foreach (var user in userManager.Users)
                {
                    var userRoleVm = new UserRoleVM
                    {
                        UserId   = user.Id,
                        UserName = user.UserName
                    };

                    if (await userManager.IsInRoleAsync(user, role.Name))
                    {
                        userRoleVm.IsSelected = true;
                    }
                    else
                    {
                        userRoleVm.IsSelected = false;
                    }

                    model.Add(userRoleVm);
                }
                return(View(model));
            }

            ViewBag.ErrorMessage = $"Role with Id:{roleId} cannot be found";
            return(View("NotFound"));
        }
Esempio n. 2
0
        public string GenerateToken(UserRoleVM userRoleVM)
        {
            string key         = "my_secret_key_12345";
            var    issuer      = "http://localhost:50693/";
            var    audience    = "http://localhost:52049/";
            var    securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var    credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var permClaims = new List <Claim>();

            permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            permClaims.Add(new Claim("Id", userRoleVM.Id));
            permClaims.Add(new Claim("Name", userRoleVM.Name));
            permClaims.Add(new Claim("Email", userRoleVM.Email));
            permClaims.Add(new Claim("Role", userRoleVM.Role));

            var token = new JwtSecurityToken(issuer,
                                             audience,
                                             permClaims,
                                             expires: DateTime.Now.AddYears(1),
                                             signingCredentials: credentials);
            var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);

            return(jwt_token);
        }
Esempio n. 3
0
        public ActionResult Get(UserRoleVM UserRoleVM)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://localhost:5001/");
                MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue("application/json");
                client.DefaultRequestHeaders.Accept.Add(contentType);
                string data        = JsonConvert.SerializeObject(UserRoleVM);
                var    contentData = new StringContent(data, Encoding.UTF8, "application/json");
                var    response    = client.PostAsync("/gateway/accounts/get", contentData).Result;
                if (response.IsSuccessStatusCode)
                {
                    char[] trimChars = { '/', '"' };
                    var    token     = response.Content.ReadAsStringAsync().Result.ToString();
                    var    handler   = new JwtSecurityTokenHandler().ReadJwtToken(token.Trim(trimChars)).Claims.FirstOrDefault(x => x.Type.Equals("Role_Name")).Value;

                    HttpContext.Session.SetString("Role: ", handler);
                    //var decodeToken = GetRole(response.Content.ReadAsStringAsync().Result.ToString());
                    //HttpContext.Session.SetString(SessionEmail, decodeToken);
                    return(Json(new { result = "Redirect", url = Url.Action("Privacy", "Home"), data = response.Content.ReadAsStringAsync().Result.ToString() }));
                }
                else
                {
                    return(Content("GAGAL"));
                }
            }
        }
Esempio n. 4
0
        public async Task <IActionResult> EditUsersInRole(string roleId)
        {
            var role = await _roleManager.FindByIdAsync(roleId);

            if (role == null)
            {
                ViewBag.ErrorMessage = $"The role with id {roleId} can not be found";
                return(View("_NotFound"));
            }

            UserRoleVM model = new UserRoleVM();

            model.RoleId   = role.Id;
            model.RoleName = role.Name;

            foreach (var user in _userManager.Users)
            {
                RoleUser userRole = new RoleUser
                {
                    UserId     = user.Id,
                    UserName   = user.UserName,
                    IsSelected = await _userManager.IsInRoleAsync(user, role.Name)
                };
                model.Users.Add(userRole);
            }

            return(View(model));
        }
        public async Task <string> Get(UserRoleVM userroleVM)
        {
            //var v = await _db.Users.Where(x => x.Email == userroleVM.User_Email).FirstOrDefaultAsync();
            var dbparams = new DynamicParameters();

            dbparams.Add("@User_Email", userroleVM.User_Email, DbType.String);
            var result = await Task.FromResult(_dapper.Get <UserRoleVM>("[dbo].[SP_Login]",
                                                                        dbparams, commandType: CommandType.StoredProcedure));

            if (BCrypt.Net.BCrypt.Verify(userroleVM.User_Password, result.User_Password))
            {
                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
                    new Claim("User_Email", result.User_Email),
                    new Claim("Role_Name", result.Role_Name)
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));

                var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);

                return(new JwtSecurityTokenHandler().WriteToken(token));
            }
            return("wrong");
        }
 public ActionResult User(int id)
 {
     UserRoleVM model = new UserRoleVM();
     model.Users = UserManager.GetByRole(id);
     model.Role = RoleManager.GetByID(id);
     return View(model);
 }
        public async Task <IActionResult> Manage(string userId)
        {
            ViewBag.userId = userId;
            var user = await userManager.FindByIdAsync(userId);

            if (user == null)
            {
                ViewBag.ErrorMessage = $"User with Id = {userId} cannot be found";
                return(View("NotFound"));
            }

            ViewBag.UserName = user.UserName;
            var model    = new List <UserRoleVM>();
            var roleList = roleManager.Roles.ToList();

            foreach (var role in roleList)
            {
                var userRolesVM = new UserRoleVM
                {
                    RoleId   = role.Id,
                    RoleName = role.Name
                };
                if (await userManager.IsInRoleAsync(user, role.Name))
                {
                    userRolesVM.Selected = true;
                }
                else
                {
                    userRolesVM.Selected = false;
                }
                model.Add(userRolesVM);
            }

            return(View(model));
        }
        public string UpdateUserRole(UserRoleVM userRole)
        {
            string userRoleId = string.Empty;

            SqlParameter[] parameters =
            {
                new SqlParameter {
                    ParameterName = "@Id", Value = userRole.Id
                },
                new SqlParameter {
                    ParameterName = "@Code", Value = userRole.Code
                },
                new SqlParameter {
                    ParameterName = "@Name", Value = userRole.Name
                },
                new SqlParameter {
                    ParameterName = "@Description", Value = userRole.Description
                },
                new SqlParameter {
                    ParameterName = "@IsActive", Value = userRole.IsActive
                },
                new SqlParameter {
                    ParameterName = "@UpdatedBy", Value = userRole.UpdatedBy
                }
            };

            userRoleId = Convert.ToString(DALHelper.ExecuteScalar("UpdateUserRole", parameters));

            return(userRoleId);
        }
        public async Task <IActionResult> GetUsersInRole(string roleId)
        {
            ViewBag.role = roleId;

            var role = await _roleManager.FindByIdAsync(roleId);

            if (role == null)
            {
                return(BadRequest($"Role with Id = {roleId} cannot be found"));
            }

            var model = new List <UserRoleVM>();

            foreach (var user in _userManager.Users)
            {
                var userRoleVM = new UserRoleVM
                {
                    UserId   = user.Id,
                    UserName = user.UserName
                };

                if (await _userManager.IsInRoleAsync(user, role.Name))
                {
                    userRoleVM.IsSelected = true;
                }
                else
                {
                    userRoleVM.IsSelected = false;
                }

                model.Add(userRoleVM);
            }

            return(Ok(model));
        }
Esempio n. 10
0
 public ActionResult ChangePassword(UserRoleVM userRoleVM)
 {
     using (HttpClient client = new HttpClient())
     {
         client.BaseAddress = new Uri("https://localhost:5001/");
         MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue("application/json");
         client.DefaultRequestHeaders.Accept.Add(contentType);
         var    token     = HttpContext.Session.GetString("token");
         char[] trimChars = { '/', '"' };
         client.DefaultRequestHeaders.Authorization =
             new AuthenticationHeaderValue("Bearer", token.Trim(trimChars));
         userRoleVM.User_Email = HttpContext.Session.GetString("email");
         string data        = JsonConvert.SerializeObject(userRoleVM);
         var    contentData = new StringContent(data, Encoding.UTF8, "application/json");
         var    response    = client.PutAsync("/gateway/accounts/", contentData).Result;
         if (response.IsSuccessStatusCode)
         {
             return(Json(new { result = "Redirect", url = Url.Action("Index", "Login"), statusCode = response.StatusCode }));
         }
         else
         {
             return(Content("GAGAL"));
         }
     }
 }
        public async Task <ActionResult> EditRoleUsers(string roleId)
        {
            ViewBag.roleId = roleId;

            var role = await _roleManager.FindByIdAsync(roleId);

            var model = new List <UserRoleVM>();

            foreach (var user in _userManager.Users)
            {
                var userRole = new UserRoleVM
                {
                    UserId   = user.Id,
                    UserName = user.UserName
                };
                if (await _userManager.IsInRoleAsync(user, role.Name))
                {
                    userRole.IsSelected = true;
                }
                else
                {
                    userRole.IsSelected = false;
                }
                model.Add(userRole);
            }
            return(View(model));
        }
Esempio n. 12
0
        public ActionResult AddUserToRole(UserRoleVM userRoleVM)
        {
            var userStore = new UserStore <IdentityUser>();
            UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore);

            if (ModelState.IsValid)
            {
                OneListCAEntities context = new OneListCAEntities();
                AspNetUser        user    = context.AspNetUsers
                                            .Where(u => u.Email == userRoleVM.Email).FirstOrDefault();
                if (userRoleVM.RoleName == "Administrator")
                {
                    manager.RemoveFromRole(user.Id, "User");
                    manager.AddToRole(user.Id, userRoleVM.RoleName);
                }
                else if (userRoleVM.RoleName == "User")
                {
                    manager.RemoveFromRole(user.Id, "Administrator");
                    manager.AddToRole(user.Id, userRoleVM.RoleName);
                }

                //user.AspNetRoles.Add(role);
                context.SaveChanges();
            }
            return(View());
        }
Esempio n. 13
0
        // GET: Token
        public string GetTokenCustomer(string id)
        {
            SqlParameter paramId = new SqlParameter("@Id", id);
            UserRoleVM   getById = db.Database.SqlQuery <UserRoleVM>("SP_AspNetUserRoles_TokenMapping @Id", paramId).Single();;

            string key      = "my_secret_key_12345";     //Secret key which will be used later during validation
            var    issuer   = "http://localhost:59950/"; //normally this will be your site URL
            var    audience = "http://localhost:59950/";

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            //Create a List of Claims, Keep claims name short
            var permClaims = new List <Claim>();

            permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            permClaims.Add(new Claim("id", getById.Id));
            permClaims.Add(new Claim("name", getById.Name));
            permClaims.Add(new Claim("email", getById.Email));
            permClaims.Add(new Claim("role", getById.Role));

            //Create Security Token object by giving required parameters
            var token = new JwtSecurityToken(issuer,   //Issuer
                                             audience, //Audience
                                             permClaims,
                                             expires: DateTime.Now.AddYears(1),
                                             signingCredentials: credentials);
            var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);

            return(jwt_token);
        }
Esempio n. 14
0
        public ActionResult Get(UserRoleVM user)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://localhost:44382");
                MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue("application/json");
                client.DefaultRequestHeaders.Accept.Add(contentType);
                string data        = JsonConvert.SerializeObject(user);
                var    contentData = new StringContent(data, Encoding.UTF8, "application/json");
                var    response    = client.PostAsync("/API/Accounts/Login", contentData).Result;
                if (response.IsSuccessStatusCode)
                {
                    char[] trimChars = { '/', '"' };

                    var jwt     = response.Content.ReadAsStringAsync().Result.ToString();
                    var handler = new JwtSecurityTokenHandler().ReadJwtToken(jwt.Trim(trimChars)).Claims.FirstOrDefault(x => x.Type.Equals("RoleName")).Value;

                    //return Json(new { result = "Redirect", url = Url.Action("Index", "Accounts"), data =jwt.ToString()});
                    return(Json(response.Content.ReadAsStringAsync().Result.ToString()));
                }
                else
                {
                    return(Content("GAGAL"));
                }
            }
        }
Esempio n. 15
0
        public async Task <IActionResult> AddUserInRole(UserRoleVM model, string role_id)
        {
            var role = await _roleManager.FindByIdAsync(role_id);

            if (role == null)
            {
                ViewBag.ErrorMessage = "Role not found!";
                return(View("Error", "Admin"));
            }

            var user = await _userManager.FindByNameAsync(model.username);

            if (user == null)
            {
                ViewBag.ErrorMessage = "User not found";
                return(View("Error", "Admin"));
            }

            if (await _userManager.IsInRoleAsync(user, role.Name))
            {
                ViewBag.ErrorMessage = "That user is already in role!";
                return(View("Error", "Admin"));
            }

            IdentityResult result = null;

            result = await _userManager.AddToRoleAsync(user, role.Name);

            return(RedirectToAction("EditRole", new { id = role_id }));
        }
Esempio n. 16
0
        public UserRoleVM EditingData(int id)
        {
            var Roleids = (from ra in db.UserRoleRelations
                           where ra.UserId == id
                           select ra.URoleId).ToArray();

            UserMaster um = db.UserMasters.Find(id);

            UserRoleVM userreg = new UserRoleVM();

            userreg.RoleId           = Roleids;
            userreg.UserId           = um.UserId;
            userreg.UserFName        = um.UserFName;
            userreg.UserLName        = um.UserLName;
            userreg.Gender           = um.Gender;
            userreg.EmailId          = um.EmailAddress;
            userreg.MobileNumber     = um.ContactNumber;
            userreg.PermanentAddress = um.PermnentAddress;
            userreg.CurrentAddress   = um.CurrentAddress;
            userreg.PWD          = um.Password;
            userreg.CreatedBy    = um.CreatedBy;
            userreg.CreatedDate  = um.CreatedDate;
            userreg.IsActive     = um.IsActive;
            userreg.ModifiedBy   = 1;
            userreg.ModifiedDate = DateTime.Now;
            return(userreg);
        }
Esempio n. 17
0
        public ActionResult Index(UserRoleVM form)
        {
            Page <Sys_Role> page = this._roleService.FindPage(form);

            this.SavePage(page, form);

            return(View());
        }
        public ActionResult User(int id)
        {
            UserRoleVM model = new UserRoleVM();

            model.Users = UserManager.GetByRole(id);
            model.Role  = RoleManager.GetByID(id);
            return(View(model));
        }
Esempio n. 19
0
        public int Insert(UserRoleVM form)
        {
            Sys_Role model = new Sys_Role();

            Ext.CopyFrom(model, form);
            model.UpdateDate = DateTime.Now;

            return(this._roleRepository.Insert(ContextDB.managerDBContext, model));
        }
Esempio n. 20
0
        public ActionResult RoleEdit(UserRoleVM form)
        {
            Sys_Role model = this._roleService.GetRole(form);

            ViewBag.form     = model;
            ViewData["type"] = "edit";

            return(View("RoleInsert"));
        }
        public UserRoleController()
        {
            string conString = Convert.ToString(ConfigurationManager.AppSettings["dbTransferDeskService"]);

            //ManuscriptContext
            this._UserRoleRepository        = new UserRoleRepository((new ManuscriptDBContext(conString)));
            _manuscriptDBRepositoryReadSide = new ManuscriptDBRepositoryReadSide(conString);
            userRoleVM = new UserRoleVM();
        }
Esempio n. 22
0
        public async Task <IActionResult> Create(UserRoleVM model, object Session)
        {
            var roles = _roleManager.Roles;

            if (model.RoleName != null)
            {
                await _roleManager.CreateAsync(new IdentityRole { Name = model.RoleName });
            }
            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 23
0
        public async Task <IHttpActionResult> GetUserRole(int id)
        {
            UserRoleVM userRole = userRoles.GetUserRole(id);

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

            return(Ok(userRole));
        }
        public ActionResult Create(UserRoleVM model)
        {
            try
            {
                string userRoleId = string.Empty;
                model.CreatedBy = LogInManager.LoggedInUserId;

                #region Check User Role Code Available.

                if (this.CheckUserRoleCodeAvailable(model.Id, model.Code) == false)
                {
                    return(Json(new
                    {
                        IsSuccess = false,
                        errorMessage = string.Format("Code : {0} already exist.", model.Code)
                    }, JsonRequestBehavior.AllowGet));
                }

                #endregion

                userRoleId = userRoleRepository.AddUserRole(model);

                if (!string.IsNullOrWhiteSpace(userRoleId))
                {
                    return(Json(new
                    {
                        IsSuccess = true,
                        data = new
                        {
                            UserRoleId = userRoleId
                        }
                    }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new
                    {
                        IsSuccess = false,
                        errorMessage = "User Role details not saved successfully."
                    }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception e)
            {
                Utility.Utility.LogError(e, "Create");
                return(Json(new
                {
                    IsSuccess = false,
                    errorMessage = e.Message
                }));
            }
        }
Esempio n. 25
0
        public static userRole ToDto(UserRoleVM vm)
        {
            userRole dto = new userRole()
            {
                code        = vm.Code,
                description = vm.Description,
                functionIds = string.Join(",", vm.FunctionIds),
                id          = vm.Id,
                name        = vm.Name,
            };

            return(dto);
        }
Esempio n. 26
0
        public UserRoleVM GetUserRole(int id)
        {
            UserRole   userRolesMaster = db.UserRoles.Find(id);
            UserRoleVM userRole        = new UserRoleVM()
            {
                Id       = userRolesMaster.URS_Id,
                UserId   = userRolesMaster.URS_UserId,
                RoleId   = userRolesMaster.URS_RoleId,
                RoleName = this.GetRolesMaster(userRolesMaster.URS_RoleId).Name,
                UserName = this.GetUserById(userRolesMaster.URS_UserId).USR_FirstName + ' ' + this.GetUserById(userRolesMaster.URS_UserId).USR_LastName
            };

            return(userRole);
        }
 public IActionResult DeleteUserRole(UserRoleVM item)
 {
     if (HttpContext.Session.GetString("UserRole") == "1" && HttpContext.Session.GetString("UserRole") != "Expired")
     {
         var i = db.UserRole.AsNoTracking().Where(a => a.UserRoleId == item.UserRoleId).FirstOrDefault();
         db.UserRole.Remove(i);
         db.SaveChanges();
         return(RedirectToAction("UserRoleList"));
     }
     else
     {
         return(RedirectToAction("Index", "Home"));
     }
 }
        public ActionResult Edit(Guid id)
        {
            var userRole = userRoleRepository.GetUserRoleById(id);

            UserRoleVM model = new UserRoleVM();

            if (userRole != null && userRole.Count > 0)
            {
                model = userRole[0];

                return(View(model));
            }

            return(RedirectToAction("List"));
        }
Esempio n. 29
0
        public int Update(UserRoleVM form)
        {
            Sys_Role model = this._roleRepository.Entity(ContextDB.managerDBContext, t => t.Id == form.Id);

            if (model != null)
            {
                model.UpdateDate  = DateTime.Now;
                model.RoleName    = form.RoleName;
                model.Description = form.Description;
                model.OrderSort   = form.OrderSort;
                model.Enabled     = form.Enabled;
            }

            return(this._roleRepository.Update(ContextDB.managerDBContext, model));
        }
Esempio n. 30
0
        public async Task <IActionResult> Index()
        {
            List <UserRoleVM> AllUserRolesData = new List <UserRoleVM>();

            var leftJoin = from p in _context.Users
                           join r in _context.UserRoles
                           on p.Id equals r.UserId
                           into temp
                           from r in temp.DefaultIfEmpty()
                           select new {
                id       = p.Id,
                username = p.UserName,
                urole    = r.RoleId
            };

            var rightJoin = from r in _context.UserRoles
                            join p in _context.Users
                            on r.UserId equals p.Id
                            into temp
                            from p in temp.DefaultIfEmpty()
                            select new
            {
                id       = p.Id,
                username = p.UserName,
                urole    = r.RoleId
            };

            var query = leftJoin.Union(rightJoin);

            foreach (var v in query)
            {
                if (string.IsNullOrEmpty(v.urole))
                {
                    CreateRole(v.id, "User");
                }

                UserRoleVM temp = new UserRoleVM
                {
                    ID    = v.id,
                    UName = v.username,
                    URole = v.urole
                };

                AllUserRolesData.Add(temp);
            }

            return(View(AllUserRolesData));
        }
Esempio n. 31
0
 public async Task <IActionResult> Create(UserRoleVM userRoleVM)
 {
     if (ModelState.IsValid)
     {
         var addUR = await _userRoleRepo.AddUserRole(userRoleVM.UserName, userRoleVM.Role);
     }
     try
     {
         return(RedirectToAction("Detail", "UserRole",
                                 new { userName = userRoleVM.UserName }));
     }
     catch
     {
         return(View());
     }
 }