/// <summary> /// Regenerates the identity callback function for cookie configuration (above). /// </summary> /// <param name="applicationUserManager">The application user manager.</param> /// <param name="applicationUser">The application user.</param> private static async Task<ClaimsIdentity> RegenerateIdentityCallback(ApplicationUserManager applicationUserManager, ApplicationUser applicationUser) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await applicationUserManager.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.UserName }; user.UserInfo = new ApplicationUserInfo { ApplicationUser = user }; Image defaultAvatar = new Image { Name = "defaultAvatar" }; user.UserInfo.Avatar = defaultAvatar; db.SaveChanges(); var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { db.SaveChanges(); await SignInAsync(user, isPersistent: false); return RedirectToAction("Index", "Home"); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return View(model); }
protected void CreateUser_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 //string code = manager.GenerateEmailConfirmationToken(user.Id); //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request); //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>."); signInManager.SignIn( user, isPersistent: false, rememberBrowser: false); using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions()) { String cartId = usersShoppingCart.GetCartId(); usersShoppingCart.MigrateCart(cartId, user.Id); } IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } }
public async Task<bool> Create([Bind(Include = "UserName,Email,EmailConfirmed,PasswordHash,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled")] AspNetUser aspNetUser) { if (ModelState.IsValid) { var user = new ApplicationUser(); user.AccessFailedCount = 0; user.Email = aspNetUser.Email.Trim(); user.EmailConfirmed = aspNetUser.EmailConfirmed; user.LockoutEnabled = aspNetUser.LockoutEnabled; user.LockoutEndDateUtc = aspNetUser.LockoutEndDateUtc; user.PhoneNumber = aspNetUser.PhoneNumber == null ? aspNetUser.PhoneNumber : aspNetUser.PhoneNumber.Trim(); user.PhoneNumberConfirmed = aspNetUser.PhoneNumberConfirmed; user.TwoFactorEnabled = aspNetUser.TwoFactorEnabled; user.UserName = aspNetUser.UserName.Trim(); try { // Use the password hash as actual password var res = await UserManager.CreateAsync(user, aspNetUser.PasswordHash); if (!res.Succeeded) { return false; } return true; } catch (Exception ex) { return false; } } return true; }
protected void CreateUser_Click(object sender, EventArgs e) { var manager = new UserManager(); var user = new ApplicationUser() { UserName = UserName.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { ApplicationUser newUser = manager.Find(UserName.Text, Password.Text); var sa = new StoredAccount(); sa.CreateNewAccount(newUser.Id,Email.Text); var returnUrl = Request.QueryString["ReturnUrl"]; IdentityHelper.SignIn(manager, user, isPersistent: false); if (returnUrl == null) { IdentityHelper.RedirectToReturnUrl("~/Game/User-Home.aspx", Response); } else { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } }
private void CreateAndLoginUser() { if (!IsValid) { return; } var manager = new UserManager(); var user = new ApplicationUser() { UserName = userName.Text }; IdentityResult result = manager.Create(user); if (result.Succeeded) { var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); return; } } AddErrors(result); }
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindByNameAsync(model.UserName); if(user == null) { user = new ApplicationUser { UserName = model.UserName, TotalCredits = AppSettingsConfig.StartCredits }; var result = await UserManager.CreateAsync(user); if (!result.Succeeded) { AddErrors(result); return View(model); } } await SignInManager.SignInAsync(user, false, false); return RedirectToLocal(returnUrl); }
public static ApplicationUser CreateUser(UserManager<ApplicationUser> userManager, string email, string firstName, string lastName, string password, bool lockOutEnabled) { var user = userManager.FindByName(email); if (user == null) { user = new ApplicationUser { UserName = email, Email = email, FirstName = firstName, LastName = lastName, EmailConfirmed = true }; try { userManager.Create(user, password); } catch (Exception ex) { Log4NetHelper.Log("Error creating Admin User", LogLevel.ERROR, "AspNetUser", 1, "none", ex); } userManager.SetLockoutEnabled(user.Id, lockOutEnabled); } return user; }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName}; try { var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInAsync(user, false); return RedirectToAction("Index", "Home"); } AddErrors(result); } catch (Exception) { //When no database, sometimes database creation fails. AddErrors(new IdentityResult("Database creation failed, please restart the application!")); return View(model); } } // If we got this far, something failed, redisplay form return View(model); }
public ActionResult Create([DataSourceRequest]DataSourceRequest request, UserAdministrationModel model) { if (model != null && this.ModelState.IsValid) { var newUser = new ApplicationUser { UserName = model.UserName, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, CreatedOn = DateTime.Now }; var password = string.IsNullOrEmpty(model.NewPassword) ? "123456" : model.NewPassword; this.userManager.Create(newUser, password); if (model.IsAdmin) { this.userManager.AddToRole(newUser.Id, ApplicationRoles.Admin); } if (model.IsArtist) { this.userManager.AddToRole(newUser.Id, ApplicationRoles.Artist); } if (model.IsDesigner) { this.userManager.AddToRole(newUser.Id, ApplicationRoles.Designer); } if (model.IsRegular) { this.userManager.AddToRole(newUser.Id, ApplicationRoles.Regular); } if (model.IsSeller) { this.userManager.AddToRole(newUser.Id, ApplicationRoles.Seller); } if (model.IsStudent) { this.userManager.AddToRole(newUser.Id, ApplicationRoles.Student); } if (model.IsTrainer) { this.userManager.AddToRole(newUser.Id, ApplicationRoles.Trainer); } model.Id = newUser.Id; model.NewPassword = string.Empty; return this.GridOperationObject(model, request); } return null; }
public async Task<ActionResult> Register(RegisterVm Model) { Tuple<RegisterVm, LoginVm> badModel; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Model.EmailReg, Email = Model.EmailReg }; IdentityUserClaim _claim = new Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim(); _claim.ClaimType = "FullName"; _claim.ClaimValue = Model.FullName; _claim.UserId = user.Id; user.Claims.Add(_claim); ViewBag.FullName = Model.FullName; ViewBag.Email = user.Email; Random random = new Random(DateTime.Now.Day); StringBuilder strBuilder = new StringBuilder("!164"); for (int i = 0; i < 3; i++) { strBuilder.Append((char)random.Next(65, 90)); strBuilder.Append((char)random.Next(97, 122)); } string temporaryPassword = strBuilder.ToString(); var result = await UserManager.CreateAsync(user, temporaryPassword); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmailAndChangePassword", "Init", new { userId = System.Web.HttpUtility.UrlEncode(user.Id), code = System.Web.HttpUtility.UrlEncode(code) }, protocol: Request.Url.Scheme); try { ViewBag.Logo = Url.Content("~/Content/images/init/Logo.png", true); ViewBag.ConfirmReference = callbackUrl; string textmail = ViewToString("emailConfirmation", null); await UserManager.SendEmailAsync(user.Id, "Confirm your account", textmail);//"Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); } catch (SmtpException e1) { await UserManager.DeleteAsync(user); ViewBag.UnsuccessfulError = e1.Message; ModelState.AddModelError("", "Не удалось создать пользователя. " + e1.Message); badModel = new Tuple<RegisterVm, LoginVm>(Model, new LoginVm()); return View("Welcome", badModel); } return View("RegisterConfirmationSent"); } else { ModelState.AddModelError("", "Не удалось создать пользователя. " + result.Errors.First()); } } // If we got this far, something failed, redisplay form badModel = new Tuple<RegisterVm, LoginVm>(Model, new LoginVm()); return View("Index", badModel); }
// Allow Initialization with an instance of ApplicationUser: public EditUserViewModel(ApplicationUser user) { this.UserName = user.UserName; this.FirstName = user.FirstName; this.LastName = user.LastName; this.Email = user.Email; }
public EntityBase SetCreated(ApplicationUser user) { CreatedOn = DateTime.Now; //CreatedBy = user; UpdatedOn = DateTime.Now; return this; }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.UserName }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); var service = new Service(); User register = new User(); register.Active = true; register.BirthYear = model.BirthYear; register.DisplayName = model.DisplayName; register.Email = model.Email; register.Gender = model.Gender; register.UserName = model.UserName; service.CreateUser(ref register); DisplayWelcomeMessage(register); return RedirectToAction("Index", "User"); } else { ModelState.AddModelError("UserName", "That username is already taken"); AddErrors(result); } } // If we got this far, something failed, redisplay form. return View(model); }
public virtual ActionResult Details(int? id, ApplicationUser currentUser) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } GameDefinitionDetailsViewModel gamingGroupGameDefinitionViewModel; try { var gameDefinitionSummary = _gameDefinitionRetriever.GetGameDefinitionDetails(id.Value, NUMBER_OF_RECENT_GAMES_TO_SHOW); gamingGroupGameDefinitionViewModel = _gameDefinitionTransformation.Build(gameDefinitionSummary, currentUser); } catch (KeyNotFoundException) { return new HttpNotFoundResult(); } catch (UnauthorizedAccessException) { return new HttpUnauthorizedResult(); } return View(MVC.GameDefinition.Views.Details, gamingGroupGameDefinitionViewModel); }
public void It_Sets_The_Basic_User_Information_For_The_Requested_User() { expectedApplicationUser = new ApplicationUser { Id = "some application user id", UserName = "******", Email = "some email address", UserGamingGroups = new List<UserGamingGroup> { new UserGamingGroup { GamingGroup = new GamingGroup() } }, Players = new List<Player>(), BoardGameGeekUser = new BoardGameGeekUserDefinition { Name = "bgg name", Id = 1 } }; var userQueryable = new List<ApplicationUser> { expectedApplicationUser, new ApplicationUser() }.AsQueryable(); autoMocker.Get<IDataContext>().Expect(mock => mock.GetQueryable<ApplicationUser>()).Return(userQueryable); var actualResult = autoMocker.ClassUnderTest.RetrieveUserInformation(expectedApplicationUser); Assert.That(actualResult.UserId, Is.EqualTo(expectedApplicationUser.Id)); Assert.That(actualResult.UserName, Is.EqualTo(expectedApplicationUser.UserName)); Assert.That(actualResult.Email, Is.EqualTo(expectedApplicationUser.Email)); Assert.That(actualResult.BoardGameGeekUser.Name, Is.EqualTo(expectedApplicationUser.BoardGameGeekUser.Name)); }
public async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser) { // Clear any partial cookies from external or two factor partial sign ins AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie); var userIdentity = await user.GenerateUserIdentityAsync(UserManager); if (rememberBrowser) { var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(user.Id); AuthenticationManager.SignIn( new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity, rememberBrowserIdentity); } else { AuthenticationManager.SignIn( new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity); } }
public ActionResult Create([Bind(Include = "ID,FirstName,LastName,Username")] Patient patient) { DBContext temp = new DBContext(); if (ModelState.IsValid) { if (db.Patients.Where(p=>p.Username == patient.Username).Count()==0) { ApplicationUser newUser = new ApplicationUser { Email = patient.Username, UserName = patient.Username }; ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); UserManager.Create(newUser, "Password1!"); var currentUser = UserManager.FindByName(patient.Username); UserManager.AddToRole(currentUser.Id, "Patient"); db.Patients.Add(patient); db.SaveChanges(); return RedirectToAction("PatientDoctor"); } else { return View("PatientExists"); } } return View(patient); }
internal void AddUserAndRole() { // access the application context and create result variables. Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; // create roleStore object that can only contain IdentityRole objects by using the ApplicationDbContext object. var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); // create admin role if it doesn't already exist if (!roleMgr.RoleExists("admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" }); } // create a UserManager object based on the UserStore object and the ApplicationDbContext object. // defines admin email account var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; IdUserResult = userMgr.Create(appUser, "Pa$$word1"); // If the new admin user was successfully created, add the new user to the "admin" role. if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "admin"); } }
internal void AddUserAndRole() { Models.ApplicationDbContext context = new Models.ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("administrator")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "******", }; IdUserResult = userMgr.Create(appUser, "1qaz2wsxE"); var user = userMgr.FindByName("administrator"); if (!userMgr.IsInRole(user.Id, "administrator")) { //userMgr.RemoveFromRoles(user.Id, "read", "edit"); IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator"); } }
public override UmcTrack GetTrackInfo(string url, ApplicationUser currentUser) { ISoundCloudConnector soundCloudConnector = new SoundCloudConnector(); string token = currentUser.ApplicationUserData.SoundcloudToken; //string token = "ssadad"; UmcTrack resultTrack = new SoundcloudTrack(); //var tokenLogin = soundCloudConnector.RefreshToken(clientId, clientSecret, token); //var newToken = tokenLogin.AccessToken; //var soundCloudClient = soundCloudConnector.Connect(new SCAccessToken {AccessToken = token}); var soundCloudClient = soundCloudConnector.UnauthorizedConnect(clientId, clientSecret); var track = soundCloudClient.Resolve.GetTrack(url); resultTrack.Url = url; resultTrack.Title = track.Title; resultTrack.Artist = track.User.UserName; resultTrack.Year = track.CreatedAt.Year.ToString(); resultTrack.InternalId = track.Id; return resultTrack; }
public override void SetUp() { base.SetUp(); expectedGamingGroup = new GamingGroup() { Id = currentUser.CurrentGamingGroupId }; autoMocker.Get<IDataContext>().Expect(mock => mock.Save(Arg<GamingGroup>.Is.Anything, Arg<ApplicationUser>.Is.Anything)) .Return(expectedGamingGroup); expectedPlayer = new Player(); autoMocker.Get<IPlayerSaver>().Expect(mock => mock.CreatePlayer( Arg<CreatePlayerRequest>.Is.Anything, Arg<ApplicationUser>.Is.Anything, Arg<bool>.Is.Anything)).Return(expectedPlayer); expectedUserGamingGroup = new UserGamingGroup { ApplicationUserId = currentUser.Id, GamingGroupId = expectedGamingGroup.Id }; autoMocker.Get<IDataContext>().Expect(mock => mock.Save<UserGamingGroup>(Arg<UserGamingGroup>.Is.Anything, Arg<ApplicationUser>.Is.Anything)) .Return(expectedUserGamingGroup); appUserRetrievedFromFindMethod = new ApplicationUser() { Id = currentUser.Id }; autoMocker.Get<IDataContext>().Expect(mock => mock.FindById<ApplicationUser>(Arg<ApplicationUser>.Is.Anything)) .Return(appUserRetrievedFromFindMethod); autoMocker.Get<IDataContext>().Expect(mock => mock.Save(Arg<ApplicationUser>.Is.Anything, Arg<ApplicationUser>.Is.Anything)) .Return(new ApplicationUser()); }
private static void AddAllUserCohortMeetings(ApplicationDbContext context, ApplicationUser user, int utcOffset, ref List<MeetingViewModel> meetingDtos) { var enrollmentsWithThisUser = context.Courses.SelectMany(u => u.Enrollments.Where(e => e.ApplicationUserId == user.Id)); foreach (var enrollment in enrollmentsWithThisUser) { //Get all meetings with this enrollment where its cohort has a meeting that is in the future Enrollment enrollment1 = enrollment; var cohortMeetings = context.Meetings.Where(m => m.CourseId == enrollment1.CourseId); foreach (var meeting in cohortMeetings) { var meetingToAdd = new MeetingViewModel { Id = meeting.Id, Title = meeting.Title, Start = DateTime.SpecifyKind(meeting.Start, DateTimeKind.Utc).AddMinutes(utcOffset), End = DateTime.SpecifyKind(meeting.End, DateTimeKind.Utc).AddMinutes(utcOffset), Description = meeting.Description, IsAllDay = meeting.IsAllDay, RecurrenceRule = meeting.RecurrenceRule, RecurrenceException = meeting.RecurrenceException, RecurrenceId = meeting.RecurrenceId, CourseId = meeting.CourseId, GtmUrl = meeting.GtmUrl }; meetingDtos.Add(meetingToAdd); } } }
//public static IEnumerable<MeetingViewModel> UserMeetingsTodayAll(ApplicationDbContext context, ApplicationUser user, Double utcOffset) //{ // var meetingDtos = new List<MeetingViewModel>(); // UserCohortMeetingsToday(context, user, utcOffset, ref meetingDtos); // MeetingsServices.UserPrivateMeetingsToday(context, user, utcOffset, ref meetingDtos); // return meetingDtos; //} private static void UserCohortMeetingsToday(ApplicationDbContext context, ApplicationUser user, Double utcOffset, ref List<MeetingViewModel> meetingDtos) { var enrollmentsWithThisUser = context.Courses.SelectMany(u => u.Enrollments.Where(e => e.ApplicationUserId == user.Id)); var localNow = DateTime.UtcNow.AddMinutes(utcOffset); var localTodayDate = localNow.ToShortDateString(); //foreach (var enrollment in enrollmentsWithThisUser) //{ // //Get all meetings with this enrollment where its cohort has a meeting that is in the future // var enrollment1 = enrollment; // //var cohortMeetings = context.Meetings.ToList().Where(m => m.CourseId == enrollment1.CourseId && m.Start.AddMinutes(utcOffset).ToShortDateString()==rightNow); // var cohortMeetings = context.Meetings.Where(m => m.CourseId == enrollment1.CourseId).OrderBy(m => m.Start); // foreach (var meeting in cohortMeetings) // { // if (meeting.Start.AddMinutes(utcOffset).ToShortDateString() == localTodayDate) // { // var meetingToAdd = new MeetingViewModel // { // Id = meeting.Id, // Title = meeting.Title, // Start = DateTime.SpecifyKind(meeting.Start, DateTimeKind.Utc).AddMinutes(utcOffset), // End = meeting.End.AddMinutes(utcOffset), // Description = meeting.Description, // IsAllDay = meeting.IsAllDay, // RecurrenceRule = meeting.RecurrenceRule, // RecurrenceException = meeting.RecurrenceException, // RecurrenceId = meeting.RecurrenceId, // CourseId = meeting.CourseId, // GtmUrl = meeting.GtmUrl // }; // meetingDtos.Add(meetingToAdd); // } // } //} }
// ************************ // Beer Postings Methods // ************************ public BeerPosting CreatePosting(ApplicationUser owner, BeerPosting _newbeerposting) { context.BeerPostings.Add(_newbeerposting); context.SaveChanges(); return _newbeerposting; }
public ActionResult Create([Bind(Include = "Id,Name,Address,Phone,Email,VendorId,AspId")] VendorUser vendorUser) { //if (ModelState.IsValid) //{ // db.VendorUsers.Add(vendorUser); // db.SaveChanges(); // return RedirectToAction("Index"); //} if (ModelState.IsValid) { var user = new ApplicationUser { UserName = vendorUser.Email, Email = vendorUser.Email }; var result = UserManager.Create(user, "Test@123"); var VendorUserId = db.AspNetUsers.Where(x => x.Email == vendorUser.Email).FirstOrDefault().Id; string userAspId = VendorUserId; vendorUser.AspId = userAspId; string loginId = User.Identity.GetUserId(); int vendorId = db.Vendors.Where(x => x.AspId == loginId).FirstOrDefault().VendorId; vendorUser.VendorId = vendorId; db.VendorUsers.Add(vendorUser); db.SaveChanges(); TempData["VendorId"] = vendorId; return RedirectToAction("Index"); } ViewBag.VendorId = new SelectList(db.Vendors, "VendorId", "Name", vendorUser.VendorId); return View(vendorUser); }
public async Task<ActionResult> Edit (string id, ApplicationUser applicationUser) { try { var user = await _userManager.FindByIdAsync(id); if(applicationUser.LockoutEnabled == true) { user.LockoutEnd = DateTime.UtcNow.AddYears(100); } else { user.LockoutEnd = DateTime.UtcNow; } user.LockoutEnabled = applicationUser.LockoutEnabled; await _userManager.UpdateAsync(user); return RedirectToAction("Index"); } catch (Exception) { ModelState.AddModelError(string.Empty, "Unable to save changes."); } return View(applicationUser); }
public ActionResult CreateAccount(NewUserModel model) { if (ModelState.IsValid) { ApplicationUserManager um = new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext())); var pass = StringHelper.RandomString(8, 10); var user = new ApplicationUser() { Id = Guid.NewGuid().ToString(), UserName = model.UserName, Email = model.Email, Created = DateTime.Now, LastLogin = null }; var result = um.Create(user, pass); if(result.Succeeded) { MailHelper.WelcomeSendPassword(user.UserName, user.Email, pass); return RedirectToAction("Index", "People"); } else { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } } return View(model); }
public ActionResult Index() { //cria um usuário de sistema. if (UserManager.FindByEmail("*****@*****.**") == null) { ApplicationUser systemUser = new ApplicationUser { UserName = "******", Email = "*****@*****.**", FirstName = "Smart Parking", LastName = "System", PhoneNumber = "(00) 00000-0000", UserType = UserType.Client }; var res = UserManager.Create(systemUser, "System12__"); if (res == null) { } } return View(); }
public ActionResult Index() { using (profiler.Step("Home/Index Action")) { var model = new HomeModel(); var UserId = User.Identity.GetUserId(); user = db.Users.Where(u => u.Id == UserId).SingleOrDefault(); if(user == null ) return RedirectToAction("Login", "Account", new { ReturnUrl = "/" }); var UnsolvedQuestions = user.GetUnsolvedQuestions(); if (user.QuizInfo != null && user.QuizInfo.HasCompletedQuiz) { model.FirstQuestionId = 0; } else { model.FirstQuestionId = UnsolvedQuestions.OrderBy(q => q.QuestionId).FirstOrDefault().QuestionId; } //model.FirstQuestionId = new eQuizContext().Questions.OrderBy(q => q.QuestionId).FirstOrDefault().QuestionId; var QuizStartTime = DateTime.Parse(db.Settings.SingleOrDefault(s => s.Name == "Quiz Start Time").Value); //ViewBag.QuizStartTime = db.Settings.SingleOrDefault(s => s.Name == "Quiz Start Time").Value; string EasternStandardTimeId = "Eastern Standard Time"; TimeZoneInfo ESTTimeZone = TimeZoneInfo.FindSystemTimeZoneById(EasternStandardTimeId); DateTime ESTDateTime = TimeZoneInfo.ConvertTimeFromUtc(QuizStartTime.ToUniversalTime(), ESTTimeZone); var TimeDiff = QuizStartTime.Subtract(ESTDateTime); model.QuizStartTime = QuizStartTime.ToString("yyyy-MM-ddTHH:mm:ss-04:00"); return View(model); } }
public async Task SendEmail(ApplicationUser user, CancellationToken cancellationToken) { var dto = _emailService.CreateTokenizedEmailDto(user.Email, user.RefreshToken, "register"); await _emailService.SendResetPasswordEmail(dto, cancellationToken); }
public void RemoveUser(ApplicationUser user) { db.Users.Remove(user); db.SaveChanges(); }
public void Add(ApplicationUser applicationUser) { context.Users.Add(applicationUser); }
private async Task <AuthenticationTicket> CreateTicketAsync(OpenIdConnectRequest request, ApplicationUser user, AuthenticationProperties properties = null) { var principle = await _signInManager.CreateUserPrincipalAsync(user); foreach (var claim in principle.Claims) { claim.SetDestinations( OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken ); } var ticket = new AuthenticationTicket(principle, properties, OpenIdConnectServerDefaults.AuthenticationScheme); if (!request.IsRefreshTokenGrantType()) { ticket.SetScopes(new[] { OpenIdConnectConstants.Scopes.OpenId, OpenIdConnectConstants.Scopes.Email, OpenIdConnectConstants.Scopes.Profile, OpenIdConnectConstants.Scopes.OfflineAccess, OpenIddictConstants.Scopes.Roles }.Intersect(request.GetScopes())); } return(ticket); }
public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); string role = Request.Form["rdUserRole"].ToString(); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, Name = Input.Name, City= Input.City, StreetAddress = Input.StreetAddress, State = Input.State, Phone = Input.Phone }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { if(!await _roleManager.RoleExistsAsync(SD.ManagerUser)) { await _roleManager.CreateAsync(new IdentityRole(SD.ManagerUser)); } if (!await _roleManager.RoleExistsAsync(SD.CustomerEndUser)) { await _roleManager.CreateAsync(new IdentityRole(SD.CustomerEndUser)); } if (!await _roleManager.RoleExistsAsync(SD.KitchenUser)) { await _roleManager.CreateAsync(new IdentityRole(SD.KitchenUser)); } if (!await _roleManager.RoleExistsAsync(SD.FrontDeskUser)) { await _roleManager.CreateAsync(new IdentityRole(SD.FrontDeskUser)); } if (role == SD.KitchenUser) { await _userManager.AddToRoleAsync(user, SD.KitchenUser); } else { if (role == SD.FrontDeskUser) await _userManager.AddToRoleAsync(user, SD.FrontDeskUser); else { if(role== SD.ManagerUser) { await _userManager.AddToRoleAsync(user, SD.ManagerUser); } else { await _userManager.AddToRoleAsync(user, SD.FrontDeskUser); await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } } } return RedirectToAction("Index","User",new {area = "Admin" }); //_logger.LogInformation("User created a new account with password."); //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); //var callbackUrl = Url.Page( // "/Account/ConfirmEmail", // pageHandler: null, // values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, // 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>."); //if (_userManager.Options.SignIn.RequireConfirmedAccount) //{ // RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }); //} //else //{ // await _signInManager.SignInAsync(user, isPersistent: false); //} } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return Page(); }
public ActionResult DisplayUserInfo() { var userID = User.Identity.GetUserId(); ApplicationUser applicationUser = UserManager.FindById(userID); return View(applicationUser); }
private IEnumerable <Claim> GetClaimsFromUser(ApplicationUser user) { var claims = new List <Claim> { new Claim(JwtClaimTypes.Subject, user.Id), new Claim(JwtClaimTypes.PreferredUserName, user.UserName) }; //if (!string.IsNullOrWhiteSpace(user.Name)) // claims.Add(new Claim("name", user.Name)); //if (!string.IsNullOrWhiteSpace(user.LastName)) // claims.Add(new Claim("last_name", user.LastName)); //if (!string.IsNullOrWhiteSpace(user.CardNumber)) // claims.Add(new Claim("card_number", user.CardNumber)); //if (!string.IsNullOrWhiteSpace(user.CardHolderName)) // claims.Add(new Claim("card_holder", user.CardHolderName)); //if (!string.IsNullOrWhiteSpace(user.SecurityNumber)) // claims.Add(new Claim("card_security_number", user.SecurityNumber)); //if (!string.IsNullOrWhiteSpace(user.Expiration)) // claims.Add(new Claim("card_expiration", user.Expiration)); //if (!string.IsNullOrWhiteSpace(user.City)) // claims.Add(new Claim("address_city", user.City)); //if (!string.IsNullOrWhiteSpace(user.Country)) // claims.Add(new Claim("address_country", user.Country)); //if (!string.IsNullOrWhiteSpace(user.State)) // claims.Add(new Claim("address_state", user.State)); //if (!string.IsNullOrWhiteSpace(user.Street)) // claims.Add(new Claim("address_street", user.Street)); //if (!string.IsNullOrWhiteSpace(user.ZipCode)) // claims.Add(new Claim("address_zip_code", user.ZipCode)); if (_userManager.SupportsUserEmail) { claims.AddRange(new[] { new Claim(JwtClaimTypes.Email, user.Email), new Claim(JwtClaimTypes.EmailVerified, user.EmailConfirmed ? "true" : "false", ClaimValueTypes.Boolean) }); } if (_userManager.SupportsUserPhoneNumber && !string.IsNullOrWhiteSpace(user.PhoneNumber)) { claims.AddRange(new[] { new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber), new Claim(JwtClaimTypes.PhoneNumberVerified, user.PhoneNumberConfirmed ? "true" : "false", ClaimValueTypes.Boolean) }); } return(claims); }
public IQueryable <DTO_PRO_DeTai> GetByRefer() { ApplicationUser user = UserManager.FindById(User.Identity.GetUserId()); return(BS_PRO_DeTai.get_PRO_DeTaiByRefer(db, PartnerID, user.StaffID, QueryStrings)); }
public IHttpActionResult RateARestaurant( [FromUri] int id, [FromBody] RatingBindingModel ratingModel) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } var restaurant = this.Data.Restaurants.Find(id); if (restaurant == null) { return(this.NotFound()); } var userId = this.User.Identity.GetUserId(); ApplicationUser user = null; if (userId != null) { user = this.Data.Users.Find(userId); } if (user == null) { return(this.Unauthorized()); } if (userId == restaurant.OwnerId) { return(this.BadRequest("User can't rate his own restaurant")); } var rating = this.Data.Ratings.All() .Where(rt => rt.RestaurantId == restaurant.Id && rt.UserId == userId) .FirstOrDefault(); if (rating == null) { rating = new Rating() { Stars = ratingModel.Stars, User = user, UserId = userId, Restaurant = restaurant, RestaurantId = restaurant.Id }; this.Data.Ratings.Add(rating); } else { rating.Stars = ratingModel.Stars; this.Data.Ratings.Update(rating); } this.Data.SaveChanges(); return(this.Ok()); }
public IHttpActionResult CreateNewRestaurant( [FromBody] RestaurantBindingModel restaurantModel) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } var town = this.Data.Towns.Find(restaurantModel.TownId); if (town == null) { return(this.BadRequest("Invalid town id")); } var userId = this.User.Identity.GetUserId(); ApplicationUser user = null; if (userId != null) { user = this.Data.Users.Find(userId); } if (user == null) { return(this.Unauthorized()); } var restaurant = new Restaurant() { Name = restaurantModel.Name, TownId = restaurantModel.TownId, Town = town, OwnerId = userId, Owner = user }; this.Data.Restaurants.Add(restaurant); this.Data.SaveChanges(); var townView = new TownViewModel() { Id = town.Id, Name = town.Name }; var restaurantView = new RestaurantViewModel() { Id = restaurant.Id, Name = restaurant.Name, Rating = null, Town = townView }; //var result = new System.Web.Mvc.ContentResult //{ // ContentType = "text/plain", // Content = JsonConvert.SerializeObject(restaurantView, new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }), // ContentEncoding = Encoding.UTF8 //}; return(this.CreatedAtRoute( "DefaultApi", new { id = restaurant.Id, controller = "restaurants" }, restaurantView)); }
public bool IsEmailConfirmed(ApplicationUser user) { return(UserManager.IsEmailConfirmedAsync(user).Result); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, CompanyId = Input.CompanyId, StreetAddress = Input.StreetAddress, City = Input.City, State = Input.State, PostalCode = Input.PostalCode, Name = Input.Name, PhoneNumber = Input.PhoneNumber, Role = Input.Role }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); if (!await _roleManager.RoleExistsAsync(StaticDetails.Role_Admin)) { await _roleManager.CreateAsync(new IdentityRole(StaticDetails.Role_Admin)); } if (!await _roleManager.RoleExistsAsync(StaticDetails.Role_Employee)) { await _roleManager.CreateAsync(new IdentityRole(StaticDetails.Role_Employee)); } if (!await _roleManager.RoleExistsAsync(StaticDetails.Role_User_Comp)) { await _roleManager.CreateAsync(new IdentityRole(StaticDetails.Role_User_Comp)); } if (!await _roleManager.RoleExistsAsync(StaticDetails.Role_User_Indi)) { await _roleManager.CreateAsync(new IdentityRole(StaticDetails.Role_User_Indi)); } if (user.Role == null) { await _userManager.AddToRoleAsync(user, StaticDetails.Role_User_Indi); } else { if (user.CompanyId > 0) { await _userManager.AddToRoleAsync(user, StaticDetails.Role_User_Comp); } await _userManager.AddToRoleAsync(user, user.Role); } var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, 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>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { if (user.Role == null) { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } else { // registering a user by an admin => // => keeping admin signed in and displaying a list of all the users return(RedirectToAction("Index", "User", new { Area = "Admin" })); } } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } Input = new InputModel() { CompanyList = _unitOfWork.Company.GetAll().Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }), RoleList = _roleManager.Roles.Where(u => u.Name != StaticDetails.Role_User_Indi).Select(x => x.Name).Select(i => new SelectListItem { Text = i, Value = i }) }; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, Name = Input.Name, City = Input.City, StreetAddress = Input.StreetAddress, State = Input.State, PostalCode = Input.PostalCode, PhoneNumber = Input.PhoneNumber }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, SD.CustomerEndUser); result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); //var userId = await _userManager.GetUserIdAsync(user); //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); //var callbackUrl = Url.Page( // "/Account/ConfirmEmail", // pageHandler: null, // values: new { area = "Identity", userId = userId, 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>."); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return(Page()); }
public bool IsHasPassword(ApplicationUser user) { return(UserManager.HasPasswordAsync(user).Result); }
private async Task <IEnumerable <Claim> > _getDefaultClaims(ApplicationUser user) { var result = await _signInManager.ClaimsFactory.CreateAsync(user); return(result.Claims); }
public static async Task InitializeDb(ApplicationDbContext context, UserManager <ApplicationUser> userManager, RoleManager <ApplicationRole> roleManager) { //context.Database.Migrate(); //context.Database.EnsureCreated(); // Add roles if (!await context.Roles.AnyAsync(r => string.Equals(r.Name, "System Administrator", StringComparison.OrdinalIgnoreCase))) { await roleManager.CreateAsync(new ApplicationRole { Name = "System Administrator", IsSysAdmin = true }); } // Add Admin user var adminUser = userManager.Users.FirstOrDefault(u => string.Equals(u.UserName, "admin", StringComparison.OrdinalIgnoreCase)); if (adminUser == null) { adminUser = new ApplicationUser { UserName = "******", Email = "admin", FirstName = "Super", LastName = "Admin" }; var result = await userManager.CreateAsync(adminUser, "P@ssword1"); if (result != IdentityResult.Success) { throw new Exception($"Unable to create '{adminUser.UserName}' account: {result}"); } } await userManager.SetLockoutEnabledAsync(adminUser, false); // Check AdminUserRoles var adminRoles = await userManager.GetRolesAsync(adminUser); if (!adminRoles.Any(r => string.Equals(r, "System Administrator"))) { await userManager.AddToRoleAsync(adminUser, "System Administrator"); } #region [STI Seed] var AJMPUserRolePermission = new string[] { "Administrator", "User" }; foreach (var rolePermission in AJMPUserRolePermission) { if (!await context.Roles.AnyAsync(r => string.Equals(r.Name, rolePermission, StringComparison.OrdinalIgnoreCase))) { var userRole = new ApplicationRole { Name = rolePermission, IsSysAdmin = false, CreatedBy = adminUser.Id }; await roleManager.CreateAsync(userRole); if (!await context.ApplicationPermission.AnyAsync(r => string.Equals(r.ApplicationPermission_Id, rolePermission, StringComparison.OrdinalIgnoreCase))) { var role = context.ApplicationRole.Where(x => x.Name == userRole.Name).FirstOrDefault(); if (role != null) { var permission = new ApplicationPermission { ApplicationPermission_Id = rolePermission, CreatedBy = adminUser.Id }; context.ApplicationPermission.Add(permission); await context.SaveChangesAsync(); if (!context.ApplicationRole_ApplicationPermission.Where(x => x.RoleId == userRole.Id && x.ApplicationPermissionId == permission.Id).Any()) { context.ApplicationRole_ApplicationPermission.Add(new ApplicationRole_ApplicationPermission { ApplicationPermissionId = permission.Id, RoleId = userRole.Id }); await context.SaveChangesAsync(); } } } } } #endregion }
public async Task AddPostComment(int postId, ApplicationUser author, Comment comment, int parentCommentId) { await _repository.AddPostComment(postId, Mapper.Map <DAL.Interface.DTO.ApplicationUser>(author), Mapper.Map <DAL.Interface.DTO.Comment>(comment), parentCommentId); }
public async Task <Like> GetPostLike(Post post, ApplicationUser user) { return(Mapper.Map <Like>(await _repository.GetPostLike(Mapper.Map <DAL.Interface.DTO.Post>(post), Mapper.Map <DAL.Interface.DTO.ApplicationUser>(user)))); }
private async Task <ActionResult> UpdateUserDetail(FarmerDetailViewModel farmerDetailViewModel, ApplicationUser user) { string phoneNumber = farmerDetailViewModel.PhoneNumber; user.PhoneNumber = phoneNumber; user.PhoneNumberConfirmed = true; await DbContext.SaveChangesAsync(); return(RedirectToAction("Index", "Manage")); }
/// <summary> /// Creates a new server. /// </summary> /// <param name="createServerDto">The creation request data.</param> /// <param name="owner">The user creating the server.</param> /// <returns>The result of the creation.</returns> public async Task <CreateServerResult> CreateServerAsync(CreateServerDto createServerDto, ApplicationUser owner) { var validationResult = AnnotationValidator.TryValidate(createServerDto); if (validationResult.Failed) { return(CreateServerResult.Fail(validationResult.Error.ToErrorList())); } var server = new Server(createServerDto.Name, createServerDto.PrivacyLevel, createServerDto.Description); var category = Category.CreateDefaultWelcomeCategory(server); server.Categories.Add(category); server.Members.Add(owner); var adminRole = ServerRole.CreateDefaultAdminRole(server); await _serverRepository.InsertAsync(server); await _serverRoleRepository.InsertAsync(adminRole); await _userRoleRepository.InsertAsync(new IdentityUserRole <Guid> { UserId = owner.Id, RoleId = adminRole.Id }); await _serverRepository.CommitAsync(); return(CreateServerResult.Ok(server)); }
private async Task SeedBlazorBoilerplateAsync() { ApplicationUser user = await _userManager.FindByNameAsync("user"); if (!_context.UserProfiles.Any()) { UserProfile userProfile = new UserProfile { UserId = user.Id, ApplicationUser = user, Count = 2, IsNavOpen = true, LastPageVisited = "/dashboard", IsNavMinified = false, LastUpdatedDate = DateTime.Now }; _context.UserProfiles.Add(userProfile); } if (!_context.Todos.Any()) { _context.Todos.AddRange( new Todo { IsCompleted = false, Title = "Test Blazor Boilerplate" }, new Todo { IsCompleted = false, Title = "Test Blazor Boilerplate 1", } ); } if (!_context.ApiLogs.Any()) { _context.ApiLogs.AddRange( new ApiLogItem { RequestTime = DateTime.Now, ResponseMillis = 30, StatusCode = 200, Method = "Get", Path = "/api/seed", QueryString = "", RequestBody = "", ResponseBody = "", IPAddress = "::1", ApplicationUserId = user.Id }, new ApiLogItem { RequestTime = DateTime.Now, ResponseMillis = 30, StatusCode = 200, Method = "Get", Path = "/api/seed", QueryString = "", RequestBody = "", ResponseBody = "", IPAddress = "::1", ApplicationUserId = user.Id } ); } _context.SaveChanges(); }
private async Task <AuthenticationTicket> CreateTicketAsync(OpenIdConnectRequest request, ApplicationUser user, AuthenticationProperties properties = null) { // Create a new ClaimsPrincipal containing the claims that // will be used to create an id_token, a token or a code. var principal = await _signInManager.CreateUserPrincipalAsync(user); // Create a new authentication ticket holding the user identity. var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), OpenIdConnectServerDefaults.AuthenticationScheme); ticket.SetResources(request.GetResources()); //if (!request.IsRefreshTokenGrantType()) //{ // Set the list of scopes granted to the client application. // Note: the offline_access scope must be granted // to allow OpenIddict to return a refresh token. ticket.SetScopes(new[] { OpenIdConnectConstants.Scopes.OpenId, OpenIdConnectConstants.Scopes.Email, OpenIdConnectConstants.Scopes.Profile, OpenIdConnectConstants.Scopes.OfflineAccess, OpenIddictConstants.Scopes.Roles }.Intersect(request.GetScopes())); //} // Note: by default, claims are NOT automatically included in the access and identity tokens. // To allow OpenIddict to serialize them, you must attach them a destination, that specifies // whether they should be included in access tokens, in identity tokens or in both. foreach (var claim in ticket.Principal.Claims) { // Never include the security stamp in the access and identity tokens, as it's a secret value. if (claim.Type == _identityOptions.Value.ClaimsIdentity.SecurityStampClaimType) { continue; } claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); } var identity = principal.Identity as ClaimsIdentity; if (!string.IsNullOrWhiteSpace(user.Email)) { identity.AddClaim(OpenIdConnectConstants.Claims.Email, user.Email, OpenIdConnectConstants.Destinations.IdentityToken); } // Add custom claims //if (!string.IsNullOrWhiteSpace(user.PhoneNumber)) // identity.AddClaim("phone", user.PhoneNumber, OpenIdConnectConstants.Destinations.IdentityToken); return(ticket); }
public IActionResult Edit(int id) { ApplicationUser user = _userManager.Users.FirstOrDefault(x => x.Id == id); return(View(user)); }
public async Task SaveUserAsync(ApplicationUser user) { _context.Users.Update(user); await _context.SaveChangesAsync(); }
private async Task <ApplicationUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable <Claim> claims) { // create a list of claims that we want to transfer into our store var filtered = new List <Claim>(); // user's display name var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value; if (name != null) { filtered.Add(new Claim(JwtClaimTypes.Name, name)); } else { var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value; var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value; if (first != null && last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last)); } else if (first != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first)); } else if (last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, last)); } } // email var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value; var user = new ApplicationUser { UserName = Guid.NewGuid().ToString(), Email = email }; var identityResult = await _userManager.CreateAsync(user); if (!identityResult.Succeeded) { throw new Exception(identityResult.Errors.First().Description); } if (filtered.Any()) { identityResult = await _userManager.AddClaimsAsync(user, filtered); if (!identityResult.Succeeded) { throw new Exception(identityResult.Errors.First().Description); } } identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider)); if (!identityResult.Succeeded) { throw new Exception(identityResult.Errors.First().Description); } return(user); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, 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>."); // If account confirmation is required, we need to show the link if we don't have a real email sender if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email })); } await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } ProviderDisplayName = info.ProviderDisplayName; ReturnUrl = returnUrl; return(Page()); }
// A method to add roles to the database that can be assigned to users private async Task CreateRoles(IServiceProvider serviceProvider) { // create RoleManager and UserManager Interfaces var RoleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >(); var UserManager = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >(); IdentityResult roleResult; //here in this line we are adding SystemAdmin Role var systemAdmin = await RoleManager.RoleExistsAsync("SystemAdmin"); if (!systemAdmin) { //here in this line we are creating SystemAdmin role and seed it to the database roleResult = await RoleManager.CreateAsync(new IdentityRole("SystemAdmin")); } //here in this line we are adding SystemAdmin Role var adminRole = await RoleManager.RoleExistsAsync("Admin"); if (!adminRole) { //here in this line we are creating admin role and seed it to the database roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin")); } // Creating a System Admin user ApplicationUser user = await UserManager.FindByEmailAsync("*****@*****.**"); if (user == null) { var newuser = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; var result = await UserManager.CreateAsync(newuser, "Admin0!"); user = await UserManager.FindByEmailAsync("*****@*****.**"); } await UserManager.AddToRoleAsync(user, "SystemAdmin"); // Create a manager role var managerRole = await RoleManager.RoleExistsAsync("Manager"); if (!managerRole) { //here in this line we are creating Manager role and seed it to the database roleResult = await RoleManager.CreateAsync(new IdentityRole("Manager")); } // var approverRole = await RoleManager.RoleExistsAsync("Approver"); if (!approverRole) { //here in this line we are creating Approver role and seed it to the database roleResult = await RoleManager.CreateAsync(new IdentityRole("Approver")); } var employeeRole = await RoleManager.RoleExistsAsync("Employee"); if (!employeeRole) { //here in this line we are creating Employee role and seed it to the database roleResult = await RoleManager.CreateAsync(new IdentityRole("Employee")); } }
public async Task <ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return(RedirectToAction("Login")); } if (loginInfo.Login.LoginProvider == "Facebook") { var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie); var access_token = identity.FindFirstValue("FacebookAccessToken"); var fb = new FacebookClient(access_token); dynamic myInfo = fb.Get("/me?fields=email"); loginInfo.Email = myInfo.email; } var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false })); case SignInStatus.Failure: default: var user = new ApplicationUser { UserName = loginInfo.DefaultUserName, Email = loginInfo.Email }; if (UserManager.FindByEmail(user.Email) == null) { var resultt = await UserManager.CreateAsync(user); if (resultt.Succeeded) { resultt = await UserManager.AddLoginAsync(user.Id, loginInfo.Login); if (resultt.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } } else { var resultt = await UserManager.AddLoginAsync(user.Id, loginInfo.Login); if (resultt.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } return(RedirectToLocal(returnUrl)); } //else //{ // ViewBag.ReturnUrl = returnUrl; // ViewBag.LoginProvider = loginInfo.Login.LoginProvider; // var newUser = new ApplicationUser { UserName = loginInfo.Email, Email = loginInfo.Email }; // var newResult = await UserManager.CreateAsync(newUser, "Nhy6&*()"); // await SignInManager.PasswordSignInAsync(loginInfo.Email, "Nhy6&*()", // false, shouldLockout: false); // return RedirectToAction("List", "Event"); //} //switch (result) //{ // case SignInStatus.Success: // return RedirectToLocal(returnUrl); // case SignInStatus.LockedOut: // return View("Lockout"); // case SignInStatus.RequiresVerification: // return RedirectToAction("SendCode", new {ReturnUrl = returnUrl, RememberMe = false}); // case SignInStatus.Failure: // default: // // If the user does not have an account, then prompt the user to create an account // ViewBag.ReturnUrl = returnUrl; // ViewBag.LoginProvider = loginInfo.Login.LoginProvider; // var newUser = new ApplicationUser { UserName = loginInfo.Email, Email = loginInfo.Email }; // var newResult = await UserManager.CreateAsync(newUser, "Nhy6&*()"); // await SignInManager.PasswordSignInAsync(loginInfo.Email, "Nhy6&*()", // false, shouldLockout: false); // return RedirectToLocal(returnUrl); // //return View("ExternalLoginConfirmation", // // new ExternalLoginConfirmationViewModel { UserName = loginInfo.ExternalIdentity.Name ,Email = loginInfo.Email }); //} }
public async Task <ActionResult> Edit(string id, string email, string password, double balance, string profiledescription, string avatar) { ApplicationUser user = await UserManager.FindByIdAsync(id); if (user != null) { user.Email = email; IdentityResult validEmail = await UserManager.UserValidator.ValidateAsync(user); if (!validEmail.Succeeded) { return(View("Error", validEmail.Errors)); } IdentityResult validPass = null; if (password != string.Empty) { validPass = await UserManager.PasswordValidator.ValidateAsync(password); if (validPass.Succeeded) { user.PasswordHash = UserManager.PasswordHasher.HashPassword(password); } else { return(View("Error", validPass.Errors)); } } user.Balance = balance; IdentityResult validBalance = await UserManager.UserValidator.ValidateAsync(user); if (!validBalance.Succeeded) { return(View("Error", validEmail.Errors)); } user.ProfileDescription = profiledescription; IdentityResult validDescription = await UserManager.UserValidator.ValidateAsync(user); if (!validDescription.Succeeded) { return(View("Error", validEmail.Errors)); } user.Avatar = avatar; IdentityResult validAvatar = await UserManager.UserValidator.ValidateAsync(user); if (Request.Files.Count > 0) { HttpPostedFileBase file = Request.Files[0]; //Check for image size if (file.ContentLength > 0 && file.ContentLength < 4000000) { if (file.ContentType.Contains("image/jpeg") || file.ContentType.Contains("image/png") || file.ContentType.Contains("image/gif")) { //Create random name & save with path string fileNameRandomExt = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); string uploadResult = Path.Combine(Server.MapPath("~/Content/uploads"), fileNameRandomExt); file.SaveAs(uploadResult); avatar = fileNameRandomExt; if (!validAvatar.Succeeded) { return(View("Error", validAvatar.Errors)); } } } } if ((validEmail.Succeeded && validPass == null && validBalance.Succeeded && validDescription.Succeeded && validAvatar.Succeeded) || (validEmail.Succeeded && password != string.Empty && validPass.Succeeded && validBalance.Succeeded && validDescription.Succeeded && validAvatar.Succeeded)) { IdentityResult result = await UserManager.UpdateAsync(user); if (result.Succeeded) { return(RedirectToAction("Index")); } else { return(View("Error", result.Errors)); } } } else { ModelState.AddModelError("", "User Not Found"); } return(View(user)); }
protected override void LoadTestData() { var htb = new Organization { Name = "Humanitarian Toolbox", LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png", WebUrl = "http://www.htbox.org", Campaigns = new List <Campaign>() }; var firePrev = new Campaign { Name = "Neighborhood Fire Prevention Days", ManagingOrganization = htb }; var queenAnne = new Event { Id = 1, Name = "Queen Anne Fire Prevention Day", Campaign = firePrev, CampaignId = firePrev.Id, StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(), EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(), Location = new Location { Id = 1 }, RequiredSkills = new List <EventSkill>(), }; var username1 = $"*****@*****.**"; var username2 = $"*****@*****.**"; var user1 = new ApplicationUser { UserName = username1, Email = username1, EmailConfirmed = true }; Context.Users.Add(user1); var user2 = new ApplicationUser { UserName = username2, Email = username2, EmailConfirmed = true }; Context.Users.Add(user2); htb.Campaigns.Add(firePrev); Context.Organizations.Add(htb); var task = new AllReadyTask { Event = queenAnne, Description = "Description of a very important task", Name = "Task # ", EndDateTime = DateTime.Now.AddDays(1), StartDateTime = DateTime.Now.AddDays(-3) }; queenAnne.Tasks.Add(task); Context.Events.Add(queenAnne); var taskSignups = new List <TaskSignup> { new TaskSignup { Task = task, User = user1 }, new TaskSignup { Task = task, User = user2 } }; Context.TaskSignups.AddRange(taskSignups); Context.SaveChanges(); }