public async Task <IActionResult> RegisterPost(RegisterVM registerVM) { if (ModelState.IsValid) { MyUser newUser = new MyUser() { FirstName = registerVM.FirstName, LastName = registerVM.LastName, Age = registerVM.Age, UserName = registerVM.Username, Email = registerVM.Email }; IdentityResult result = await _userManager.CreateAsync(newUser, registerVM.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } return(View(registerVM)); } } else { return(View(registerVM)); } return(RedirectToAction("Index", "Home")); //return View(); }
public async Task <ActionResult> UpdateNurse([FromBody] NurseUpdateModel nurseUM) { try { //update account(fullname, email, phone) MyUser user = await _userManager.FindByIdAsync(nurseUM.Id.ToString()); if (user == null) { return(NotFound()); } user = nurseUM.Adapt(user); user.DateUpdated = DateTime.Now; user.Nurse = nurseUM.Adapt(user.Nurse); user.Nurse.DateUpdated = DateTime.Now; user.Nurse.UpdatedByUserName = (await _userManager.GetUserAsync(User)).UserName; var success = await _userManager.UpdateAsync(user); if (success.Succeeded) { return(Ok()); } else { return(BadRequest(success.Errors)); } } catch (Exception e) { return(BadRequest(e.Message)); } }
public MyResponse <MyUser> OK() { MyUser m = new MyUser(); var r = MyResponse <MyUser> .Success(m); return(r); }
protected void Page_Load(object sender, EventArgs e) { userManager = IoCContainer.ServiceLocator.Resolve <IDbManager>(); if (this.Response.Cookies["Id"].Value != null) { MyUser u = userManager.GetUserById(Convert.ToInt32(this.Response.Cookies["Id"])); List <string> roles = userManager.GetUserRoles(u.Email); this.Session.Add("Email", txtEmail.Text); this.Session.Add("Password", txtPassword.Text); this.Session.Add("Role", roles); this.Session.Add("Name", u.Name + " " + u.Surname); this.Session.Add("Id", u.Id); this.Session.Add("CurrentUser", u); if (roles.Contains("Admin")) { Response.Redirect("~/Admin/Main.aspx"); } if (roles.Contains("Employer")) { Response.Redirect("~/Employer"); } if (roles.Contains("Employee")) { Response.Redirect("~/Employee/"); } } }
public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordBM model) { if (!ModelState.IsValid) { return(BadRequest()); } if (model.NewPassword.CompareTo(model.ConfirmNewPassword) != 0) { return(BadRequest()); // NewPassword and ConfirmPassword are valid but do not match } MyUser user = _context.Users.Cast <MyUser>().Single(x => x.UserName == HttpContext.User.Identity.Name); if (user == null) { return(BadRequest()); } var result = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword); if (!result.Succeeded) { return(BadRequest()); //current password is incorrect } return(Ok()); }
public ActionResult submitEvaluation(Evaluation evaluation) { if (HttpContext.User.Identity.IsAuthenticated) { MyUser user = HttpContext.User as MyUser; if (user != null) { evaluation.UID = user.UID; } evaluation.DataTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); db.Evaluations.Add(evaluation); db.SaveChanges(); evaluation.User = db.Users.FirstOrDefault(r => r.UID == evaluation.UID); evaluation.Order = db.Orders.FirstOrDefault(r => r.OID == evaluation.OID); EvaluationVM tmpEVM = new EvaluationVM(evaluation); if (Request.IsAjaxRequest()) { string jsonStr = PubFunction.BuildResult(tmpEVM); return(Content(jsonStr)); } else { return(View(tmpEVM)); } } else { string jsonStr = PubFunction.BuildResult("Err"); return(Content(jsonStr)); } }
public virtual async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new MyUser { UserName = model.Email, Email = model.Email, Voornaam = model.Voornaam, Achternaam = model.Achternaam, Geboortedatum = model.Geboortedatum, Postcode = model.Postcode, Beveiligingsvraag = model.Beveiligingsvraag, Antwoord = model.Antwoord }; 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>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Register(RegisterViewModel vm) { if (ModelState.IsValid) { MyUser user = new MyUser { UserName = vm.Username }; var result = await _userManagerService.CreateAsync(user, vm.Password); if (result.Succeeded) { await _userManagerService.SetEmailAsync(user, vm.Email); await _userManagerService.AddToRoleAsync(user, vm.Role); return(RedirectToAction("Index", "Home")); } else { foreach (var err in result.Errors) { ModelState.AddModelError("", err.Description); } } } return(View(vm)); }
protected void CreateUser_Click(object sender, EventArgs e) { this.CaptchaTextbox.Text = string.Empty; if (!Page.IsValid) return; var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var user = new MyUser() { UserName = UserName.Text, Email = EmailTexbox.Text, RegisterDate = DateTime.Now, LastLoginDate = DateTime.Now, AvatarUrl = "Default.jpg" }; var result = manager.Create(user, Password.Text); if (!result.Succeeded) return; manager.AddToRole(user.Id, "user"); var code = manager.GenerateEmailConfirmationToken(user.Id); var callbackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id.ToString(CultureInfo.InvariantCulture)); manager.SendEmail(user.Id, "فعال سازی حساب کاربری سایت www.DotNetToturials.org", "لطفا برای فعال سازی حساب کاربری خود بر روی لینک مقابل کلیک کنید <a href=\"" + callbackUrl + "\">here</a>."); ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Javascript", "Javascript:CompletedRegister();", true); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new MyUser { UserName = Input.Name, UserIdNumber = Input.UserIdNumber, City = Input.City }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public void Update(MyUser userParam, string currentPass = null, string password = null) { var user = _userManager.FindByIdAsync(userParam.UserName).Result; if (user == null) { throw new Exception("User not found"); } if (userParam.UserName != user.UserName) { // username has changed so check if the new username is already taken if (_userManager.Users.Any(x => x.UserName == userParam.UserName)) { throw new Exception("Username " + userParam.UserName + " is already taken"); } } // update user properties user.FirstName = userParam.FirstName; user.LastName = userParam.LastName; user.UserName = userParam.UserName; // update password if it was entered if (!string.IsNullOrWhiteSpace(password) && !string.IsNullOrWhiteSpace(currentPass)) { _userManager.ChangePasswordAsync(user, currentPass, password); } _userManager.UpdateAsync(user); }
public async Task <ActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { MyUser user = new MyUser { UserName = model.Email, Email = model.Email, Year = model.Year }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); if (model.Email.Split('@')[0] == "admin") { UserManager.AddToRole(user.Id, "admin"); } else { UserManager.AddToRole(user.Id, "user"); } if (result.Succeeded) { return(RedirectToAction("Login", "Account")); } else { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } } return(View(model)); }
/// <summary> /// 是否能够通过认证 /// </summary> /// <param name="userAccount"></param> /// <param name="password"></param> /// <returns></returns> public bool IsPass(string userAccount, string password) { if (String.IsNullOrEmpty(_table)) { _error = "没有认证的表"; return(false); } else { DataTable dt = getUserTable(userAccount, password); if (dt == null || dt.Rows.Count < 1) { _error = "获取用户信息出错(账户不存在或密码错误)"; return(false); } else if (dt.Columns.Contains("iflag") && !Constants.TRUE_ID.Equals(dt.Rows[0]["iflag"].ToString())) { _error = "用户不是[正常]状态"; return(false); } else { _myUser = new MyUser(dt.Rows[0]["id"].ToString(), password, ""); setUserApd(_myUser, dt); return(true); } } }
// GET: Login public ActionResult Index(MyUser us) { us.AddressLegal = new Company.Register.Lib.Model.Address() { CityId = 1, ContryId = 3, House = "76", Street = "kkkk" }; us.AddressPhysical = new Company.Register.Lib.Model.Address() { CityId = 1, ContryId = 3, House = "76", Street = "kkkk" }; us.BankDetails[0] = new BankDetail() { AccountNumber = "", Bik = "", CurrencyId = 1 }; us.ContactNumbers[0] = new Company.Register.Lib.Model.Phone() { PhoneCode = "777", PhoneNumber = "77777777", PhoneTypeId = 1, СountryСode = "7" }; if (ModelState.IsValid) { TempData.Add("User", us); return(RedirectToAction("Success")); } else { return(View()); } }
public static void SearchAgentsEmployee(IDbManager manager) { List <MySearchAgent> agents = manager.GetSearchAgents(); Console.WriteLine("SearchAgents!"); for (int i = 0; i < agents.Count; i++) { List <MyVacancy> results = manager.FindVacancies(agents[i].Request, ""); if (results.Count > 0) { MyUser u = manager.GetUserById(agents[i].UserId); manager.FilterVacancies(results, u.Id); if (results.Count > 0) { for (int j = 0; j < results.Count; j++) { MailService.SendMessage(u.Email, @"It seems that we found nice vacancy for you :)" + Environment.NewLine + "Header: " + results[j].ProfessionName + Environment.NewLine + "More: localhost:35235/Home/Search/" + results[j].Id); manager.AddSearchResult(agents[i].Id, results[j].Id); Console.WriteLine("To: " + u.Email); Console.WriteLine(@"It seems that we found nice vacancy for you :)" + Environment.NewLine + "Header: " + results[j].ProfessionName + Environment.NewLine + "More: localhost:35235/Home/Search/" + results[j].Id); Console.WriteLine("----------------------------------------------------------------"); } } } } }
public ActionResult Success() { MyUser user = (MyUser)TempData["User"]; ViewBag.Message = CompanyRegisterService.RegisterContractors((UserAccount)user); return(View()); }
public static void SearchAgentsEmployer(IDbManager manager) { List <MySearchAgentEmployer> agentsEmployer = manager.GetSearchAgentsEmployer(); Console.WriteLine("SearchAgentEmployer!"); for (int i = 0; i < agentsEmployer.Count; i++) { List <MyUser> results = manager.FindResumes(agentsEmployer[i].Request, ""); if (results.Count > 0) { MyUser u = manager.GetUserById(agentsEmployer[i].UserId); manager.FilterResumes(results, u.Id); if (results.Count > 0) { for (int j = 0; j < results.Count; j++) { MailService.SendMessage(u.Email, @"It seems that we found nice resume for you :)" + Environment.NewLine + "Header: " + manager.GetUserDetailById(results[j].UserDetails).Header + Environment.NewLine + "More: localhost:35235/Employer/Resume/" + results[j].Id); manager.AddSearchResultEmployer(agentsEmployer[i].Id, results[j].Id); Console.WriteLine("To: " + u.Email); Console.WriteLine(@"It seems that we found nice resume for you :)" + Environment.NewLine + "Header: " + manager.GetUserDetailById(results[j].UserDetails).Header + Environment.NewLine + "More: localhost:35235/Employer/Resume/" + results[j].Id); Console.WriteLine("----------------------------------------------------------------"); } } } } }
// GET: Projects public async Task <IActionResult> Index() { var currentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier); MyUser currentUser = await _userManager.FindByIdAsync(currentUserId); var roles = await _userManager.GetRolesAsync(currentUser); IList <Project> projects = new List <Project>(); if (roles.Contains("Admin")) { projects = await _context.Projects.Include(p => p.OwnerDept).ToListAsync(); } else if (roles.Contains("Manager")) { projects = await _context.DepartmentProjects .Include(dp => dp.Project) .Include(dp => dp.Project.OwnerDept) .Where(dp => dp.DepartmentId == currentUser.DepartmentId) .Select(dp => dp.Project) .ToListAsync(); } return(View(projects)); }
public JsonResult SignUp(string name, string password) { var judge = "1"; MyUser.AddUser(name, password); return(Json(judge, JsonRequestBehavior.AllowGet)); }
public async Task <IActionResult> DeleteAccount([FromBody] LoginBM credentials) { //check if username and password are valid strings: if (!ModelState.IsValid) { return(BadRequest()); } MyUser user = _context.Users.Cast <MyUser>().Single(x => x.UserName == HttpContext.User.Identity.Name); if (user == null) { return(BadRequest()); } //check if credentials are correct: if (!(await _userManager.CheckPasswordAsync(user, credentials.Password))) { return(Unauthorized()); } var result = await _userManager.DeleteAsync(user); if (!result.Succeeded) { return(BadRequest()); } return(Ok()); }
async void Change_username_btn_Clicked(System.Object sender, System.EventArgs e) { var user = new MyUser(); var newUsername = New_username_entry.Text; bool usernameOk; var authProvider = new FirebaseAuthProvider(new FirebaseConfig(WebAPIKey)); void UsernameValidation() { //deve contenere tra i 6 e i 18 caratteri alfanumerici var userPattern = "[A-Za-z][A-Za-z0-9._]{5,17}"; if (newUsername != null) { if (Regex.IsMatch(newUsername, userPattern)) { usernameOk = true; LabelUserError.TextColor = Color.Transparent; } else { usernameOk = false; LabelUserError.TextColor = Color.Red; } } else { usernameOk = false; LabelUserError.TextColor = Color.Red; } } UsernameValidation(); if (usernameOk) { try { //This is the saved firebaseauthentication that was saved during the time of login var savedfirebaseauth = JsonConvert.DeserializeObject <Firebase.Auth.FirebaseAuth>(Preferences.Get("MyLoginToken", "")); //Here we are Refreshing the token var RefreshedContent = await authProvider.RefreshAuthAsync(savedfirebaseauth); Preferences.Set("MyLoginToken", JsonConvert.SerializeObject(RefreshedContent)); //Cambio password utente await authProvider.UpdateProfileAsync(savedfirebaseauth.FirebaseToken, newUsername, ""); await App.Current.MainPage.DisplayAlert("Success.", "New Username set correctly.", "Ok"); await Navigation.PushAsync(new LoginPage()); } catch (Exception ex) { Console.WriteLine(ex.Message); await App.Current.MainPage.DisplayAlert("Ops... Something went wrong.", "Try to logout and log back in.", "Ok"); } } }
public ActionResult DeleteConfirmed(int id) { MyUser myUser = db.MyUsers.Find(id); db.MyUsers.Remove(myUser); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult ChangeUserInfo(string message = "") { var dataAcc = new DataAccess(); MyUser user = dataAcc.GetUserInfo((string)Session["AccountName"]); ViewData["Message"] = message; return(View("ChangeUserInfo", user)); }
public void Should_calculate_name() { var user = new MyUser(); var name = sut.GetStreamName(typeof(MyUser), id); Assert.Equal($"myUser-{id}", name); }
public ActionResult ChangeInfo(MyUser user) { user.Username = (string)Session["AccountName"]; var dataAcc = new DataAccess(); dataAcc.ChangeUserInfo(user); return(RedirectToAction("ChangeUserInfo", new { message = "修改用户信息成功!" })); }
public int LogInUser(MyUser myUser) { if (myUser == null) { return(0); } return(ContentProcessor.LogInUser(myUser)); }
public int SaveUser(MyUser myUser) { if (myUser == null) { return(0); } return(ContentProcessor.RegisterNewUser(myUser)); }
private static MyUser ReduceUser(MyUser oldUser, object action) { if (action is UpdateAction a && oldUser.Equals(a.userToUpdate)) { return(a.newUserValues); } return(oldUser); }
public void ExchangeInfo() { // called from Host ... Ag.LogStartWithStr(2, mName + " ExchangeInfo Emit ... \t\t\t\t <<< Action :: GameMsg >>>"); SendGameMsg(MyUser.ToNodeAmUser()); Ag.LogString(mName + " ExchangeInfo Emit ... \t\t\t\t <<< Done >>>"); }
public async Task <IdentityResult> UpdatePassword(string password) { MyUser userAuth = await FindUserAuthAsync(); string resetToken = await _userManager.GeneratePasswordResetTokenAsync(userAuth); return(await _userManager.ResetPasswordAsync(userAuth, resetToken, password)); }
//Проверка данных юзера. Если есть в базе и активен, получаем его номер. Если нет - 0 public static int LogInUser(MyUser myUser) { if (myUser == null || myUser.Login.Length > 10 || myUser.Password.Length > 10 || myUser.Login.Length == 0 || myUser.Password.Length == 0) { return(0); } return(LoginRepository.CheckUser(myUser)); }
public Family( String Name, MyUser Father, MyUser Mother, MyUser Gopher ) : base() { this.Name = Name; this.Father = Father; this.Mother = Mother; this.Gopher = Gopher; this.Children = new Collection<MyUser>(); this.PSite = new Collection<MyUser>(); }
public async Task<ActionResult> Index(UserViewModel model) { if (ModelState.IsValid) { var user = new MyUser() { UserName = model.UserName, EmailAddress = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { return RedirectToAction("AccountList"); } else { AddErrorsFromResult(result); } } return View(model); }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new MyUser() { UserName = model.UserName }; user.HomeTown = model.HomeTown; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToAction("Index", "Home"); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return View(model); }
public async Task<ActionResult> Create(RegisterViewModel userViewModel, string RoleId) { if (ModelState.IsValid) { var user = new MyUser(); user.UserName = userViewModel.UserName; user.HomeTown = userViewModel.HomeTown; var adminresult = await UserManager.CreateAsync(user, userViewModel.Password); //Add User Admin to Role Admin if (adminresult.Succeeded) { if (!String.IsNullOrEmpty(RoleId)) { //Find Role Admin var role = await RoleManager.FindByIdAsync(RoleId); var result = await UserManager.AddToRoleAsync(user.Id, role.Name); if (!result.Succeeded) { ModelState.AddModelError("", result.Errors.First().ToString()); ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Id", "Name"); return View(); } } } else { ModelState.AddModelError("", adminresult.Errors.First().ToString()); ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name"); return View(); } return RedirectToAction("Index"); } else { ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name"); return View(); } }
public async Task<ActionResult> Create(RegisterViewModel userViewModel, string RoleId) { if (ModelState.IsValid) { var user = new MyUser(); user.UserName = userViewModel.UserName; user.HomeTown = userViewModel.HomeTown; var adminresult = await IdentityManager.Users.CreateLocalUserAsync(user, userViewModel.Password, CancellationToken.None); //Add User Admin to Role Admin if (adminresult.Success) { if (!String.IsNullOrEmpty(RoleId)) { var result = await IdentityManager.Roles.AddUserToRoleAsync(user.Id, RoleId, CancellationToken.None); if (!result.Success) { ModelState.AddModelError("", result.Errors.First().ToString()); ViewBag.RoleId = new SelectList(await context.Roles.ToListAsync(), "Id", "Name"); return View(); } } } else { ModelState.AddModelError("", adminresult.Errors.First().ToString()); ViewBag.RoleId = new SelectList(await context.Roles.ToListAsync(), "Id", "Name"); return View(); } return RedirectToAction("Index"); } else { ViewBag.RoleId = new SelectList(await context.Roles.ToListAsync(), "Id", "Name"); return View(); } }
private void CreateAndLoginUser() { if (!IsValid) return; var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var externalIdentity = HttpContext.Current.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); var firstOrDefault = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email); if (firstOrDefault == null) return; var emailClaim = firstOrDefault.Value; var user = new MyUser { UserName = ExternalRegisterUserName.Text, Email = emailClaim, LastLoginDate = DateTime.Now, RegisterDate = DateTime.Now, AvatarUrl = "Default.jpg", EmailConfirmed = true }; var result = manager.Create(user); if (result.Succeeded) { manager.AddToRole(user.Id, "user"); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { RedirectOnFail(); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { IdentityHelper.SignIn(manager, user, false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); return; } } AddErrors(result); }
public UserView(MyUser User) : base(Guid.Parse(User.Id)) { this.Roles = new Collection<RoleView>(); foreach(var role in User.Roles) { this.Roles.Add(new RoleView(role)); } this.Fee = User.Fee; this.FeePaid = User.FeePaid; this.Personal = new PersonalView( User.Personal ); this.School = new SchoolView( User.School ); this.Medical = new MedicalView( User.Medical); this.Religion = new ReligionView( User.Religion); this.Emergency = new EmergencyView( User.Emergency); this.Transportation = new TransportationView( User.Transportation); this.Staff = new StaffView(User.Staff); this.Retreater = User.Retreater; this.RetreaterPending = User.RetreaterPending; this.Staffer = User.Staffer; this.StafferPending = User.StafferPending; this.Position = User.Position; if(User.ApplicationStamp != null) this.ApplicationStamp = User.ApplicationStamp; }
private async Task SignInAsync(MyUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); AuthenticationManager.SignIn( new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager)); }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new MyUser { UserName = model.Email, Email = model.Email, }; //user.Roles.Add(new MyUserRole { UserId = 1, RoleId = 2 }); var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await UserManager.AddToRoleAsync(user.Id, "admin"); await SignInAsync(user, 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>"); SendMadrillEmail(model.Email, model.Password); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new MyUser { 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) { await SignInAsync(user, 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); // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link"); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task SignIn(RegisterExternalBindingModel model) { //Check Model State if(!ModelState.IsValid) { //If Model State is not Valid, call error on Caller. Clients.Caller.error("Invalid Model: " + ModelState); } else { //Else, attempt logging the user try { //Find the User using the Log In Information var user = await UserManager.FindAsync( new UserLoginInfo( "microsoft", model.ExternalAccessToken ) ); //If User and Login exists, return the Token. if(user != null) { Clients.Caller.token(user.Id); } else { //Else, the User will be created. user = new MyUser { //UserName just needs to be unique. We really want an email address. UserName = model.Id, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Profile = new Profile() }; //The External Login is Added to the user user.Logins.Add(new IdentityUserLogin { LoginProvider = "microsoft", ProviderKey = model.ExternalAccessToken }); //Save the new User to the Database. IdentityResult result = await UserManager.CreateAsync( user ); //Check to see if User was successfully saved if(result.Succeeded) { //If User was saved, return the Token. Clients.Caller.token( user.Id ); } else { //Else, something went wrong with registering user. Abort operation and call error method on Caller. Clients.Caller.error("Registration Failed"); } } } //For Entity Validation Exception Errors, output the validation errors. catch ( DbEntityValidationException error ) { string output = "Exception Occurred: " + error.Message + ":"; //Return all error messages to error method on Caller. foreach ( var validationErrors in error.EntityValidationErrors ) { foreach ( var validationError in validationErrors.ValidationErrors ) { output += "Property: " + validationError.PropertyName + ", Error: " + validationError.ErrorMessage + " ------"; } } Clients.Caller.error( output ); } //Catch all other Exceptions to avoid silent failure catch ( Exception error ) { string output = "Exception Occurred: " + error.Message + " : "; while(error.InnerException != null) { output += "Inner Exception: " + error.InnerException.Message; error = error.InnerException; } //Return all error messages to error method on Caller. Clients.Caller.error( output ); } } }
public async Task<ActionResult> Register(RegisterAdminViewModel model) { if (ModelState.IsValid) { var user = new MyUser {Id = "admin", UserName = model.Email, Email = model.Email, Name = model.Email }; var result = UserManager.Create(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); result = await UserManager.AddToRoleAsync(user.Id, "Admin"); return RedirectToAction("Main", "Admin"); } } return View("~/Views/Auth/RegisterAdmin.cshtml", model); }
private async Task<bool> RegisterUser(RegisterUserModel model) { MyUser newUser = new MyUser { Id = model.Object_id, Email = model.Email, UserName = model.Login, Name = model.Name, }; var createResult = await UserManager.CreateAsync(newUser); if(createResult.Succeeded) { if(model.RegisterType == AuthType.Facebook || model.RegisterType == AuthType.Twitter) { foreach(Claim claim in model.UserClaims) { createResult = UserManager.AddClaim(newUser.Id, claim); } createResult = UserManager.AddLogin(newUser.Id, model.LoginProvider); } createResult = UserManager.AddToRole(newUser.Id, "User"); return true; } return false; }
private async Task SignInAsync(MyUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); }
private int AddUser(UserEditViewModel userDetail) { var user = new MyUser() { UserName = userDetail.UserName, IPAddress = Request.ServerVariables["REMOTE_ADDR"], BrowserInfo = Request.Browser.Type, Email = userDetail.Email, DateRegistered = DateTime.Now }; using (var userManager = new UserManager<MyUser, long>( new UserStore<MyUser, MyRole, long, MyLogin, MyUserRole, MyClaim>(new ApplicationDbContext()))) { var result = userManager.Create(user, userDetail.Password); if (result == IdentityResult.Success) { user = userManager.FindByName(userDetail.UserName); _userRepository.AssignStartupUserPreferenceTableColumns((int)user.Id); } } return (int)user.Id; }
private bool SetCurrentUser(AuthType authType ,MyUser user, string access_token = null, string access_token_secret = null) { try { if (authType == AuthType.Facebook) Repository.UpdateClaim("FacebookAccessToken", access_token, user.Id); if (authType == AuthType.Twitter) { Repository.UpdateClaim("TwitterAccessToken", access_token, user.Id); Repository.UpdateClaim("TwitterAccessTokenSecret", access_token_secret, user.Id); } return true; } catch { return false; } }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { // Create a local login before signing in the user var user = new MyUser(); user.UserName = model.UserName; user.HomeTown = model.HomeTown; var result = await IdentityManager.Users.CreateLocalUserAsync(user, model.Password); if (result.Success) { await IdentityManager.Authentication.SignInAsync(AuthenticationManager, user.Id, isPersistent: false); return RedirectToAction("Index", "Home"); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var user = new MyUser(); user.UserName = model.UserName; IdentityResult result = await IdentityManager.Authentication.CreateAndSignInExternalUserAsync(AuthenticationManager,user); if (result.Success) { return RedirectToLocal(returnUrl); } else { AddErrors(result); } } ViewBag.ReturnUrl = returnUrl; return View(model); }
/// <summary> /// Funtion that retrieves the users from the database and fills <see cref="Users"/>. /// </summary> public void FillUserList() { Users.Clear(); foreach (Microsoft.SqlServer.Management.Smo.Database db in server.Databases) { if (!db.Name.Contains("_db")) continue; //Run the EnumLoginMappings method and return details of database user-login mappings to a DataTable object variable. DataTable d; d = db.EnumLoginMappings(); foreach (DataRow r in d.Rows) { MyUser myUser = new MyUser { Database = db.Name }; foreach (DataColumn c in r.Table.Columns) { switch (c.ColumnName) { case "UserName": { myUser.UserName = (string)r[c]; break; } case "LoginName": { myUser.LoginName = (string)r[c]; break; } default: break; } } if (!myUser.LoginName.Contains("admin")) Users.Add(myUser); } } }
public async Task<IHttpActionResult> LogInExternal(RegisterExternalBindingModel model) { if(!ModelState.IsValid) { return BadRequest( ModelState ); } if(User.Identity.IsAuthenticated == true) { if(User.Identity.Name == model.Email) { return Ok("Already Authenticated"); } else { return Unauthorized(); } } else { try { var user = await UserManager.FindAsync(new UserLoginInfo("microsoft", model.ExternalAccessToken)); if( user != null) { //Return Token (GUID of User) return Ok(user.Id); } else { user = new MyUser { UserName = model.Id, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName }; user.Logins.Add( new IdentityUserLogin { LoginProvider = "microsoft", ProviderKey = model.ExternalAccessToken } ); IdentityResult result = await UserManager.CreateAsync( user ); IHttpActionResult errorResult = GetErrorResult( result ); if ( errorResult != null ) { return errorResult; } //Return Token (GUID of User) return Ok( user.Id ); } } catch(Exception error) { return BadRequest(error.Message); } } }
public async Task<ActionResult> Register(RegisterViewModel model) { string mail; string splitmail; if (ModelState.IsValid) { ValidateModel(model); mail = model.Email; splitmail = mail.Split('@')[1]; if(splitmail.Equals("ap.be")) { var user = new MyUser() { UserName = model.UserName }; user.Email = mail; var result = await UserManager.CreateAsync(user, model.Password); string adminEmail = ConfigurationManager.AppSettings["AdminEmail"].ToString(); if (result.Succeeded) { String url = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); if (!Request.ApplicationPath.TrimEnd('/').Equals("")) { url += Request.ApplicationPath.TrimEnd('/'); } UserManager.AddToRole(user.Id, "Docent"); var mailUser = UserManager.FindByName(model.UserName); dynamic email = new Email("Activate"); email.Url = url; email.To = mailUser.UserName; email.From = adminEmail; email.UserName = mailUser.UserName; email.UserId = mailUser.Id; email.ConfirmationToken = UserManager.GetConfirmationToken(mailUser.Id); email.Send(); //Don't log in, activate account first //await SignInAsync(user, isPersistent: false); return RedirectToAction("Activate"); } else { AddErrors(result); } } else { ModelState.AddModelError("", "Foutieve email"); } } // 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 MyUser { UserName = model.UserName, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // Add UserDetails (connection with User [FK]) user.AddUserDetails(model.FirstName, model.LastName); user.AddRole("User"); 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", "Auth", 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", new { area = "" }); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
private async Task SignInAsync( MyUser user, bool isPersistent ) { isPersistent = false; AuthenticationManager.SignOut( DefaultAuthenticationTypes.ExternalCookie ); var identity = await UserManager.CreateIdentityAsync( user, DefaultAuthenticationTypes.ApplicationCookie ); var properties = new AuthenticationProperties() { IsPersistent = isPersistent }; //properties.ExpiresUtc = new DateTimeOffset( FormsAuthentication.Timeout.Ticks, new TimeSpan( DateTime.Now.Ticks - DateTime.UtcNow.Ticks ) ); AuthenticationManager.SignIn( properties, identity ); FormsAuthentication.SetAuthCookie( user.UserName, isPersistent ); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new MyUser() { UserName = model.UserName }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }