private async Task SendRestorePasswordEmail(string requestId, ApplicationUser user) { var url = Url.Action("SetNewPassword", "RestorePassword", new { requestId }, "https"); var message = new SendGridMessage(); message.AddTo(user.Email); message.From = new MailAddress("*****@*****.**", "Добрый робот uLearn"); message.Subject = "Восстановление пароля uLearn"; message.Html = "Чтобы изменить пароль к аккаунту " + user.UserName + ", перейдите по ссылке: <a href=\"" + url + "\">" + url + "</a>"; var login = ConfigurationManager.AppSettings["SendGrid.Login"]; var password = ConfigurationManager.AppSettings["SendGrid.Password"]; var credentials = new NetworkCredential(login, password); var transport = new SendGrid.Web(credentials); try { await transport.DeliverAsync(message); } catch (InvalidApiRequestException ex) { throw new Exception(ex.Message + ":\n\n" + string.Join("\n", ex.Errors), ex); } }
private async Task InternalLoginAsync(HttpContextBase context, ApplicationUser user, bool isPersistent) { var authenticationManager = GetAuthenticationManager(context); authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await user.GenerateUserIdentityAsync(userManager, userRoles); authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity); }
public static System.Web.WebPages.HelperResult Avatar(ApplicationUser user, string classes="") { return new System.Web.WebPages.HelperResult(__razor_helper_writer => { if (user.HasAvatar) { WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\t\t<img class=\"user__avatar "); WebViewPage.WriteTo(@__razor_helper_writer, classes); WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\" src=\""); WebViewPage.WriteTo(@__razor_helper_writer, user.AvatarUrl); WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\" alt=\""); WebViewPage.WriteTo(@__razor_helper_writer, HttpUtility.HtmlAttributeEncode(user.VisibleName)); WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\" />\r\n"); } else { WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\t\t<div class=\"user__avatar user__avatar__placeholder "); WebViewPage.WriteTo(@__razor_helper_writer, classes); WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\" style=\"background-color: "); WebViewPage.WriteTo(@__razor_helper_writer, GetAvatarPlaceholderColor(user)); WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\">"); WebViewPage.WriteTo(@__razor_helper_writer, GetAvatarPlaceholderLetter(user)); WebViewPage.WriteLiteralTo(@__razor_helper_writer, "</div>\r\n"); } }); }
public static System.Web.WebPages.HelperResult GetAvatarPlaceholderLetter(ApplicationUser user) { return new System.Web.WebPages.HelperResult(__razor_helper_writer => { WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\t"); WebViewPage.WriteTo(@__razor_helper_writer, char.ToUpper(user.VisibleName.FindFirstLetter('O'))); WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\r\n"); }); }
public static System.Web.WebPages.HelperResult GetAvatarPlaceholderColor(ApplicationUser user) { return new System.Web.WebPages.HelperResult(__razor_helper_writer => { var hue = Math.Abs(user.Id.GetHashCode()) % 360; WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\t"); WebViewPage.WriteLiteralTo(@__razor_helper_writer, "hsl("); WebViewPage.WriteTo(@__razor_helper_writer, hue); WebViewPage.WriteLiteralTo(@__razor_helper_writer, ", 64%, 75%)"); WebViewPage.WriteLiteralTo(@__razor_helper_writer, "\r\n"); }); }
public async Task<bool> AddUserToGroup(int groupId, ApplicationUser user) { return await AddUserToGroup(groupId, user.Id); }
public static async Task LoginAsync(HttpContextBase context, ApplicationUser user, bool isPersistent) { log.Info($"Пользователь {user.VisibleName} (логин = {user.UserName}, id = {user.Id}) залогинился"); await new AuthenticationManager().InternalLoginAsync(context, user, isPersistent); }
public static async Task LoginAsync(HttpContextBase context, ApplicationUser user, bool isPersistent) { await new AuthenticationManager().InternalLoginAsync(context, user, isPersistent); }
public UserCourseModel(Course course, ApplicationUser user, ULearnDb db) { Course = course; User = user; var visits = db.Visits.Where(v => v.UserId == user.Id && v.CourseId == course.Id).GroupBy(v => v.SlideId).ToDictionary(g => g.Key, g => g.FirstOrDefault()); var unitResults = new Dictionary<string, UserCourseUnitModel>(); foreach (var slide in Course.Slides) { var unit = slide.Info.UnitName; if (!unitResults.ContainsKey(unit)) unitResults.Add(unit, new UserCourseUnitModel { UnitName = unit, SlideVisits = new ProgressModel(), Exercises = new ProgressModel(), Quizes = new ProgressModel(), Total = new ProgressModel() }); var res = unitResults[unit]; var isVisited = visits.ContainsKey(slide.Id); var isPassed = isVisited && visits[slide.Id].IsPassed; var score = isPassed ? visits[slide.Id].Score : 0; res.SlideVisits.Total++; res.Total.Total += slide.MaxScore; res.Total.Earned += score; if (isVisited) res.SlideVisits.Earned++; if (slide is ExerciseSlide) { res.Exercises.Total += slide.MaxScore; res.Exercises.Earned += score; } if (slide is QuizSlide) { res.Quizes.Total += slide.MaxScore; res.Quizes.Earned += score; } } Units = course.GetUnits().Select(unitName => unitResults[unitName]).ToArray(); Total = new UserCourseUnitModel { Total = new ProgressModel(), Exercises = new ProgressModel(), SlideVisits = new ProgressModel(), Quizes = new ProgressModel() }; foreach (var result in Units) { Total.Total.Add(result.Total); Total.Exercises.Add(result.Exercises); Total.SlideVisits.Add(result.SlideVisits); Total.Quizes.Add(result.Quizes); } }
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 AuthenticationManager.LoginAsync(HttpContext, user, isPersistent: false); if (string.IsNullOrWhiteSpace(model.ReturnUrl)) return RedirectToAction("Index", "Home"); return Redirect(this.FixRedirectUrl(model.ReturnUrl)); } this.AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName }; var result = await userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await AuthenticationManager.LoginAsync(HttpContext, user, isPersistent: false); if (string.IsNullOrWhiteSpace(model.ReturnUrl)) model.ReturnUrl = Url.Action("Index", "Home"); else model.ReturnUrl = this.FixRedirectUrl(model.ReturnUrl); model.RegistrationFinished = true; } else this.AddErrors(result); } return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage", "Account"); } ExternalLoginInfo info = await AuthenticationManager.GetExternalLoginInfoAsync(HttpContext); if (info == null) { return View("ExternalLoginFailure"); } ViewBag.LoginProvider = info.Login.LoginProvider; if (ModelState.IsValid) { var userAvatarUrl = info.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == "AvatarUrl")?.Value; var firstName = info.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value; var lastName = info.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value; var user = new ApplicationUser { UserName = model.UserName, FirstName = firstName, LastName = lastName, AvatarUrl = userAvatarUrl, }; var result = await userManager.CreateAsync(user); if (result.Succeeded) { result = await userManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await AuthenticationManager.LoginAsync(HttpContext, user, isPersistent: false); return Redirect(this.FixRedirectUrl(returnUrl)); } } this.AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
/// <summary> /// Invoked after the LTI request has been authenticated so the application can sign in the application user. /// </summary> /// <param name="context">Contains information about the login session as well as the LTI request.</param> /// <param name="claims">Optional set of claims to add to the identity.</param> /// <returns>A <see cref="Task"/> representing the completed operation.</returns> public static async Task OnAuthenticated(LtiAuthenticatedContext context, IEnumerable<Claim> claims = null) { ClaimsIdentity identity; if (!IsAuthenticated(context.OwinContext)) { // Find existing pairing between LTI user and application user var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ULearnDb())); var loginProvider = string.Join(":", new[] { context.Options.AuthenticationType, context.LtiRequest.ConsumerKey }); var providerKey = context.LtiRequest.UserId; var login = new UserLoginInfo(loginProvider, providerKey); var user = await userManager.FindAsync(login); if (user == null) { var usernameContext = new LtiGenerateUserNameContext(context.OwinContext, context.LtiRequest); await context.Options.Provider.GenerateUserName(usernameContext); if (string.IsNullOrEmpty(usernameContext.UserName)) { throw new Exception("Can't generate username"); } user = await userManager.FindByNameAsync(usernameContext.UserName); if (user == null) { user = new ApplicationUser { UserName = usernameContext.UserName }; var result = await userManager.CreateAsync(user); if (!result.Succeeded) { var errors = String.Join("\n\n", result.Errors); throw new Exception("Can't create user: "******"LtiRequest")); foreach (var claim in claimsToRemove) { identity.RemoveClaim(claim); } identity.AddClaim(new Claim(context.Options.ClaimType, json, ClaimValueTypes.String, context.Options.AuthenticationType)); if (claims != null) { foreach (var claim in claims) { identity.AddClaim(claim); } } context.OwinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); // Redirect to original URL so the new identity takes affect context.RedirectUrl = context.LtiRequest.Url.ToString(); }
public static System.Web.WebPages.HelperResult SmallAvatar(ApplicationUser user, string classes="") { return new System.Web.WebPages.HelperResult(__razor_helper_writer => { WebViewPage.WriteTo(@__razor_helper_writer, Avatar(user, "small " + classes)); ; }); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage", "Account"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(HttpContext); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.UserName }; var result = await userManager.CreateAsync(user); if (result.Succeeded) { result = await userManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await AuthenticationManager.LoginAsync(HttpContext, user, isPersistent: false); return Redirect(this.FixRedirectUrl(returnUrl)); } } this.AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public UserInfoModel(ApplicationUser user, Course[] courses) { User = user; Courses = courses; }
private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); }
/// <summary> /// Invoked after the LTI request has been authenticated so the application can sign in the application user. /// </summary> /// <param name="context">Contains information about the login session as well as the LTI request.</param> /// <param name="claims">Optional set of claims to add to the identity.</param> /// <returns>A <see cref="Task"/> representing the completed operation.</returns> public static async Task OnAuthenticated(LtiAuthenticatedContext context, IEnumerable<Claim> claims = null) { log.Info($"LTI вызвал событие OnAuthenticated при запросе на {context.Request.Uri}"); ClaimsIdentity identity; if (!IsAuthenticated(context.OwinContext)) { // Find existing pairing between LTI user and application user var userManager = new ULearnUserManager(); var loginProvider = string.Join(":", context.Options.AuthenticationType, context.LtiRequest.ConsumerKey); var providerKey = context.LtiRequest.UserId; var login = new UserLoginInfo(loginProvider, providerKey); var user = await userManager.FindAsync(login); log.Info($"Ищу пользователя: провайдер {loginProvider}, идентификатор {providerKey}"); if (user == null) { log.Info("Не нашёл пользователя"); var usernameContext = new LtiGenerateUserNameContext(context.OwinContext, context.LtiRequest); log.Info("Генерирую имя пользователя для LTI-пользователя"); await context.Options.Provider.GenerateUserName(usernameContext); if (string.IsNullOrEmpty(usernameContext.UserName)) { throw new Exception("Can't generate username"); } log.Info($"Сгенерировал: {usernameContext.UserName}, ищу пользователя по этому имени"); user = await userManager.FindByNameAsync(usernameContext.UserName); if (user == null) { log.Info("Не нашёл пользователя с таким именем, создаю нового"); user = new ApplicationUser { UserName = usernameContext.UserName }; var result = await userManager.CreateAsync(user); if (!result.Succeeded) { var errors = string.Join("\n\n", result.Errors); throw new Exception("Can't create user: "******"Добавляю LTI-логин {login} к пользователю {user.VisibleName} (Id = {user.Id})"); // Save the pairing between LTI user and application user await userManager.AddLoginAsync(user.Id, login); } log.Info($"Подготавливаю identity для пользователя {user.VisibleName} (Id = {user.Id})"); // Create the application identity, add the LTI request as a claim, and sign in identity = await userManager.CreateIdentityAsync(user, context.Options.SignInAsAuthenticationType); } else { log.Info($"Пришёл LTI-запрос на аутенфикацию, но пользователь уже аутенфицирован на ulearn: {context.OwinContext.Authentication.User.Identity.Name}"); identity = (ClaimsIdentity)context.OwinContext.Authentication.User.Identity; } var json = JsonConvert.SerializeObject(context.LtiRequest, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); log.Info($"LTI-запрос: {json}"); var claimsToRemove = identity.Claims.Where(c => c.Type.Equals("LtiRequest")); foreach (var claim in claimsToRemove) { log.Info($"Требование в LTI-запросе: {claim}"); identity.RemoveClaim(claim); } identity.AddClaim(new Claim(context.Options.ClaimType, json, ClaimValueTypes.String, context.Options.AuthenticationType)); if (claims != null) { foreach (var claim in claims) { identity.AddClaim(claim); } } log.Info($"Аутенфицирую identity: {identity.Name}"); context.OwinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); // Redirect to original URL so the new identity takes affect context.RedirectUrl = context.LtiRequest.Url.ToString(); }