protected async void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); // ユーザーとロールの初期化 // ロールの作成 var roleManager = new ApplicationRoleManager(new UserStore()); await roleManager.CreateAsync(new ApplicationRole { Name = "admin" }); await roleManager.CreateAsync(new ApplicationRole { Name = "users" }); var userManager = new ApplicationUserManager(new UserStore()); // 一般ユーザーの作成 await userManager.CreateAsync(new ApplicationUser { UserName = "******" }, "p@ssw0rd"); await userManager.AddToRoleAsync( (await userManager.FindByNameAsync("tanaka")).Id, "users"); // 管理者の作成 await userManager.CreateAsync(new ApplicationUser { UserName = "******" }, "p@ssw0rd"); await userManager.AddToRoleAsync( (await userManager.FindByNameAsync("super_tanaka")).Id, "users"); await userManager.AddToRoleAsync( (await userManager.FindByNameAsync("super_tanaka")).Id, "admin"); Debug.WriteLine("-----------"); }
public async Task Create(Beneficiary beneficiary, ApplicationUser applicationUser, string theme) { using (var trasactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { try { if (_userManager.FindByEmail(applicationUser.Email) != null) { throw new ApplicationException("Ya existe un usuario con ese email."); } var result = await _userManager.CreateAsync(applicationUser); if (!result.Succeeded) { throw new ApplicationException(result.Errors.FirstOrDefault()); } await _userManager.AddToRoleAsync(applicationUser.Id, RolesNames.Beneficiary); try { await _notificationService.SendAccountConfirmationEmail(applicationUser.Id, theme); } catch (Exception) { } var card = new Card(); card.IssueDate = _clock.Now; card.Number = _cardService.GenerateNumber(beneficiary); card.ExpirationDate = _cardService.CalculateExpirationDate(beneficiary.BirthDate.GetValueOrDefault()); beneficiary.Cards.Add(card); beneficiary.CreatedDate = _clock.Now; beneficiary.UserId = applicationUser.Id; Uow.Beneficiaries.Add(beneficiary); await Uow.CommitAsync(); trasactionScope.Complete(); } catch (Exception ex) { trasactionScope.Dispose(); throw ex; } } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Name = model.Name, Surname = model.Surname, Phone = model.Phone }; var result = await UserManager.CreateAsync(user, model.Password); await UserManager.AddToRoleAsync(user.Id, model.Role); Rating rating = new Rating(); rating.Sum = 5; rating.Times = 1; rating.Average = 5; var worklyUser = new WorklyUser { Email = model.Email, Name = model.Name, Surname = model.Surname, Phone = model.Phone, Rating = rating, Role = model.Role }; var tempList = new List <Review>(); var rev = new Review(); /// rev.Comment = "comment goes here"; /// tempList.Add(rev); // worklyUser.Review = tempList; jobSystemContext.WorklyUsers.Add(worklyUser); jobSystemContext.SaveChanges(); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://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>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <HttpResponseMessage> Update(HttpRequestMessage request, ApplicationGroupViewModel appGroupViewModel) { if (ModelState.IsValid) { var appGroup = _appGroupService.GetDetail(appGroupViewModel.ID); try { appGroup.UpdateApplicationGroup(appGroupViewModel); _appGroupService.Update(appGroup); //_appGroupService.Save(); //save group var listRoleGroup = new List <ApplicationRoleGroup>(); foreach (var role in appGroupViewModel.Roles) { listRoleGroup.Add(new ApplicationRoleGroup() { GroupId = appGroup.ID, RoleId = role.Id }); } _appRoleService.AddRolesToGroup(listRoleGroup, appGroup.ID); _appRoleService.Save(); //add role to user var listRole = _appRoleService.GetListRoleByGroupId(appGroup.ID); var listUserInGroup = _appGroupService.GetListUserByGroupId(appGroup.ID); foreach (var user in listUserInGroup) { var listRoleName = listRole.Select(x => x.Name).ToArray(); foreach (var roleName in listRoleName) { await _userManager.RemoveFromRoleAsync(user.Id, roleName); await _userManager.AddToRoleAsync(user.Id, roleName); } } return(request.CreateResponse(HttpStatusCode.OK, appGroupViewModel)); } catch (NameDuplicatedException dex) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, dex.Message)); } } else { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, FullName = model.FullName , Identification = model.Identification , DOB = model.DOB , Height = model.Height , Weight = model.Weight , Phone1 = model.Phone1 , Phone2 = model.Phone2 , Address1 = model.Address1 , Address2 = model.Address2 , Notes = model.Notes }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { result = await UserManager.AddToRoleAsync(user.Id, model.RoleName); //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>"); return(RedirectToAction("Register", "Account")); } AddErrors(result); } // If we got this far, something failed, redisplay form List <SelectListItem> list = new List <SelectListItem>(); foreach (var role in RoleManager.Roles.OrderBy(x => x.Name)) { list.Add(new SelectListItem() { Value = role.Name, Text = role.Name }); } ViewBag.Roles = list; return(View(model)); }
public async Task <ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return(View("Error")); } var result = await UserManager.ConfirmEmailAsync(userId, code); await UserManager.AddToRoleAsync(userId, "user"); //await SignInManager.SignInAsync(userId, isPersistent: false, rememberBrowser: false); //return RedirectToAction("Index", "Home"); return(View(result.Succeeded ? "ConfirmEmail" : "Error")); }
public async Task <ActionResult> Register(CustomerRegisterModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await UserManager.AddToRoleAsync(user.Id, UserRoles.Customer); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); model.Id = user.Id; model.IsCanOrder = true; TempData["NewCustomer"] = model; return(RedirectToAction("Create", "Customer")); } AddErrors(result); } return(View(model)); }
public async Task <ActionResult> Create([Bind(Include = "Id,Name,Telephone,UserID")] Teacher teacher) { ApplicationUserManager _app = Request.GetOwinContext().GetUserManager <ApplicationUserManager>(); if (ModelState.IsValid) { db.Teacher.Add(teacher); db.SaveChanges(); await _app.AddToRoleAsync(teacher.UserID, "Teacher"); return(RedirectToAction("Index")); } return(View(teacher)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, PhoneNumber = model.PhoneNumber }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (user.Email.Equals("*****@*****.**") || user.Email.Equals("*****@*****.**") || user.Email.Equals("*****@*****.**")) { await UserManager.AddToRoleAsync(user.Id, RoleName.SuperAdmin); } else { await UserManager.AddToRoleAsync(user.Id, RoleName.Guest); await RecordUserRegistrationInfoAsync(user.Email, model.CompanyName, model.OutletName); } string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Email Confirmation"); ViewBag.Message = "Check your email and confirm your registration"; return(View("RegInfo")); //return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> frmAddUser(AccountRegisterViewModel viewModel) { // If the ModelState is valid... if (ModelState.IsValid) { // Instantiate a User object var user = new UserLogin { UserName = viewModel.Username, UserRole = viewModel.UserRole }; // Create the user var result = await _userManager.CreateAsync(user, viewModel.Password); // If the user was successfully created... if (result.Succeeded) { //// Sign-in the user //await _signInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); //Assign User to Role await _userManager.AddToRoleAsync(user.Id, viewModel.UserRole); // Redirect them to the web app's "Home" page return(RedirectToAction("Index", "Home")); } // If there were errors... // Add model errors foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } return(View(viewModel)); }
public async Task <ActionResult> RegisterCustomer(CustomerRegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //Luu thong tin dang ky vao table customer Customer customer = new Customer { Name = model.Name, Address = model.Address, Phone = model.Phone, Email = model.Email, UserId = user.Id }; db.Customers.Add(customer); db.SaveChanges(); //Gán role Customer cho user await UserManager.AddToRoleAsync(user.Id, "Customer"); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Apellidos = model.Apellidos, Nombres = model.Nombres, PhoneNumber = model.Telefono, Documento = model.Documento, TipoDocumento = model.TipoDocumento, }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var rol = _securityManager.GetRolesById(model.Rol); var resultRol = await UserManager.AddToRoleAsync(user.Id, rol.Name); if (result.Succeeded && resultRol.Succeeded) { return(RedirectToAction("Index", "Home")); } } AddErrors(result); } var roles = _securityManager.GetRoles(); model.Roles = new SelectList(roles, "Name", "Name", 1); model.TiposDocumento = new SelectList(_catalogos.ObtenerCatalogoPorTipo(CatalogosEnum.TipoDocumento), "Value", "Text", 1); // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (model.IsAdmin) { await UserManager.AddToRoleAsync(user.Id, "admin");//MAKING THE ADMIN ROLE, for now is hardcoded but must be taked from db in db context } else { await UserManager.AddToRoleAsync(user.Id, "user");//MAKING THE user ROLE, for now is hardcoded but must be taked from db in db context } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://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>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); if (model.UserRoles == "Подрядчик") { await UserManager.AddToRoleAsync(user.Id, "Подрядчик"); } else { await UserManager.AddToRoleAsync(user.Id, "Заказчик"); } // Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см. по адресу: http://go.microsoft.com/fwlink/?LinkID=320771 // Отправка сообщения электронной почты с этой ссылкой // 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, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // Появление этого сообщения означает наличие ошибки; повторное отображение формы return(View(model)); }
public async Task <ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return(View("Error")); } var result = await UserManager.ConfirmEmailAsync(userId, code); if (result.Succeeded) { // Add user to User role once email is confirmed await UserManager.AddToRoleAsync(userId, "User"); } return(View(result.Succeeded ? "ConfirmEmail" : "Error")); }
public async Task <ActionResult> Register(RegisterViewModel model) { var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext())); if (!roleManager.RoleExists("Admin")) { var role = new IdentityRole { Name = "Admin" }; roleManager.Create(role); } if (ModelState.IsValid) { if (UserManager.Users.Any(x => x.Name.Equals(model.Name)) || UserManager.Users.Any(x => x.PhoneNumber.Equals(model.Phone))) { if (UserManager.Users.Any(x => x.Name.Equals(model.Name))) { ModelState.AddModelError("Name", "ชื่อนี้มีผู้ใช้แล้ว"); } if (UserManager.Users.Any(x => x.PhoneNumber.Equals(model.Phone))) { ModelState.AddModelError("Phone", "เบอร์โทรศัพท์นี้มีผู้ใช้แล้ว"); } return(View(model)); } var user = new ApplicationUser { UserName = model.Email, Name = model.Name, Email = model.Email, JoinDate = DateTime.UtcNow, PhoneNumber = model.Phone, UserRole = "Admin" }; var result = await UserManager.CreateAsync(user, model.Phone); if (result.Succeeded) { await UserManager.AddToRoleAsync(user.Id, "Admin"); return(RedirectToAction("Index", "Account")); } AddErrors(result); } return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, PhoneNumber = model.Phone, Gender = model.Gender }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); await UserManager.AddToRoleAsync(user.Id, model.UserRole); // For more information on how to enable account confirmation and password reset please visit https://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>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form var userRoles = _context.Roles.ToList(); var registrationViewModel = new RegisterViewModel { Email = model.Email, ConfirmPassword = model.ConfirmPassword, UserName = model.ConfirmPassword, Phone = model.Phone, Password = model.Password, Gender = model.Gender, UserRole = model.UserRole, GenderTypes = new List <string>() { Gender.MALE, Gender.FEMALE }, Roles = userRoles }; return(View(registrationViewModel)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, SignInDate = DateTime.Now }; if (Request.Files.Count > 0) { HttpPostedFileBase upload = Request.Files["upload"]; var avatar = new Forum.Models.File { FileName = Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } user.Photo = avatar.Content; user.Files = new List <Models.File> { avatar }; } var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); await UserManager.AddToRoleAsync(user.Id, "Member"); // 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>"); return(View(model)); //return RedirectToRoute("Categories"); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
private async Task <Tuple <IdentityResult, Guid> > CreateUser(RegisterAccountRequest model) { InviteInfo invite = null; if (model.InviteCode != null) { invite = _invitesService.FindInviteByToken(model.InviteCode.Value); if (invite == null || !invite.Email.Equals(model.Email, StringComparison.OrdinalIgnoreCase)) { return(new Tuple <IdentityResult, Guid>(IdentityResult.Failed("Bad invite"), Guid.Empty)); } } var user = new ApplicationUser { DomainId = Guid.NewGuid(), UserName = model.Email, Email = model.Email, IsActive = true, Profile = new ApplicationUserProfile { FirstName = model.FirstName, LastName = model.LastName } }; IdentityResult result = await _userManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return(new Tuple <IdentityResult, Guid>(result, Guid.Empty)); } string role = GlobalInfo.Candidate; if (invite != null) { role = invite.RoleName; user.EmailConfirmed = true; await _invitesService.UseInviteAsync(model.InviteCode.Value, user.Id); } else { await SendConfirmEmailAsync(user); } await _userManager.AddToRoleAsync(user.Id, role); return(new Tuple <IdentityResult, Guid>(IdentityResult.Success, user.DomainId)); }
public async Task <ActionResult> Register(RegisterViewModel model) { //if (ModelState.IsValid) {//create an application usser ApplicationUser user = null; if (model.RoleName == "Customer") { // creates a customer user = new Customer { UserName = model.Email, Email = model.Email, CustomerBalance = model.CustomerBalance }; } else { //testing purposes (create administrator) user = new Administrator { UserName = model.Email, Email = model.Email }; } var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //create the role for that user result = await UserManager.AddToRoleAsync(user.Id, model.RoleName); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://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>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Fio = model.Fio }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // если создание прошло успешно, то добавляем роль пользователя await UserManager.AddToRoleAsync(user.Id, "user"); #region Этот функционал если после регистрации нужно подтвердить email пользователя //// 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>"); // генерируем токен для подтверждения регистрации var 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, "Подтверждение электронной почты", "Для завершения регистрации перейдите по ссылке:: <a href=\"" + callbackUrl + "\">завершить регистрацию</a>"); return(View("DisplayEmail")); #endregion #region Этот функционал если после регистрации нужно сразу авторизовывать пользователя //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 //return RedirectToAction("Index", "Home"); #endregion } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task AddUserToRoleAsync(string userName, string role) { var existingUser = await _userManager.FindByNameAsync(userName); if (existingUser == null) { throw new NoSuchEntityException(existingUser.GetType().Name); } IdentityResult result = await _userManager.AddToRoleAsync(existingUser, role); if (!result.Succeeded) { throw new UserInvalidOperationException(result.ToString()); } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Firstname = model.Firstname, Surname = model.Surname, Address = model.Address, Zipcode = model.Zipcode, City = model.City }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://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>"); // await this.UserManager.AddToRoleAsync(user.Id, model.UserRole); //Create Cart for User Cart c = new Cart(); DateTime today = DateTime.Now; c.Expirationdate = today.AddDays(7); var userId = user.Id; c.UserId = userId; Cart ex = db.Carts.Where(Exc => Exc.UserId == userId).DefaultIfEmpty(null).First(); if (ex == null) { db.Carts.Add(c); db.SaveChanges(); } //End Cart Code await UserManager.AddToRoleAsync(user.Id, "Bezoeker"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); //creating user if (result.Succeeded) //if creating successful, Do the following actions: { await UserManager.AddToRoleAsync(user.Id, "user"); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); //подтверждение email var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); //перенаправляем на представление ConfirmEmail await UserManager.SendEmailAsync(user.Id, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>"); // return(View("DisplayEmail")); //if (ModelState.IsValid) //{ // var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Age = model.Age }; // var result = await UserManager.CreateAsync(user, model.Password); // if (result.Succeeded) // { // await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); //// Дополнительные сведения о включении подтверждения учетной записи и сброса пароля см. на странице https://go.microsoft.com/fwlink/?LinkID=320771. //// Отправка сообщения электронной почты с этой ссылкой //// 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, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>"); //return RedirectToAction("Index", "Home"); } AddErrors(result); } // Появление этого сообщения означает наличие ошибки; повторное отображение формы return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, IsScience = model.IsScience, IsArts = model.IsArts, IsTechnology = model.IsTechnology, IsEducation = model.IsEducation, IsSports = model.IsSports, IsReligious = model.IsReligious, IsSkillAcquisition = model.IsSkillAcquisition, IsEntrepreneurship = model.IsEntrepreneurship, IsGames = model.IsGames }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //For creating new role and adding user to the new role var roleStore = new RoleStore <IdentityRole>(new ApplicationDbContext()); var roleManager = new RoleManager <IdentityRole>(roleStore); await roleManager.CreateAsync(new IdentityRole("Member")); await UserManager.AddToRoleAsync(user.Id, "Member"); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://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>"); return(RedirectToAction("Index", "Members")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, DateOfBirth = model.DateOfBirth, Country = model.Country, Region = model.Region, City = model.City, Street = model.Street, StreetNumber = model.StreetNumber, ZipCode = model.ZipCode, }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // assign user to initial role var roleStore = new RoleStore <IdentityRole>(new AppUsersDbContext()); var roleManager = new RoleManager <IdentityRole>(roleStore);; await roleManager.CreateAsync(new IdentityRole("Validated User")); await UserManager.AddToRoleAsync(user.Id, "Validated User"); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); //AppUsersDbContext db = new AppUsersDbContext(); //db.SaveChanges(); // For more information on how to enable account confirmation and password reset please visit https://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>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await UserManager.AddToRoleAsync(user.Id, "patient"); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); var identity = (ClaimsPrincipal)Thread.CurrentPrincipal; var email = user.Email; //if (User.IsInRole == "doctor"){ /*Doctor doc = new Doctor { login = email }; * db.Doctor.Add(doc); * db.SaveChanges();*/ //} //if (User.IsInRole == "patient"){ Patient pat = new Patient { login = model.Email }; db.Patient.Add(pat); db.SaveChanges(); //} // Дополнительные сведения о включении подтверждения учетной записи и сброса пароля см. на странице https://go.microsoft.com/fwlink/?LinkID=320771. // Отправка сообщения электронной почты с этой ссылкой // 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, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // Появление этого сообщения означает наличие ошибки; повторное отображение формы return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { //var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var uzytkownik = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(uzytkownik, model.Password); if (result.Succeeded) { var resultRole = await UserManager.AddToRoleAsync(uzytkownik.Id, "Handlowiec"); if (resultRole.Succeeded) { using (SklepContext db = new SklepContext()) { Handlowiec handlowiec = new Handlowiec { Imie = model.Imie, Nazwisko = model.Nazwisko, UserId = uzytkownik.Id, Email = uzytkownik.Email }; db.Handlowcy.Add(handlowiec); db.SaveChanges(); } await SignInManager.SignInAsync(uzytkownik, isPersistent : false, rememberBrowser : false); // Aby uzyskać więcej informacji o sposobie włączania potwierdzania konta i resetowaniu hasła, odwiedź stronę https://go.microsoft.com/fwlink/?LinkID=320771 // Wyślij wiadomość e-mail z tym łączem // 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, "Potwierdź konto", "Potwierdź konto, klikając <a href=\"" + callbackUrl + "\">tutaj</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(resultRole); } AddErrors(result); } // Dotarcie do tego miejsca wskazuje, że wystąpił błąd, wyświetl ponownie formularz return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (model.RoleName == "User") { var normalUser = new NormalUser { id = user.Id }; context.NormalUsers.Add(normalUser); context.SaveChanges(); } else if (model.RoleName == "Doctor") { var doctor = new Doctor { id = user.Id }; context.Doctors.Add(doctor); context.SaveChanges(); } result = await UserManager.AddToRoleAsync(user.Id, model.RoleName); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://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>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { try { if (ModelState.IsValid) { var user = new ApplicationUser { Id = Guid.NewGuid().ToString(), UserName = model.FullName, Email = model.Email, FullName = model.FullName, PhoneNumber = model.PhoneNumber, Address = model.Address, Avatar = "defaultAvatar.jpg", }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // temp code tạo role và gắn role cho user khi đăng ký var roleStore = new RoleStore <IdentityRole>(new ApplicationDbContext()); var roleManager = new RoleManager <IdentityRole>(roleStore); // await roleStore.CreateAsync(new IdentityRole("Customer")); await UserManager.AddToRoleAsync(user.Id, "Customer"); // login await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://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); //string html = "Please confirm your account by clicking <a class=\"btn btn-sucess\" href=\"" + callbackUrl + "\">Confirm</a>"; //await UserManager.SendEmailAsync(user.Id, "Confirm your account", html); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); } catch { return(RedirectToAction("Erorr", "Home")); } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { if (model.ImageFile == null) { model.ImagePath = "~/Content/Images/Empty_pic.png"; } else { string fileName = Path.GetFileNameWithoutExtension(model.ImageFile.FileName); string extension = Path.GetExtension(model.ImageFile.FileName); fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; model.ImagePath = "~/Content/Images/" + fileName; fileName = Path.Combine(Server.MapPath("~/Content/Images/"), fileName); model.ImageFile.SaveAs(fileName); } var user = new TARUser { CreatedAt = DateTime.Now, LastModifiedAt = DateTime.Now, DisplayName = model.Name, ImagePath = model.ImagePath, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); await UserManager.AddToRoleAsync(user.Id, "Member"); /* For more information on how to enable account confirmation and password reset please visit https://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>"); */ ModelState.Clear(); return(RedirectToAction("Index", "DashBoard")); } AddErrors(result); } /* If we got this far, something failed, redisplay form */ return(View(model)); }
public async Task<IHttpActionResult> Post([FromBody]RegisterUserModel model) { if (!ModelState.IsValid) return BadRequest(ModelState); var manager = new ApplicationUserManager(new MySqlUserStore<ApplicationUser>()); var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email, PhoneNumber = model.PhoneNumber }; IdentityResult result = await manager.CreateAsync(user, model.Password); if (!result.Succeeded) return GetErrorResult(result); result = await manager.AddToRoleAsync(model.UserName, model.Role); if (!result.Succeeded) return GetErrorResult(result); return Ok(); }
public async Task<bool> InsertOrUpdate(IdentityUserViewModel model, ApplicationUserManager userManager) { var user = await userManager.FindByIdAsync(model.Id); if (user == null) { user = new ApplicationUser(); user.Assign(model); var result = await userManager.CreateAsync(user, "1234567"); if (!result.Succeeded) return false; model.Id = user.Id; } else { user.Email = model.Email; user.UserName = model.UserName; user.DUI = model.DUI; user.PhoneNumber = model.PHONE_2; user.ADDRESS = model.ADDRESS; user.Category = model.Category; user.FirstName = model.FirstName; user.LastName = model.LastName; user.DUI = model.DUI; user.PHONE_2 = model.PHONE_2; user.ProfilePicture = model.ProfilePicture; user.CenterId = model.CenterId; //user.Address = model.Address; //user.FirstName = model.FirstName; //user.LastName = model.LastName; //user.DocumentNum = model.DocumentNum; //user.ProfilePicture = model.ProfilePicture; await userManager.UpdateAsync(user); } if (model.ForceChangePassword) { var tok = await userManager.GeneratePasswordResetTokenAsync(model.Id); var result = await userManager.ResetPasswordAsync(model.Id, tok, model.Password); if (!result.Succeeded) return false; } var roles = await userManager.GetRolesAsync(model.Id); if (!roles.Any() && !string.IsNullOrEmpty(model.Role)) { var res = await userManager.AddToRoleAsync(model.Id, model.Role); } if (roles.All(r => r != model.Role) && roles.Any()) { var result = await userManager.AddToRoleAsync(model.Id, model.Role); } roles.Where(r => r != model.Role).ToList().ForEach(role => userManager.RemoveFromRole(model.Id, role)); if (model.CenterId != 0) { var claim = await Context.UserClaims.FirstOrDefaultAsync(c => c.UserId == user.Id && c.ClaimType == "CenterId"); var claims = await userManager.GetClaimsAsync(user.Id); if (claim != null) { claim.ClaimValue = model.CenterId.Value.ToString(); await Context.SaveChangesAsync(); } else { await userManager.AddClaimAsync(model.Id, new System.Security.Claims.Claim("CenterId", model.CenterId.ToString())); } } return true; }
public bool AddUserToRole(ApplicationUserManager userManager, int userId, string roleName) { var idResult = userManager.AddToRoleAsync(userId, roleName); return idResult.IsCompleted; }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, PhoneNumber = model.PhoneNumber, Email = model.Email}; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new SGURestaurantContext())); await userManager.AddToRoleAsync(user.Id, "Customer"); //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); string msg = "Bạn đã đăng ký tài khoản tại SGURestaurant<br/>Vui lòng hoàn tất việc đăng ký của bạn <a href=\"" + callbackUrl + "\">tại đây</a>"; await UserManager.SendEmailAsync(user.Id, "SGURestaurant - Xác nhận đăng ký", msg); return RedirectToAction("Confirm", new { Email = user.Email }); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }