public async Task <ActionResult> Register(RegisterViewModel model) { var aspNetUserRoles = new AspNetUserRoles(); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //create the user role aspNetUserRoles.RoleId = model.UserRole; aspNetUserRoles.UserId = user.Id; db.AspNetUserRoles.Add(aspNetUserRoles); db.SaveChanges(); // yeni register olan kişiye bilgilerini mail atsın // bool mail = await SendEmail(user); return(RedirectToAction("Successful", "Account")); } AddErrors(result); } // If we got this far, something failed, redisplay form ViewBag.UserRole = new SelectList(db.AspNetUserRoles, "Id", "Email") as IEnumerable <SelectListItem>; return(View(model)); }
private bool CreateUserRole(string userId, string roleId) { var user = GetUserById(userId); var role = GetRoleById(roleId); var userRole = new AspNetUserRoles { Role = role, User = user }; using (var cl = new HttpClient()) { cl.BaseAddress = new Uri(baseurl); var content = JsonConvert.SerializeObject(userRole); var buffer = System.Text.Encoding.UTF8.GetBytes(content); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var postTask = cl.PostAsync("api/AspNetUserRoles", byteContent).Result; if (postTask.IsSuccessStatusCode) { return(true); } return(false); } }
public ActionResult HuyPhanQuyen([Bind(Include = "Id")] AspNetUser user, string RoleID) { if (Session["DangNhap"] == null || !Session["DangNhap"].ToString().Equals("true")) { return(RedirectToAction("Index", "DangNhap")); } if (!ModelState.IsValid) { return(View(user)); } var kh = db.AspNetUsers.Single(u => u.Id.Equals(user.Id)); // nếu 1 khách hàng chỉ còn 1 quyên thì không được xóa quyền nữa if (kh.AspNetRoles.Count == 1) { return(RedirectToAction("Index")); } AspNetUserRoles a = new AspNetUserRoles(); var khachhang = a.Users.Find(user.Id); var quyen = a.Roles.Find(RoleID); khachhang.AspNetRoles.Remove(quyen); if (a.SaveChanges() > 0) { return(RedirectToAction("Index")); } else { List <AspNetRole> listQuyen = kh.AspNetRoles.ToList <AspNetRole>(); ViewBag.Quyens = new SelectList(listQuyen, "Id", "Name"); return(View(user)); } }
public ActionResult Index() { //Session["BiKhoa"] = null; if (Session["BiKhoa"] != null) { return(RedirectToAction("LogOffs", "Account")); } string MaTK = null; MaTK = User.Identity.GetUserId(); if (MaTK != null) { Session["DangNhap"] = "1"; } if (Session["DangKyRoles"] != null && Session["DangKyRoles"].ToString().Equals("DKRoles")) { String userIDnek = User.Identity.GetUserId(); AspNetUserRoles userR = new AspNetUserRoles(); var u = userR.Users.Find(userIDnek); var _quyen = userR.Roles.Find("1"); u.AspNetRoles.Add(_quyen); userR.SaveChanges(); Session["DangKyRoles"] = null; } return(View()); }
public ActionResult EditRole(bool isChecked, string userId, string roleId) { bool successful = false; if (isChecked) { // Adding Role for User AspNetUserRoles newRole = new AspNetUserRoles() { RoleId = roleId, UserId = userId, UserRoleId = Guid.NewGuid().ToString(), }; db.AspNetUserRoles.Add(newRole); db.SaveChanges(); successful = true; } else { // Remove Role from User AspNetUserRoles userRole = db.AspNetUserRoles .Where(ur => ur.UserId == userId && ur.RoleId == roleId) .FirstOrDefault(); if (userRole != null) { db.AspNetUserRoles.Attach(userRole); db.AspNetUserRoles.Remove(userRole); db.SaveChanges(); successful = true; } } return(Json(new { success = successful }, JsonRequestBehavior.AllowGet)); }
public IActionResult AgregarRolUser(AspNetUserRoles ur) { db.AspNetUserRoles.Add(ur); db.SaveChanges(); return(RedirectToAction("Index")); }
public async Task <ActionResult> UpdateUserRole([FromBody] AspNetUserDTO aspNetUserDTO) { try { if (aspNetUserDTO.userRoles.RoleName != null && aspNetUserDTO.Email != null) { var GetuserId = _userRepo.GetUser(aspNetUserDTO); var GetUserRoleId = _userRepo.GetRole(aspNetUserDTO.userRoles.RoleName); AspNetUserRoles NewRole = new AspNetUserRoles() { UserId = GetuserId.Result.Id, RoleId = GetUserRoleId.Result.Id }; await _userRepo.UpdateUserRole(NewRole); return(new StatusCodeResult(200)); } else { return(new StatusCodeResult(400)); } }catch (Exception ex) { return(new StatusCodeResult(400)); } }
public IActionResult ChangeMembership(ViewModelFood model) { if (model.CurrentUser.isPremium) { AspNetUserRoles role = new AspNetUserRoles(); role.RoleId = ("F4F4367D-940C-4FD7-A848-137508F418C1"); role.UserId = model.CurrentUser.Id; var cust = _context.Customer.SingleOrDefault(c => c.UserId == role.UserId); cust.Points = 0; _context.AspNetUserRoles.Add(role); _context.SaveChanges(); } else { var role = _context.AspNetUserRoles.SingleOrDefault(r => r.UserId == model.CurrentUser.Id && r.RoleId == "F4F4367D-940C-4FD7-A848-137508F418C1"); var cust = _context.Customer.SingleOrDefault(c => c.UserId == role.UserId); cust.Points = 0; _context.Remove(role); _context.SaveChanges(); } return(RedirectToAction("ManageUsers")); }
public ActionResult Create(AspNetUserRoles crear) { try { if (ModelState.IsValid) { IchamiloClient client = new IchamiloClient(); client.Open(); ChamiloUser chuser = client.getUserChamilo(crear.AspNetUsers.Name); if (crear.AspNetRoles.Name == "Maestro" && chuser.Status == 5) { chuser.Status = 1; client.updateUser(chuser, chuser.Username); } if (crear.AspNetRoles.Name == "Estudiante" && chuser.Status == 1) { chuser.Status = 5; client.updateUser(chuser, chuser.Username); } db.AspNetUserRoles.Add(crear); db.SaveChanges(); return(RedirectToAction("Index")); } } catch (Exception) { ViewBag.Error = "El usuario ya pertenece al rol."; return(RedirectToAction("Index")); } return(View(crear)); }
public async Task UpdateUserRole(AspNetUserRoles NewRoleToUser) { try { if (NewRoleToUser.RoleId != null && NewRoleToUser.UserId != null) { try { var checkuserifexcist = _databaseContext.AspNetUserRoles.Where(y => y.UserId == NewRoleToUser.UserId).Select(c => new AspNetUserRoles() { RoleId = c.RoleId, UserId = c.UserId }).FirstOrDefault(); if (checkuserifexcist != null) { _databaseContext.AspNetUserRoles.Remove(checkuserifexcist); await _databaseContext.SaveChangesAsync(); _databaseContext.AspNetUserRoles.Add(NewRoleToUser); } else { _databaseContext.AspNetUserRoles.Add(NewRoleToUser); } await _databaseContext.SaveChangesAsync(); }catch (Exception ex) { throw new ArgumentException(ex.Message); } } }catch (Exception ex) { throw new ArgumentException(ex.Message); } }
public ActionResult EditRol(AspNetUserRoles r) { try { if (!ModelState.IsValid) { return(View()); } using (var db = new UsuarioContext()) { AspNetUserRoles rol = db.AspNetUserRoles.Find(r.UserId, r.RoleId); rol.Rolename = r.Rolename; db.SaveChanges(); return(RedirectToAction("Role")); } } catch (Exception error) { ModelState.AddModelError("Error al editar el rol", error); return(View()); } }
public ActionResult Edit(AspNetUserRoles obj) { if (ModelState.IsValid) { try { var result = iRoleManage.Update(obj, "u"); return(Json(new { ErrorCode = result.ErrorCode, Message = result.Msg, Id = result.Id, JsonRequestBehavior.AllowGet })); } catch (Exception ex) { return(Json(new { ErrorCode = false, Message = ex.Message }, JsonRequestBehavior.AllowGet)); } } Response.TrySkipIisCustomErrors = true; string messages = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)); return(Json(new { ErrorCode = 1, Message = messages }, JsonRequestBehavior.AllowGet)); }
public async Task <IActionResult> Edit([FromForm] AspNetUserRolesEditViewModel vmItem, [FromRoute] string id) { if (id == null) { return(NotFound()); } // Get time stamp for table to handle concurrency conflict var tableName = nameof(AspNetUserRoles); var tableVersion = await _context.TableVersion.FirstOrDefaultAsync(h => h.Id == tableName); var dbItem = await _context.AspNetUserRoles .Where(h => h.UserId == id) .FirstOrDefaultAsync(); if (dbItem == null) { return(NotFound()); } _context.Remove(dbItem); await _context.SaveChangesAsync(); var dbItem1 = new AspNetUserRoles { UserId = id, RoleId = vmItem.RoleId, }; _context.Add(dbItem1); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Details), new { id = dbItem1.UserId })); }
public async Task EditRole(AspNetRoleModel model) { var aspNetRole = _context.AspNetRoles.Where(x => x.Id.ToLower().Trim() == model.Id.Trim().ToLower()).SingleOrDefault(); if (aspNetRole == null) { throw new NullReferenceException(String.Concat(_localizer["EditDataError"], _localizer["RoleNotFound"])); } aspNetRole.Name = model.Name.Trim(); aspNetRole.NormalizedName = model.Name.ToUpper().Trim(); var users = await _context.AspNetUserRoles.Where(x => x.RoleId == model.Id).ToListAsync(); var userToRemove = users.Where(x => !model.Users.Select(u => u.Id).Contains(x.UserId)); var userToAdd = model.Users.Where(x => !users.Select(u => u.UserId).Contains(x.Id)); foreach (var user in userToRemove) { _context.Entry <AspNetUserRoles>(user).State = EntityState.Deleted; } foreach (var user in userToAdd) { var aspNetUserRole = new AspNetUserRoles { RoleId = aspNetRole.Id, UserId = user.Id }; await _context.AspNetUserRoles.AddAsync(aspNetUserRole); } await _context.SaveChangesAsync(); }
public async Task <IActionResult> Edit(string id, [Bind("UserId,RoleId")] AspNetUserRoles aspNetUserRoles) { if (id != aspNetUserRoles.UserId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(aspNetUserRoles); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AspNetUserRolesExists(aspNetUserRoles.UserId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["RoleId"] = new SelectList(_context.AspNetRoles, "Id", "Id", aspNetUserRoles.RoleId); ViewData["UserId"] = new SelectList(_context.AspNetUsers, "Id", "Id", aspNetUserRoles.UserId); return(View(aspNetUserRoles)); }
public async Task <IActionResult> AddtoRole([Bind("UserId, RoleId")] AspNetUserRoles aspNetUserRoles) { if ((aspNetUserRoles.UserId + "").Trim() == "" && (aspNetUserRoles.RoleId + "").Trim() == "") { ModelState.AddModelError("", "No User to add"); TempData["Message"] = "No User to add"; return(RedirectToAction(nameof(Index))); } try { var UserName = _context.AspNetUsers.Where(w => w.Id == aspNetUserRoles.UserId).FirstOrDefault().UserName; if (ModelState.IsValid) { _context.Add(aspNetUserRoles); await _context.SaveChangesAsync(); TempData["Message"] = "User added to Role: " + UserName; return(RedirectToAction(nameof(UserInRole))); } } catch (Exception ex) { // throw; ModelState.AddModelError("", ex.GetBaseException().Message); return(View("UserInRole")); } return(View("UserInRole")); }
public async Task <ActionResult> RegisterCustomer(UserViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Name, Name = model.Name, BirthDay = model.BirthDay, Sex = model.Sex, PhoneNumber = model.PhoneNumber.ToString(), Email = model.Email, WardId = model.WardID, DetailAddress = model.DetailAddress, CreateAt = DateTime.Now, IsDelete = false, }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { AspNetUserRoles temp = new AspNetUserRoles(); temp.ShopID = this.GetShopId(); temp.UserId = user.Id; temp.RoleId = 2; temp.IsDelete = false; shopUserSV.AddShopUser(temp); return(Json(new { flag = true })); } return(Json(new { flag = false })); } return(Json(new { flag = false })); }
public IHttpActionResult PutAspNetUserRoles(string id, AspNetUserRoles aspNetUserRoles) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != aspNetUserRoles.UserId) { return(BadRequest()); } db.Entry(aspNetUserRoles).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!AspNetUserRolesExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult PostAspNetUserRoles(AspNetUserRoles aspNetUserRoles) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.AspNetUserRoles.Add(aspNetUserRoles); try { db.SaveChanges(); } catch (DbUpdateException) { if (AspNetUserRolesExists(aspNetUserRoles.UserId)) { return(Conflict()); } else { throw; } } return(CreatedAtRoute("DefaultApi", new { id = aspNetUserRoles.UserId }, aspNetUserRoles)); }
public void UpdateDepRep(string id) { AspNetUsers user1 = inventory.AspNetUsers.Where(P => P.Id == id).First <AspNetUsers>(); AspNetUsers user2 = inventory.AspNetUsers.Where(P => P.UserType == "DeptRep" && P.DepartmentID.Substring(0, 4) == user1.DepartmentID.Substring(0, 4)).First <AspNetUsers>(); AspNetUserRoles role1 = inventory.AspNetUserRoles.Where(p => p.UserId == user1.Id).First(); AspNetUserRoles role2 = inventory.AspNetUserRoles.Where(p => p.UserId == user2.Id).First(); Department dep1 = inventory.Department.Where(p => p.DepartmentID == user1.DepartmentID).First(); user1.UserType = "DeptRep"; user2.UserType = "DeptStaff"; dep1.DepartmentRep = user1.Id; inventory.AspNetUserRoles.Remove(role1); inventory.AspNetUserRoles.Remove(role2); AspNetUserRoles userrole = new AspNetUserRoles(); userrole.UserId = role1.UserId; userrole.RoleId = "2"; inventory.AspNetUserRoles.Add(userrole); AspNetUserRoles userrole1 = new AspNetUserRoles(); userrole1.UserId = role2.UserId; userrole1.RoleId = "4"; inventory.AspNetUserRoles.Add(userrole1); inventory.SaveChanges(); }
public string AddUser(UserModel user) { try { var userEntities = _context.AspNetUsers.Where(m => m.Email == user.Email).ToList(); if (userEntities.Any()) { return("-3"); } var userEntity = mapper.Map <UserModel, AspNetUsers>(user); userEntity.Id = Guid.NewGuid().ToString(); userEntity.SecurityStamp = Guid.NewGuid().ToString("D"); userEntity.EmailConfirmed = true; userEntity.PasswordHash = PasswordManager.HashPassword(user.Password); _context.AspNetUsers.Add(userEntity); _context.SaveChanges(); if (!string.IsNullOrEmpty(user.Role)) { var role = new AspNetUserRoles { UserId = userEntity.Id, RoleId = user.Role }; _context.AspNetUserRoles.Add(role); _context.SaveChanges(); } return(userEntity.Id); } catch (Exception e) { return(null); } }
public ActionResult Editar(AspNetUserRoles aspu) { try { if (!ModelState.IsValid) { return(View()); } using (var db = new AlmacenContexto()) { AspNetUserRoles aspnet = db.AspNetUserRoles.Find(aspu.UserId, aspu.RoleId); aspnet.RoleId = aspu.RoleId; aspnet.RoleName = aspu.RoleName; db.SaveChanges(); return(RedirectToAction("Index")); } } catch (Exception ex) { ModelState.AddModelError("Error", ex); return(View()); } }
public async Task <IActionResult> PutAspNetUserRoles(string id, AspNetUserRoles aspNetUserRoles) { if (id != aspNetUserRoles.UserId) { return(BadRequest()); } _context.Entry(aspNetUserRoles).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AspNetUserRolesExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task EditUserRoleByUser(AspNetUserModel model) { var aspNetUserRoles = await _context.AspNetUserRoles.Where(x => x.UserId.ToLower().Trim() == model.Id.Trim().ToLower()).ToListAsync(); if (aspNetUserRoles == null) { throw new NullReferenceException(String.Concat(_localizer["EditDataError"], _localizer["RoleNotFound"])); } var rolesToRemove = aspNetUserRoles.Where(x => !model.Roles.Select(u => u.Id).Contains(x.RoleId)); var rolesToAdd = model.Roles.Where(x => !aspNetUserRoles.Select(u => u.RoleId).Contains(x.Id)); foreach (var role in rolesToRemove) { _context.Entry <AspNetUserRoles>(role).State = EntityState.Deleted; } foreach (var role in rolesToAdd) { var aspNetUserRole = new AspNetUserRoles { RoleId = role.Id, UserId = model.Id }; await _context.AspNetUserRoles.AddAsync(aspNetUserRole); } await _context.SaveChangesAsync(); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Uzyskaj informacje o użytkowniku od dostawcy logowania zewnętrznego var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { string idnowe = user.Id; AspNetUserRoles roling = new AspNetUserRoles(); Klienci ni = new Klienci(); zamowienia no = new zamowienia(); if (idnowe != null) { roling.RoleId = "3"; roling.UserId = idnowe; dbruls.AspNetUserRoles.Add(roling); await dbruls.SaveChangesAsync(); ni.Id_uzytkownik = idnowe; ni.email = user.Email; db.Klienci.Add(ni); no.Id_zamowienia = idnowe; no.id_klienta = idnowe; no.status = 0; no.e_mail = model.Email; db.zamowienia.Add(no); await db.SaveChangesAsync(); } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { //Tạo biến user theo class ApplicationUser, truyền các giá trị của model nhập từ form vào var user = new ApplicationUser { IsDelete = false, Name = model.Name, UserName = model.Email, BirthDay = model.Birthday, Sex = model.Sex, Identity = model.Identity, PhoneNumber = model.PhoneNumber.ToString(), Email = model.Email, WardId = model.WardID, DetailAddress = model.DetailAddress, Description = model.Description, CreateAt = DateTime.Now, }; //Tạo một tài khản mới vào database AspNetUsers var result = await UserManager.CreateAsync(user, model.Password); //Khi tạo thành công sẽ tiến hành đăng nhập, và thêm dữ liệu vào database AspNetUserRole if (result.Succeeded) { //đăng nhập vào hệ thống await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); AspNetUserRoles temp = new AspNetUserRoles(); //Khởi tạo một biến temp từ class AspNetUserRole Model temp.RoleId = model.Role; temp.ShopID = model.ShopID; temp.UserId = user.Id; temp.IsDelete = false; shopUserSV.AddShopUser(temp); //Thêm vào AspNetUserRole //trở về view Index của ShopUserController return(RedirectToAction("Index", "ShopUser")); } //Trường hợp khi thêm thất bại, ct sẽ add các lỗi trở lại form thông báo cho người dùng AddErrors(result); } //Lấy từ database danh sách Role, Shop, và City List <AspNetRoles> listRole = roleSV.GetAll().ToList(); ViewData["ListRole"] = listRole; List <Shop> listShop = shopSV.GetAll().ToList(); ViewData["ListShop"] = listShop; List <City> listCity = citySV.GetAll().ToList(); ViewData["ListCity"] = listCity; // If we got this far, something failed, redisplay form return(View()); }
public ActionResult DeleteConfirmed(int id) { AspNetUserRoles eliminar = db.AspNetUserRoles.Find(id); db.AspNetUserRoles.Remove(eliminar); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(string id1, string id2) { AspNetUserRoles aspNetUserRoles = db.AspNetUserRoles.Find(id1, id2); db.AspNetUserRoles.Remove(aspNetUserRoles); db.SaveChanges(); return(RedirectToAction("Index")); }
public async Task <IActionResult> Edit(AspNetUserRoles userRole) { var user = await userManager.FindByIdAsync(userRole.UserId); await userManager.AddToRoleAsync(user, userRole.RoleId); return(RedirectToAction(nameof(Index))); }
public void CreateRole(string Id, string RoleId) { AspNetUserRoles userRole = new AspNetUserRoles(); userRole.UserId = Id; userRole.RoleId = RoleId; db.AspNetUserRoles.Add(userRole); }