protected override IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state) { this.CurrentUser = this.users .GetUser(requestContext.HttpContext.User.Identity.Name); return base.BeginExecute(requestContext, callback, state); }
protected void CreateUser_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var user = new User() { 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>."); Notifier.AddSuccessMessage("Registration successful!"); signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { //ErrorMessage.Text = result.Errors.FirstOrDefault(); Notifier.AddErrorMessage(result.Errors.FirstOrDefault()); } }
public ActionResult Users_Create([DataSourceRequest]DataSourceRequest request, UserAdminViewModel model) { if (ModelState.IsValid && model != null) { //var movie = Mapper.Map<Movie>(model); var user = new User() { FirstName = model.FirstName, LastName = model.LastName, Avatar = model.Avatar, BirthDate = model.BirthDate, Gender = model.Gender, About = model.About, CreatedOn = model.CreatedOn, PreserveCreatedOn = model.PreserveCreatedOn, IsHidden = model.IsHidden, ModifiedOn = model.ModifiedOn, IsDeleted = model.IsDeleted, DeletedOn = model.DeletedOn }; var result = this.users.Add(user); Mapper.Map(result, model); } return Json(new[] { model }.ToDataSourceResult(request, ModelState)); }
protected void Page_PreRender(object sender, EventArgs e) { string userIdToLoad = this.Request.Params["UserId"]; if (string.IsNullOrEmpty(userIdToLoad)) { this.Response.Redirect("~/Home"); } else { string currentUserId = this.User.Identity.GetUserId(); if (currentUserId != userIdToLoad) { this.Response.Redirect("~/Errors/Forbidden.aspx"); } else { this.CurrentUser = this.Users.GetById(currentUserId); if (this.CurrentUser == null) { this.Response.Redirect("~/Errors/NotFound.aspx"); } else { this.FirstName.Text = this.CurrentUser.FirstName; this.LastName.Text = this.CurrentUser.LastName; this.FacebookAccountUrl.Text = this.CurrentUser.FacebookAccountUrl; this.YouTubeAccountUrl.Text = this.CurrentUser.YouTubeAccountUrl; } } } }
protected void Page_Load(object sender, EventArgs e) { string userId = this.Request.QueryString["UserId"]; if (userId == null) { userId = this.Context.User.Identity.GetUserId(); } this.User = this.Users.GetById(userId); this.userImage.ImageUrl = this.User.ImageUrl; }
public static Domain.User ToDomain(this Data.Models.User entity) { return(new Domain.User() { Id = entity.Id, Username = entity.Username, Password = entity.Password, Added = entity.Added, CouponUser = entity.CouponUser.ToDomainList(), Request = entity.Request.ToDomainList() }); }
public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error))); } if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(new ChallengeResult(provider, this)); } Data.Models.User user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable <Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); Authentication.SignIn(identity); } return(Ok()); }
public static ClaimsIdentity Create(User user, string authenticationType) { if (user == null) { throw new ArgumentNullException("user"); } var id = new ClaimsIdentity(authenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.String)); id.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, user.Username, ClaimValueTypes.String)); return id; }
protected override IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state) { if (this.CurrentUser == null) { if (this.User != null) { string userId = this.User.Identity.GetUserId(); User user = this.Users.GetById(userId); this.CurrentUser = user; } } return base.BeginExecute(requestContext, callback, state); }
protected void Page_Load(object sender, EventArgs e) { userId = Request.Url.Segments[4]; user = _db.Users.Where(u => u.Id == userId).FirstOrDefault(); if (user.Roles.Count > 0) { MakeAdminButton.CssClass = "hidden"; } else { RemoveAdminButton.CssClass = "hidden"; } }
protected void CreateUser_Click(object sender, EventArgs e) { this.SaveProfileImageToServer(); ApplicationUserManager manager = this.Context .GetOwinContext() .GetUserManager<ApplicationUserManager>(); ApplicationSignInManager signInManager = this.Context .GetOwinContext() .Get<ApplicationSignInManager>(); string userEmail = this.Server.HtmlEncode(this.Email.Text); string imageUrl = "~/Images/"; if (!string.IsNullOrEmpty(this.Request.Files[0].FileName)) { HttpPostedFile file = this.Request.Files[0]; int indexOfFileExtensionBeginning = file.FileName.LastIndexOf('.'); string extensionIncludingDot = file.FileName.Substring(indexOfFileExtensionBeginning); imageUrl = string.Concat(imageUrl, userEmail, "/avatar", extensionIncludingDot); } else { imageUrl = string.Concat(imageUrl, "default.jpg"); } var user = new User() { FirstName = this.Server.HtmlEncode(this.FirstName.Text), LastName = this.Server.HtmlEncode(this.LastName.Text), UserName = userEmail, Email = userEmail, ProfileImageUrl = imageUrl, FacebookAccountUrl = this.Server.HtmlEncode(this.FacebookAccountUrl.Text), YouTubeAccountUrl = this.Server.HtmlEncode(this.YouTubeAccountUrl.Text) }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { this.ErrorMessage.Text = result.Errors.FirstOrDefault(); } }
public TimetableTile(Booking Booking, TimeSlot Time, Room Room, User CurrentUser) { // Sets UI bindings to reference this object DataContext = this; this.Booking = Booking; this.Time = Time; this.Room = Room; // Set the default brightness function to the default BrightnessCurve = DefaultBrightnessCurve; // Default to the background window colour Brush = SystemColors.WindowBrush; if (Booking != null) // If there's actually a booking in this slot, use its colour Brush = new SolidColorBrush(Booking.Subject.Colour); Background = Brush; // Initialise the UI InitializeComponent(); // Hook up mouse events MouseEnter += TimetableTile_MouseEnter; MouseLeave += TimetableTile_MouseLeave; // If there's a booking in this slot if (Booking != null && CurrentUser != null) { // If the current user is somehow involved in the booking (either // as a student or teacher) if (((CurrentUser is Student) && Booking.Students.Any(s => s.Id == CurrentUser.Id)) || ((CurrentUser is Teacher) && Booking.Teacher.Id == CurrentUser.Id)) { // Do a simple animation on the tiles to draw attention Storyboard PulseEffect = (Storyboard)Resources["PulseEffect"]; PulseEffect.Begin(Outer); } } }
public async Task<ActionResult> Register(RegisterViewModel model) { if (this.ModelState.IsValid) { var user = new User(); if (model.IsArtist) { user.IsArtist = true; } user.Name = model.Name; user.Email = model.Email; user.UserName = model.Email; var result = await this.UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (model.IsArtist) { this.UserManager.AddToRole(user.Id, GlobalRolesConstants.ArtistRoleName); user.IsArtist = true; } await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return this.RedirectToAction("Index", "Home"); } this.AddErrors(result); } // If we got this far, something failed, redisplay form return this.View(model); }
public async Task<ActionResult> ExternalLoginConfirmation( ExternalLoginConfirmationViewModel model, string returnUrl) { if (this.User.Identity.IsAuthenticated) { return this.RedirectToAction("Index", "Manage"); } if (this.ModelState.IsValid) { // Get the information about the user from the external login provider var info = await this.AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return this.View("ExternalLoginFailure"); } var user = new User { UserName = model.Email, Email = model.Email }; var result = await this.UserManager.CreateAsync(user); if (result.Succeeded) { result = await this.UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return this.RedirectToLocal(returnUrl); } } this.AddErrors(result); } this.ViewBag.ReturnUrl = returnUrl; return this.View(model); }
private void CreateAndLoginUser() { if (!IsValid) { return; } var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>(); var user = new User() { UserName = email.Text, Email = email.Text }; IdentityResult result = manager.Create(user); if (result.Succeeded) { var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { RedirectOnFail(); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { signInManager.SignIn(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 // var code = manager.GenerateEmailConfirmationToken(user.Id); // Send this link via email: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id) IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); return; } } AddErrors(result); }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new User { UserName = model.FullName, Email = model.Email, FullName = model.FullName, CreatedOn = DateTime.Now }; var result = await this.UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await this.UserManager.AddToRoleAsync(user.Id, "User"); await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return this.RedirectToAction("Index", "Home"); } this.AddErrors(result); } return this.View(model); }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new User { UserName = model.UserName, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Avatar = model.Avatar, Gender = model.Gender, About = model.About }; if (string.IsNullOrEmpty(user.Avatar) || string.IsNullOrWhiteSpace(user.Avatar)) { if (user.Gender == Gender.Female) { user.Avatar = UserDefaultPictureConstants.Female; } else if (user.Gender == Gender.Male) { user.Avatar = UserDefaultPictureConstants.Male; } else { user.Avatar = UserDefaultPictureConstants.Neutral; } } var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, false, false); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
private ProfileViewModel GetBasicInfo(User user) { if (user == null) { throw new Exception("User not found,"); } var roles = this.userServices.GetUserRoles(user.Id); var basicViewModel = new ProfileViewModel() { Role = roles[0], User = this.Mapper.Map<UserViewModel>(user), CurrentUsername = this.User.Identity.GetUserName() }; basicViewModel.User.Rating = this.statisticsServices.GetRatingForUser(user.Id); return basicViewModel; }
public async Task<ActionResult> Register(RegisterViewModel model) { if (this.ModelState.IsValid) { var user = new User() { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Location = new Location() { City = model.City, CountryId = 32, CreatedOn = DateTime.Now } }; if (model.ProfileImage != null) { string filename = Path.GetFileName(model.ProfileImage.FileName); string folderPath = this.Server.MapPath(GlobalConstants.ImageFolderPathPrefix + user.Id); string imagePath = folderPath + "/" + filename; string imageUrl = GlobalConstants.ImageUrlPrefix + user.Id + "/" + filename; if (!Directory.Exists(folderPath)) { DirectoryInfo directory = Directory.CreateDirectory(folderPath); } model.ProfileImage.SaveAs(imagePath); user.Image = new Image() { Path = imageUrl, CreatedOn = DateTime.Now }; } else { user.Image = new Image() { Path = GlobalConstants.DefaultUserPicture, CreatedOn = DateTime.Now }; } var result = await this.UserManager.CreateAsync(user, model.Password); this.UserManager.AddToRole(user.Id, GlobalConstants.UserRoleName); if (result.Succeeded) { await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return this.RedirectToAction("Home", "Home"); } this.AddErrors(result); } return this.View(model); }
private BaseEditModel GetBasicEditInfo(User user) { if (user == null) { throw new Exception("User not found,"); } var roles = this.userServices.GetUserRoles(user.Id); var basicViewModel = this.Mapper.Map<BaseEditModel>(user); basicViewModel.Role = roles[0]; basicViewModel.CurrentUsername = this.User.Identity.GetUserName(); return basicViewModel; }
public async Task<ActionResult> Register(RegisterViewModel model) { if (this.countries.GetById(model.CountryId) == null) { this.ModelState.AddModelError("Country", "No such country was found, please contact administrator."); } if (this.ModelState.IsValid) { var user = new User { UserName = model.UserName, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, CountryId = model.CountryId, DateOfBirth = model.DateOfBirth }; var result = await this.UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { this.UserManager.AddToRole(user.Id, ((UserRoles)model.Role).ToString()); if ((UserRoles)model.Role == UserRoles.Student) { this.studentInfos.Create(user.Id); } else if ((UserRoles)model.Role == UserRoles.Director) { this.directorInfos.Create(user.Id); } await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return this.RedirectToAction("Index", "Home"); } this.AddErrors(result); } var countriesList = this.Cache.Get( "Countries", () => this.countries.All().ToList(), 60 * 60); model.Countries = new SelectList(countriesList, "Id", "Name", model.CountryId); // If we got this far, something failed, redisplay form return this.View(model); }
protected void CreateUser_Click(object sender, EventArgs e) { this.Upload_Image(); ApplicationUserManager manager = this.Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); ApplicationSignInManager signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var birthday = new DateTime(); DateTime.TryParse(this.Calendar.Text, out birthday); string imageUrl = "~/Images/"; if (!string.IsNullOrEmpty(this.Request.Files[0].FileName)) { imageUrl += this.UserName.Text + "/avatar" + this.Request .Files[0] .FileName .Substring(this.Request .Files[0].FileName .LastIndexOf('.')); } else { imageUrl += "default.jpg"; } var user = new User() { FirstName = this.FirstName.Text, LastName = this.LastName.Text, UserName = this.UserName.Text, Email = this.Email.Text, DateOfBirth = birthday, AboutMe = this.AboutMe.Text, ImageUrl = imageUrl }; var userKnowledge = new List<string>(); foreach (ListItem item in this.DeveloperKnowledgeListBox.Items) { if (item.Selected) { userKnowledge.Add(item.Value); } } var userSkills = new List<string>(); foreach (ListItem item in this.DeveloperSkillsListBox.Items) { if (item.Selected) { userSkills.Add(item.Value); } } user.Knowledge = string.Join(", ", userKnowledge); user.Skills = string.Join(", ", userSkills); IdentityResult result = manager.Create(user, this.Password.Text); if (result.Succeeded) { User registeredUser = manager.FindByName(user.UserName); if (this.IsDeveloperRadioButton.Checked) { manager.AddToRole(registeredUser.Id, "developer"); } else if (this.IsBusinessRadioButton.Checked) { manager.AddToRole(registeredUser.Id, "business"); } signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"] ?? "~/Home", Response); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } }