protected override void Seed(ULearnDb context) { var roleStore = new RoleStore <IdentityRole>(context); var roleManager = new RoleManager <IdentityRole>(roleStore); roleManager.Create(new IdentityRole(LmsRoles.SysAdmin)); if (!context.Users.Any(u => u.UserName == "user")) { var userStore = new UserStore <ApplicationUser>(context); var manager = new ULearnUserManager(userStore); var user = new ApplicationUser { UserName = "******", FirstName = "User", LastName = "" }; manager.Create(user, "asdasd"); } if (!context.Users.Any(u => u.UserName == "admin")) { var userStore = new UserStore <ApplicationUser>(context); var manager = new ULearnUserManager(userStore); var user = new ApplicationUser { UserName = "******", FirstName = "System Administrator", LastName = "" }; manager.Create(user, "fullcontrol"); manager.AddToRole(user.Id, LmsRoles.SysAdmin); } context.SaveChanges(); }
protected override void Seed(ULearnDb db) { var roleStore = new RoleStore <IdentityRole>(db); var roleManager = new RoleManager <IdentityRole>(roleStore); roleManager.Create(new IdentityRole(LmsRoles.SysAdmin.ToString())); var userStore = new UserStore <ApplicationUser>(db); var manager = new ULearnUserManager(userStore); if (!db.Users.Any(u => u.UserName == "user")) { var user = new ApplicationUser { UserName = "******", FirstName = "User", LastName = "" }; manager.Create(user, "asdasd"); } if (!db.Users.Any(u => u.UserName == "admin")) { var user = new ApplicationUser { UserName = "******", FirstName = "System Administrator", LastName = "" }; manager.Create(user, "fullcontrol"); manager.AddToRole(user.Id, LmsRoles.SysAdmin.ToString()); } var usersRepo = new UsersRepo(db); usersRepo.CreateUlearnBotUserIfNotExists(); db.SaveChanges(); }
public CertificatesController() { var db = new ULearnDb(); certificatesRepo = new CertificatesRepo(db); userManager = new ULearnUserManager(db); }
private static async Task <ClaimsIdentity> GetIdentityForLtiLogin(LtiAuthenticatedContext context, ULearnDb db, UserLoginInfo ltiLogin) { var userManager = new ULearnUserManager(db); using (var transaction = db.Database.BeginTransaction(IsolationLevel.Serializable)) { var ltiLoginUser = await userManager.FindAsync(ltiLogin); if (ltiLoginUser != null) { log.Info($"Нашёл LTI-логин: провайдер {ltiLogin.LoginProvider}, идентификатор {ltiLogin.ProviderKey}, он принадлежит пользователю {ltiLoginUser.UserName} (Id = {ltiLoginUser.Id})"); return(await userManager.CreateIdentityAsync(ltiLoginUser, context.Options.SignInAsAuthenticationType)); } log.Info($"Не нашёл LTI-логин: провайдер {ltiLogin.LoginProvider}, идентификатор {ltiLogin.ProviderKey}"); if (IsAuthenticated(context.OwinContext)) { var ulearnPrincipal = context.OwinContext.Authentication.User; log.Info($"Пришёл LTI-запрос на аутенфикацию, пользователь уже аутенфицирован на ulearn: {ulearnPrincipal.Identity.Name}. Прикрепляю к пользователю LTI-логин"); await userManager.AddLoginAsync(ulearnPrincipal.Identity.GetUserId(), ltiLogin); return((ClaimsIdentity)ulearnPrincipal.Identity); } 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"); } log.Info($"Сгенерировал имя пользователя для LTI-пользователя: {usernameContext.UserName}, ищу пользователя по этому имени"); var ulearnUser = await userManager.FindByNameAsync(usernameContext.UserName); if (ulearnUser == null) { log.Info("Не нашёл пользователя с таким именем, создаю нового"); ulearnUser = new ApplicationUser { UserName = usernameContext.UserName }; var result = await userManager.CreateAsync(ulearnUser); if (!result.Succeeded) { var errors = string.Join("\n\n", result.Errors); throw new Exception("Can't create user for LTI: " + errors); } } await userManager.AddLoginAsync(ulearnUser.Id, ltiLogin); var identity = await userManager.CreateIdentityAsync(ulearnUser, context.Options.SignInAsAuthenticationType); transaction.Commit(); return(identity); } }
public CertificatesController(ULearnDb db, WebCourseManager courseManager) { this.courseManager = courseManager; certificatesRepo = new CertificatesRepo(db); userManager = new ULearnUserManager(db); certificateGenerator = new CertificateGenerator(db, courseManager); }
public NotificationsController(ULearnDb db, CourseManager courseManager) { notificationsRepo = new NotificationsRepo(db); usersRepo = new UsersRepo(db); visitsRepo = new VisitsRepo(db); userManager = new ULearnUserManager(db); this.courseManager = courseManager; telegramBotName = WebConfigurationManager.AppSettings["ulearn.telegram.botName"]; secretForHashes = WebConfigurationManager.AppSettings["ulearn.secretForHashes"] ?? ""; }
public InitialDataCreator( UlearnDb db, RoleManager <IdentityRole> roleManager, ULearnUserManager userManager, UsersRepo usersRepo ) { this.db = db; this.roleManager = roleManager; this.userManager = userManager; this.usersRepo = usersRepo; }
public KonturPassportRequiredFilter(ULearnUserManager userManager) { this.userManager = userManager; }
public ExerciseController() { exerciseStudentZipsCache = new ExerciseStudentZipsCache(); userManager = new ULearnUserManager(db); }
/// <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(); }