public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { var user = new ApplicationUsers(); user.Name = model.Name; user.Surname = model.Surname; user.UserName = model.Username; user.Email = model.Email; var result = userManager.Create(user, model.Password); if (result.Succeeded) { //User created //asign role to user if (roleManager.RoleExists("User")) { userManager.AddToRole(user.Id, "user"); } return(RedirectToAction("Login", "Account")); } else { ModelState.AddModelError("RegisterUserError", "Kullanıcı oluşturma Hatası"); } } return(View(model)); }
private static async Task <string> EnsureUser(IServiceProvider serviceProvider, string testUserPw, string UserName, int ProfileID, bd_lesContext _context) { var userManager = serviceProvider.GetService <UserManager <ApplicationUsers> >(); var func = new Funcionario { NomeCompleto = UserName }; var user = await userManager.FindByNameAsync(UserName); if (user == null && UserName != null && ProfileID != 0) { _context.Add(func); await _context.SaveChangesAsync(); user = new ApplicationUsers { UserName = UserName, FuncionarioIdFuncionario = func.IdFuncionario, IdPerfil = ProfileID }; var result = await userManager.CreateAsync(user, testUserPw); if (!result.Succeeded) { Console.WriteLine(result.Errors); _context.Remove(func); await _context.SaveChangesAsync(); } } return(user.Id); }
public static async Task InitilizeRole(IServiceProvider serviceProvider) { UserManager <ApplicationUsers> userManager = serviceProvider.GetRequiredService <UserManager <ApplicationUsers> >(); RoleManager <IdentityRole> roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >(); string login = "******"; string pass = "******"; if (await roleManager.FindByIdAsync("admin") == null) { await roleManager.CreateAsync(new IdentityRole("admin")); } if (await roleManager.FindByIdAsync("user") == null) { await roleManager.CreateAsync(new IdentityRole("user")); } if (await userManager.FindByNameAsync(login) == null) { ApplicationUsers admin = new ApplicationUsers { UserName = login }; IdentityResult result = await userManager.CreateAsync(admin, pass); if (result.Succeeded) { await userManager.AddToRoleAsync(admin, "admin"); } } }
private async Task SignInAsync(ApplicationUsers user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUsers { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { 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, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); ViewBag.Link = callbackUrl; return(View("DisplayEmail")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> EditPost(string id, ApplicationUsers user) { if (id != user.Id) { return(PartialView("EditUser", user)); } var userFromDb = await _userManager.FindByIdAsync(id); if (userFromDb == null) { return(NotFound("No user")); } userFromDb.Name = user.Name; userFromDb.Gender = user.Gender; userFromDb.Contact = user.Contact; userFromDb.DateOfBirth = user.DateOfBirth; userFromDb.Region = user.Region; userFromDb.Country = user.Country; userFromDb.City = user.City; userFromDb.Address = user.Address; await _userManager.UpdateAsync(userFromDb); return(RedirectToAction("Index")); }
public async Task <IActionResult> OnGet() { //Create Roles for our Website And create ADmin USer if (!await _roleManager.RoleExistsAsync(SD.SuperAdminEndUser)) { await _roleManager.CreateAsync(new IdentityRole(superAdminEndUser)); var userAdmin = new ApplicationUsers() { UserName = "******", FullName = "Main Supper Admin", Email = "*****@*****.**", PhoneNumber = "0912312321" }; var resultUser = await _userManager.CreateAsync(userAdmin, "Admin123*"); await _userManager.AddToRoleAsync(userAdmin, SD.SuperAdminEndUser); } if (!await _roleManager.RoleExistsAsync(SD.CustomerUser)) { await _roleManager.CreateAsync(new IdentityRole(SD.CustomerUser)); } return(Page()); }
public List <Party> GetPartiesUser(string username) { List <Party> parties = new List <Party>(); OpenClosedConnection(); List <int> partyIds = new List <int>(); List <ApplicationUser> users = new List <ApplicationUser>(); List <string> partyNames = new List <string>(); List <int> indexesLeadCharacter = new List <int>(); var command = new SqlCommand("execute GetParties @username", connection); command.Parameters.Add(new SqlParameter("@username", username)); using (var reader = command.ExecuteReader()) { while (reader.Read()) { partyIds.Add(int.Parse(reader[0].ToString())); string userId = reader[1].ToString(); users.Add(ApplicationUsers.Where(u => u.Id == userId).First()); partyNames.Add(reader[2].ToString()); indexesLeadCharacter.Add(int.Parse(reader[3].ToString())); } } for (int x = 0; x < partyIds.Count(); x++) { Party party = new Party(users[x], partyNames[x], new List <Character>(), indexesLeadCharacter[x], partyIds[x]); AddCharacters(party); parties.Add(party); } connection.Close(); return(parties); }
public void ChangeActiveParty(int partyIndex, string username) { ApplicationUser user = ApplicationUsers.Include(s => s.Parties).Where(u => u.UserName == username).First(); user.ChangeSelectedPartyIndex(partyIndex); Entry(user).State = EntityState.Modified; }
public async Task <IActionResult> AddUser(UserInfoViewModel model) { var role = await _role.FindByIdAsync(model.RoleId); if (ModelState.IsValid) { var user = new ApplicationUsers { UserName = model.Email, Email = model.Email, Name = model.Name, Designation = role.Name, Status = model.Status, PasswordHash = model.Password }; var result = await _usermanager.CreateAsync(user, model.Password); if (result.Succeeded) { await _usermanager.AddToRoleAsync(user, role.Name); return(RedirectToAction("Index")); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return(View()); }
public async Task <IActionResult> AccessRight(string selectedItems, string userId) { List <TreeViewNode> items = JsonConvert.DeserializeObject <List <TreeViewNode> >(selectedItems); ApplicationUsers user = await _userManager.FindByIdAsync(userId); if (user != null) { //Delete All Roles for User var roles = await _userManager.GetRolesAsync(user); IdentityResult delRoleResult = await _userManager.RemoveFromRolesAsync(user, roles); if (delRoleResult.Succeeded) { for (int i = 0; i < items.Count; i++) { ApplicationRoles approle = await _roleManager.FindByIdAsync(items[i].id); if (approle != null) { IdentityResult result = await _userManager.AddToRoleAsync(user, approle.Name); if (result.Succeeded) { } } } } } return(RedirectToAction("Index", "User")); }
public async Task Invoke(HttpContext httpContext, UserManager <ApplicationUsers> _userManager, ICondominiumService _condominiumManager) { if (httpContext.User.Identity.IsAuthenticated) { ApplicationUsers user = await _userManager.GetUserAsync(httpContext.User); if (user != null) { var retorno = await _condominiumManager.GetCondominiumByIdAsync(user.Id); if (retorno.Count == 0 && httpContext.Request.Path.Value != path) { httpContext.Response.Redirect(path); } else { await _next(httpContext); } } else { await _next(httpContext); } } else { await _next(httpContext); } }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUsers { UserName = model.UserName, Email = model.Email, MemberSince = DateTime.Now }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); return(RedirectToAction("Index", "home")); } foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } return(View()); }
public ActionResult Login([Bind] ApplicationUser user) { var users = new ApplicationUsers(Configuration); var allUsers = users.GetUsers().FirstOrDefault(); if (users.GetUsers().Any(u => u.UserName == user.UserName && u.Password == user.Password)) { var userClaims = new List <Claim>() { new Claim(ClaimTypes.Name, user.UserName) }; var grandmaIdentity = new ClaimsIdentity(userClaims, "User Identity"); var userPrincipal = new ClaimsPrincipal(new[] { grandmaIdentity }); HttpContext.SignInAsync(userPrincipal); if (user.ReturnUrl != null) { return(Redirect(user.ReturnUrl)); } return(RedirectToAction("Index", "Home")); } return(RedirectToAction("Index", "Home")); }
public async Task <ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles) { if (ModelState.IsValid) { var user = new ApplicationUsers { UserName = userViewModel.Email, Email = userViewModel.Email }; var adminresult = await UserManager.CreateAsync(user, userViewModel.Password); //Add User to the selected Roles if (adminresult.Succeeded) { if (selectedRoles != null) { var result = await UserManager.AddToRolesAsync(user.Id, selectedRoles); if (!result.Succeeded) { ModelState.AddModelError("", result.Errors.First()); ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name"); return(View()); } } } else { ModelState.AddModelError("", adminresult.Errors.First()); ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name"); return(View()); } return(RedirectToAction("Index")); } ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name"); return(View()); }
public async Task <(bool Succeeded, string[] Errors)> UpdateUserAsync(ApplicationUsers user, string password) { var result = await _userManager.UpdateAsync(user); if (!result.Succeeded) { return(false, result.Errors.Select(e => e.Description).ToArray()); } result = await _userManager.RemovePasswordAsync(user); if (!result.Succeeded) { return(false, result.Errors.Select(e => e.Description).ToArray()); } result = await _userManager.AddPasswordAsync(user, password); if (!result.Succeeded) { return(false, result.Errors.Select(e => e.Description).ToArray()); } return(true, new string[] { }); }
public async Task <(bool Succeeded, string[] Errors)> CreateUserAsync(ApplicationUsers user, string roles, string password) { var result = await _userManager.CreateAsync(user, password); if (!result.Succeeded) { return(false, result.Errors.Select(e => e.Description).ToArray()); } user = await _userManager.FindByNameAsync(user.UserName); try { result = await _userManager.AddToRoleAsync(user, roles); } catch { throw; } if (!result.Succeeded) { return(false, result.Errors.Select(e => e.Description).ToArray()); } return(true, new string[] { }); }
public async Task <(bool, string[])> CreateUserAsync(ApplicationUsers user, IEnumerable <string> roles, string password) { var result = await userManager.CreateAsync(user, password); if (!result.Succeeded) { return(false, result.Errors.Select(e => e.Description).ToArray()); } user = await userManager.FindByNameAsync(user.UserName); try { result = await this.userManager.AddToRolesAsync(user, roles.Distinct()); } catch (Exception ex) { await DeleteUserAsync(user); throw; } if (!result.Succeeded) { await DeleteUserAsync(user); return(false, result.Errors.Select(e => e.Description).ToArray()); } return(true, new string[] { }); }
public void Create_New_Application_User() { string newUser = @"{ ""id"": 1, ""name"": ""Jody"", ""username"": ""Matty"", ""email"": ""*****@*****.**"", ""address"": { ""street"": ""Kulas Light"", ""suite"": ""Apt. 556"", ""city"": ""Gwenborough"", ""zipcode"": ""92998-3874"", ""geo"": { ""lat"": ""-37.3159"", ""lng"": ""81.1496"" } }, ""phone"": ""1-770-736-8031 x56442"", ""website"": ""hildegard.org"", ""company"": { ""name"": ""Romaguera-Crona"", ""catchPhrase"": ""Multi-layered client-server neural-net"", ""bs"": ""harness real-time e-markets"" } }"; var user = new API <ApplicationUsers>(); var url = user.SetUrl("users"); var request = user.CreatePostRequest(newUser); var response = user.GetResponse(url, request); ApplicationUsers content = user.GetContent <ApplicationUsers>(response); Assert.AreEqual("Jody", content.Name); }
public ApplicationUsers LoginUser(ApplicationUsers users) { try { var user = _context.ApplicationUsers.Where(a => a.UserName == users.UserName).FirstOrDefault(); if (user == null) { return(null); } else { var passwordKey = user.Pass; var password = user.Password; var resultDecrypt = PasswordSecurity.Decrypt(password, passwordKey); if (resultDecrypt == users.Password) { return(user); } } } catch (Exception ex) { } return(null); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUsers { 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); // 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("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
/// <summary> /// Use Dapper to call the data base and bring back the user account information /// </summary> /// <param name="input"></param> /// <returns>ApplicationUser</returns> public async Task <ApplicationUsers> UserLogin(UserLoginDatabaseInput input) { //Set up the DyanmicParameters object for Dapper var p = new DynamicParameters(); //Add the input params to the dynamic parameter p.Add("@p_UserName", input.UserName); p.Add("@p_UserPassword", input.Password); IEnumerable <ApplicationUsers> result; using (IDbConnection connection = new SqlConnection(_connectionString)) { result = await connection.QueryAsync <ApplicationUsers>("sp_UserLogin", p, commandType : CommandType.StoredProcedure); if (result.Count() == 0) { throw new InvalidLoginException("The user name or password was invalid"); } } ApplicationUsers applicationUser = result.FirstOrDefault(); return(applicationUser); }
public async Task <UserDto> Register(RegisterData data, ModelStateDictionary modelState) { var user = new ApplicationUsers { UserName = data.Username, Email = data.Email, PhoneNumber = data.PhoneNumber, }; var result = await userManager.CreateAsync(user, data.Password); if (result.Succeeded) { return(new UserDto { Id = user.Id, Username = user.UserName, }); } foreach (var error in result.Errors) { var errorKey = error.Code.Contains("Password") ? nameof(data.Password) : error.Code.Contains("Email") ? nameof(data.Email) : error.Code.Contains("UserName") ? nameof(data.Username) : ""; modelState.AddModelError(errorKey, error.Description); } return(null); }
public ActionResult Register(RegisterModel model) { var user = new ApplicationUsers(); user.Name = model.Name; user.Surname = model.Surname; user.UserName = model.Username; user.Email = model.Email; user.PhoneNumber = model.PhoneNumber; var result = userManager.Create(user, model.Password); if (result.Succeeded) { //User created //asign role to user if (roleManager.RoleExists("User")) { userManager.AddToRole(user.Id, "User"); } return(RedirectToAction("Login", "Account")); } return(View(model)); }
public async Task <CustomerViewModel> CreateCustomer(CustomerCreateModel customer) { ApplicationUsers user = new ApplicationUsers() { UserName = customer.Users.UserName, FullName = customer.Users.UserName }; var result = await _accountManager.CreateUserAsync(user, customer.Users.Roles, customer.Users.Password); if (result.Succeeded) { Customer customerByDB = new Customer() { Name = customer.Name, Code = customer.Code, Address = customer.Address, Discount = customer.Discount, User = await _accountManager.GetUserByNameAsync(user.UserName) }; _unitOfWork.Customers.Create(customerByDB); return(GetCustomersDBToViewModelById(customerByDB.Id)); } return(null); }
public ActionResult KayitOl(RegisterModel model) { if (ModelState.IsValid) { ApplicationUsers user = new ApplicationUsers(); var users = userManager.Users.Where(x => x.UserName.Contains(model.Name + "." + model.Surname)).ToList(); if (users != null && users.Count > 0) { user.UserName = model.Name + "." + model.Surname + "" + users.Count; } else { user.UserName = model.Name + "." + model.Surname; } user.Name = model.Name; user.Surname = model.Surname; string sifre = Utility.RastgeleSifre.RandomPassword(); var result = userManager.Create(user, sifre);//Şifre oluşturulcak rastgele if (result.Succeeded) { LoginModel loginUser = new LoginModel(); loginUser.Username = user.UserName; loginUser.Password = sifre; TempData["User"] = loginUser; return(RedirectToAction("Index", "User")); } } return(View()); }
public async Task <IActionResult> RegisterDoctor(AppDoctorModelVM model) { if (!ModelState.IsValid) { return(BadRequest(new { status = false, message = "Parameters sent are invalid" })); } try { UserInfoVM userInfo = new UserInfoVM(); var user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { userInfo.IsEmailConfirmed = user.EmailConfirmed; userInfo.IsPhoneConfirmed = user.PhoneNumberConfirmed; return(BadRequest(new { status = false, message = "You are already registered with this Email", userInfo })); } var applicationUser = new ApplicationUsers { UserName = model.Email, FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, Password = model.Password, ConfirmPassword = model.ConfirmPassword, PhoneNumber = model.PhoneNumber, DOB = model.DOB, Gender = model.Gender, SpecialityId = model.SpecialityId, StateId = model.StateId, LicenseNumber = model.LicenseNumber, RecordedAt = DateTime.Now }; var result = await _userManager.CreateAsync(applicationUser, model.Password); //add role await _userManager.AddToRoleAsync(applicationUser, GlobalVariables.isDoctor); if (!result.Succeeded) { return(BadRequest(new { status = false, message = result.Errors.First().Code })); } userInfo.IsEmailConfirmed = false; userInfo.IsPhoneConfirmed = false; return(Ok(new { status = true, message = "Registered Successfully", userInfo })); } catch (Exception ae) { return(BadRequest(new { status = false, message = ae.Message.ToString() })); } }
public async Task <IActionResult> RegisterPatient(AppPatientModelVM model) { if (!ModelState.IsValid) { return(Ok(new { status = false, message = "The parameters are not correct" })); } try { UserInfoVM userInfo = new UserInfoVM(); var user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { userInfo.IsEmailConfirmed = user.EmailConfirmed; userInfo.IsPhoneConfirmed = user.PhoneNumberConfirmed; return(BadRequest(new { status = false, message = "You are already registered with this email." })); } int otpCode = GlobalMethods.GenerateOTP(); var applicationUser = new ApplicationUsers { UserName = model.Email, FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, Password = model.Password, ConfirmPassword = model.ConfirmPassword, PhoneNumber = model.PhoneNumber, DOB = model.DOB, Gender = model.Gender, OTP = otpCode, StateId = model.StateId }; var result = await _userManager.CreateAsync(applicationUser, model.Password); //add role await _userManager.AddToRoleAsync(applicationUser, GlobalVariables.isPatient); if (!result.Succeeded) { return(BadRequest(new { status = false, message = result.Errors.First().Code })); } userInfo.IsEmailConfirmed = false; userInfo.IsPhoneConfirmed = false; return(BadRequest(new { status = true, message = "Registered successfully", userInfo })); } catch (Exception ae) { return(BadRequest(new { status = false, message = ae.Message.ToString() })); } }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new ApplicationUsers { UserName = Input.UserName, Email = Input.Email, PhoneNumber = Input.PhoneNumber }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { if (!await _roleManager.RoleExistsAsync(SD.AdminUser)) { await _roleManager.CreateAsync(new IdentityRole(SD.AdminUser)); } if (!await _roleManager.RoleExistsAsync(SD.User)) { await _roleManager.CreateAsync(new IdentityRole(SD.User)); } if (Input.IsAdmin) { await _userManager.AddToRoleAsync(user, SD.AdminUser); } else { await _userManager.AddToRoleAsync(user, SD.User); } _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); // remove these to avoid kicking out the current admin user's account after created a new one /*var callbackUrl = Url.Page( * "/Account/ConfirmEmail", * pageHandler: null, * values: new { userId = user.Id, code = code }, * protocol: Request.Scheme); * * await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", * $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); * * * // await _signInManager.SignInAsync(user, isPersistent: false); * // return LocalRedirect(returnUrl);*/ return(RedirectToAction("Index", "AdminUsers", new { area = "Admin" })); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public static void LogIn(ApplicationUsers user) { if (user != null) { loggedUser = user; LoggedInState = true; } }