public static void SeedUsers(UserManager <User> userManager) { if (userManager?.FindByNameAsync("*****@*****.**").Result == null) { User user = new User(); user.UserName = "******"; user.Email = "*****@*****.**"; user.EmailConfirmed = true; user.IsActive = true; IdentityResult result = userManager.CreateAsync(user, "Kavdansky1!").Result; if (result.Succeeded) { userManager.AddToRoleAsync(user, "Admin").Wait(); } } if (userManager?.FindByNameAsync("*****@*****.**").Result == null) { User user = new User(); user.UserName = "******"; user.Email = "*****@*****.**"; user.EmailConfirmed = true; user.IsActive = true; IdentityResult result = userManager.CreateAsync (user, "Rusulski1!").Result; if (result.Succeeded) { userManager.AddToRoleAsync(user, "ChiefEditor").Wait(); } } }
public async Task Invoke(HttpContext httpContext, UserManager<ApplicationUser> manager) { if (httpContext.Request.Path.StartsWithSegments(_options.Path)) { var headers = httpContext.Request.Headers; if (!(headers.ContainsKey("ApiUser") && headers.ContainsKey("ApiToken"))) { await httpContext.Authentication.ChallengeAsync(); return; } var apiUser = headers.FirstOrDefault(h => h.Key == "ApiUser").Value; var token = headers.FirstOrDefault(h => h.Key == "ApiToken").Value; var user = await manager.FindByNameAsync(apiUser).ConfigureAwait(false); var authorized = await manager.VerifyUserTokenAsync(user, "Default", "api-request-injest", token).ConfigureAwait(false); if (!authorized) { await httpContext.Authentication.ChallengeAsync(); return; } } await _next(httpContext); }
public string submitCodePost(string title, string content, string type) { using (ApplicationDbContext db = new ApplicationDbContext()) { CodePost tmp = new CodePost(); content = HttpUtility.JavaScriptStringEncode(content); var store = new UserStore<ApplicationUser>(db); var userManager = new UserManager<ApplicationUser>(store); ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result; var currentUser = userManager.FindById(User.Identity.GetUserId()); if (title != null && content != null && type != null) { tmp.title = title; tmp.content = content; tmp.votes = 0; tmp.user_id = user.Id; tmp.userName = user.user; tmp.userImgPath = currentUser.userImgPath; } bool result = updateHashTags(tmp); if(result == false) db.posts.Add(tmp); db.SaveChanges(); return "success"; } }
public ApplicationUser getAppUser(IPrincipal User) { var store = new UserStore<ApplicationUser>(new ApplicationDbContext()); var userManager = new UserManager<ApplicationUser>(store); ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result; return user; }
private string GetUserId(string userName) { var store = new UserStore<ApplicationUser>(new ApplicationDbContext()); var userManager = new UserManager<ApplicationUser>(store); ApplicationUser user = userManager.FindByNameAsync(userName).Result; return user.Id; }
public async Task<MyUser> GetUserByName(string name) { var db = new DataContext(); var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db)); var currentUser = await userMan.FindByNameAsync(name); return currentUser; }
public static async Task SetDisplayName(this Controller baseController, ClaimsPrincipal user, UserManager<User> userManager) { if (baseController.TempData["UserDisplayName"] == null || string.IsNullOrEmpty(baseController.TempData["UserDisplayName"].ToString())) { if (user.Identity.IsAuthenticated) { var loggedInUser = await userManager.FindByNameAsync(user.Identity.Name); baseController.TempData["UserDisplayName"] = loggedInUser.GetFirstName(); } } }
public ActionResult Index() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result; model = new ImageModel(); if (user != null) { model.ImageUrl = user.ImageUrl; } return PartialView("~/Views/Shared/_LoginPartial.cshtml", model); }
public ActionResult AddToCart(Product product) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result; List<Product> products = new List<Product>(); user.UserCart.Products.Add(product); foreach (var item in user.UserCart.Products) { products.Add(item); } return View(products); }
// GET: Files/Create public ActionResult Create() { var store = new UserStore<ApplicationUser>(new ApplicationDbContext()); var userManager = new UserManager<ApplicationUser>(store); ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result; if (user == null) return View(); ViewBag.OwnerId = new SelectList(db.Users.Where(u => u.Id == user.Id), "Id", "FirstName"); ViewBag.ReceiverId = AddFirstItem(new SelectList(db.Users, "Id", "FirstName")); ViewBag.GroupId = AddFirstItem(new SelectList(db.Groups, "GroupID", "GroupName")); return View(); }
// GET: api/CalcReleases public IQueryable<CalcRelease> GetCalcRelease() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result; string[] myInClause = null; if (user.Scheme != null) { myInClause = user.Scheme.Split(','); return db.CalcRelease.Where(s => myInClause.Contains(s.Scheme)); } else { return null; } }
public async Task Invoke(HttpContext context, SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager) { if (context.User.Identity.IsAuthenticated) { this.SetNTContext(context); } // automatically logging in in the dev mode else if (SiteSettings.IsEnvironment(SecurityConstants.DevEnvironment)) { ApplicationUser user = await userManager.FindByNameAsync(SecuritySettings.NootusProfileUserName); await signInManager.SignInAsync(user, false); } await this.next(context); }
public IQueryable<string> Get() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result; string[] myInClause = null; var response = Request.CreateResponse(); if (user.Scheme != null) { myInClause = user.Scheme.Split(','); return db.Schemes.Where(s => myInClause.Contains(s.Name)).Select(m => m.Name).Distinct(); } else { return null; } }
/// <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) { // Find existing pairing between LTI user and application user var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new LtiDb())); 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)) { return; } user = await userManager.FindByNameAsync(usernameContext.UserName); if (user == null) { user = new ApplicationUser { UserName = usernameContext.UserName }; var result = await userManager.CreateAsync(user); if (!result.Succeeded) { return; } } // Save the pairing between LTI user and application user await userManager.AddLoginAsync(user.Id, login); } // Create the application identity, add the LTI request as a claim, and sign in var identity = await userManager.CreateIdentityAsync(user, context.Options.SignInAsAuthenticationType); identity.AddClaim(new Claim(context.Options.ClaimType, JsonConvert.SerializeObject(context.LtiRequest, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), 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 async Task <IActionResult> Login(UserVM userVM, string returnUrl) { var user = await userManager?.FindByNameAsync(userVM.AppUser.UserName); if (user != null) { await signInManager.SignOutAsync(); var signRes = await signInManager.PasswordSignInAsync(user, userVM.Password, false, false); if (signRes.Succeeded) { return(Redirect(returnUrl)); } } return(View()); }
public async Task<WikiDownUser> Save(IPrincipal principal, UserManager<WikiDownUser> userManager) { var user = await userManager.FindByNameAsync(this.UserName); var roles = this.GetRoles(principal, user); if (user != null) { if (user.UserName == principal.Identity.Name) { var userAccessLevel = ArticleAccessHelper.GetAccessLevel(user.Roles); if (userAccessLevel < ArticleAccessLevel.Admin) { throw new HttpResponseException(HttpStatusCode.BadRequest); } } user.SetRoles(roles); user.SetDisplayName(this.DisplayName); user.SetEmail(this.Email); if (!string.IsNullOrWhiteSpace(this.Password)) { await userManager.RemovePasswordAsync(user.Id); await userManager.AddPasswordAsync(user.Id, this.Password); } await userManager.UpdateAsync(user); WikiDownUserCacheHelper.Clear(user.UserName); } else { user = new WikiDownUser(this.UserName) { Roles = roles }; user.SetDisplayName(this.DisplayName); user.SetEmail(this.Email); await userManager.CreateAsync(user, this.Password); } return user; }
public Task <IdentityResult> ValidateAsync(UserManager <User> manager, User user) { string findUser = manager?.FindByNameAsync(user.UserName)?.Result?.UserName; var errors = new List <IdentityError>(); if (user.UserName.StartsWith(" ") || user.UserName.EndsWith(" ")) { errors.Add(new IdentityError { Description = "Имя не может начинаться или заканчиваться пробелом." }); } if (user.UserName == findUser) { errors.Add(new IdentityError { Description = "Такое имя уже существует." }); } if (user.UserName.Contains("admin")) { errors.Add(new IdentityError { Description = $"Имя не может содержать - 'admin'" }); } if (user.Email.Contains("admin")) { errors.Add(new IdentityError { Description = $"Email не может содержать - 'admin'" }); } return(Task.FromResult(errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray()))); }
public async Task<IHttpActionResult> UpdateRuoloUtente(UpdateRuoloUtenteModel Model) { if (Model == null || !ModelState.IsValid) return BadRequest(ModelState); using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) { var utente = await userManager.FindByNameAsync(Model.Username); if (utente == null) return NotFound(); if (Model.NuovoStato) { await userManager.AddToRoleAsync(utente.Id, Model.Ruolo); } else { await userManager.RemoveFromRoleAsync(utente.Id, Model.Ruolo); } } return Ok(); }
public virtual async Task <AppUser> FindByNameAsync(string userName) { var user = await _userManager.FindByNameAsync(userName).ConfigureAwait(false); return(user.ToAppUser()); }
/// <summary> /// Gets the user. /// </summary> /// <param name="WindowsPrincipal">The windows principal.</param> /// <returns>The user</returns> private static User GetUser(WindowsPrincipal WindowsPrincipal) { Contract.Requires<ArgumentNullException>(WindowsPrincipal != null, "WindowsPrincipal"); Claim NameClaim = WindowsPrincipal.FindFirst(ClaimTypes.Name); string Name = NameClaim.Value; string[] Parts = Name.Split(new[] { '\\' }, 2); string ShortName = Parts[Parts.Length - 1]; using (UserStore UserStore = new UserStore()) { using (UserManager<User, long> UserManager = new UserManager<User, long>(UserStore)) { User User = UserManager.FindByNameAsync(ShortName).Result; if (User == null) { UserManager.CreateAsync(new User() { UserName = ShortName }, Guid.NewGuid().ToString()).Wait(); User = UserManager.FindByNameAsync(ShortName).Result; } return User; } } }
private void SeedIdentity(UserManager <Uporabnik> userManager, RoleManager <IdentityRole> roleManager) { //Roles if (!roleManager.RoleExistsAsync("Admin").Result) { var role = new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" }; var roleResult = roleManager.CreateAsync(role).Result; } if (!roleManager.RoleExistsAsync("Uporabnik").Result) { var role = new IdentityRole { Name = "Uporabnik", NormalizedName = "UPORABNIK" }; var roleResult = roleManager.CreateAsync(role).Result; } if (!roleManager.RoleExistsAsync("Skladiscnik").Result) { var role = new IdentityRole { Name = "Skladiscnik", NormalizedName = "SKLADISCNIK" }; var roleResult = roleManager.CreateAsync(role).Result; } if (!roleManager.RoleExistsAsync("Test").Result) { var role = new IdentityRole { Name = "Test", NormalizedName = "TEST" }; var roleResult = roleManager.CreateAsync(role).Result; } //Test Users //ADMIN if (userManager.FindByNameAsync("*****@*****.**").Result == null) { var user = new Uporabnik(); user.UserName = "******"; user.Email = "*****@*****.**"; user.PodjetjeId = 1; user.EmailConfirmed = true; var result = userManager.CreateAsync(user, "Password123.").Result; if (result.Succeeded) { userManager.AddToRoleAsync(user, "Admin").Wait(); } } //UPORABNIKI if (userManager.FindByNameAsync("*****@*****.**").Result == null) { var user = new Uporabnik(); user.UserName = "******"; user.Email = "*****@*****.**"; user.PodjetjeId = 2; user.EmailConfirmed = true; var result = userManager.CreateAsync(user, "Password123.").Result; if (result.Succeeded) { userManager.AddToRoleAsync(user, "Uporabnik").Wait(); } } if (userManager.FindByNameAsync("*****@*****.**").Result == null) { var user = new Uporabnik(); user.UserName = "******"; user.Email = "*****@*****.**"; user.PodjetjeId = 3; user.EmailConfirmed = true; var result = userManager.CreateAsync(user, "Password123.").Result; if (result.Succeeded) { userManager.AddToRoleAsync(user, "Uporabnik").Wait(); } } //SKLADIŠÈNIK if (userManager.FindByNameAsync("*****@*****.**").Result == null) { var user = new Uporabnik(); user.UserName = "******"; user.Email = "*****@*****.**"; user.PodjetjeId = 1; user.EmailConfirmed = true; user.SkladisceId = 1; var result = userManager.CreateAsync(user, "Password123.").Result; if (result.Succeeded) { userManager.AddToRoleAsync(user, "Skladiscnik").Wait(); } } }
public async Task <string> GetUserIdByUserName(string username) { var user = await _userManager.FindByNameAsync(username); return(user?.Id); }
public static void Initialize() { eQuizContext db = new eQuizContext(); using (var Transaction = db.Database.BeginTransaction()) { try { if (db.Questions.Count() == 0) { // question 1 var q1 = new Question(); q1.Text = "Which Helper Method Returns binary output to write to the response?"; db.Questions.Add(q1); db.SaveChanges(); var a1 = new Answer(); a1.Text = "Content"; a1.IsCorrect = true; a1.QuestionId = q1.QuestionId; db.Answers.Add(a1); var a2 = new Answer(); a2.Text = "File"; a2.IsCorrect = false; a2.QuestionId = q1.QuestionId; db.Answers.Add(a2); var a3 = new Answer(); a3.Text = "JavaScript"; a3.IsCorrect = false; a3.QuestionId = q1.QuestionId; db.Answers.Add(a3); var a4 = new Answer(); a4.Text = "Json"; a4.IsCorrect = false; a4.QuestionId = q1.QuestionId; db.Answers.Add(a4); db.SaveChanges(); // question 2 var q2 = new Question(); q2.Text = "Which Action Result Renders a partial view, which defines a section of a view that can be rendered inside another view?"; db.Questions.Add(q2); db.SaveChanges(); var q2a1 = new Answer(); q2a1.Text = "ContentResult"; q2a1.IsCorrect = false; q2a1.QuestionId = q2.QuestionId; db.Answers.Add(q2a1); var q2a2 = new Answer(); q2a2.Text = "RedirectResult"; q2a2.IsCorrect = true; q2a2.QuestionId = q2.QuestionId; db.Answers.Add(q2a2); var q2a3 = new Answer(); q2a3.Text = "PartialViewResult"; q2a3.IsCorrect = false; q2a3.QuestionId = q2.QuestionId; db.Answers.Add(q2a3); var q2a4 = new Answer(); q2a4.Text = "None of above."; q2a4.IsCorrect = false; q2a4.QuestionId = q2.QuestionId; db.Answers.Add(q2a4); db.SaveChanges(); // question 3 var q3 = new Question(); q3.Text = "The Controller class is responsible for the following processing stages:"; db.Questions.Add(q3); db.SaveChanges(); var q3a1 = new Answer(); q3a1.Text = "Locating the appropriate action method to call and validating that it can be called"; q3a1.IsCorrect = false; q3a1.QuestionId = q3.QuestionId; db.Answers.Add(q3a1); var q3a2 = new Answer(); q3a2.Text = "Getting the values to use as the action method's arguments"; q3a2.IsCorrect = false; q3a2.QuestionId = q3.QuestionId; db.Answers.Add(q3a2); var q3a3 = new Answer(); q3a3.Text = "Handling all errors that might occur during the execution of the action method"; q3a3.IsCorrect = false; q3a3.QuestionId = q3.QuestionId; db.Answers.Add(q3a3); var q3a4 = new Answer(); q3a4.Text = "All of the above."; q3a4.IsCorrect = true; q3a4.QuestionId = q3.QuestionId; db.Answers.Add(q3a4); db.SaveChanges(); } //this is for creating user var userStore = new UserStore<ApplicationUser>(db); var userManager = new UserManager<ApplicationUser>(userStore); if (!(db.Users.Any(u => u.UserName == "*****@*****.**"))) { var userToInsert = new ApplicationUser { UserName = "******", Email = "*****@*****.**", PhoneNumber = "03035332033", LockoutEnabled = true, FirstName = "Muhammad", LastName = "Sohail" }; userManager.Create(userToInsert, "Sohail@2"); } if (!(db.Users.Any(u => u.UserName == "*****@*****.**"))) { var userToInsert = new ApplicationUser { UserName = "******", Email = "*****@*****.**", PhoneNumber = "03035332033", LockoutEnabled = true, FirstName = "Melvin", LastName = "Claxton" }; userManager.Create(userToInsert, "123456"); } //this is for creating/getting role RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); var role = new IdentityRole("Administrator"); if (!RoleManager.RoleExists("Administrator")) { RoleManager.Create(role); } else { role = RoleManager.FindByName("Administrator"); } //this is for assigning role that is created above ApplicationUser user = userManager.FindByNameAsync("*****@*****.**").Result; if(!userManager.IsInRole(user.Id, role.Id)) { userManager.AddToRole(user.Id, role.Name); } //this is for assigning role that is created above user = userManager.FindByNameAsync("*****@*****.**").Result; if (!userManager.IsInRole(user.Id, role.Id)) { userManager.AddToRole(user.Id, role.Name); } Transaction.Commit(); } catch(Exception exc) { Transaction.Rollback(); } } using (var Transaction = db.Database.BeginTransaction()) { try { var Settings = db.Settings.ToList(); bool QuizStartTimeSettingExists = false; foreach (var Setting in Settings) { if (Setting.Name.Contains("Quiz Start Time")) { QuizStartTimeSettingExists = true; break; } } if (!QuizStartTimeSettingExists) { db.Settings.Add(new Setting { Name = "Quiz Start Time", Value = "2020/01/01" }); db.SaveChanges(); } Transaction.Commit(); } catch (Exception exc) { Transaction.Rollback(); } } }
private async Task BuildForInternalAsync(Tenant tenant) { //Create Organization Units var organizationUnits = new List <OrganizationUnit>(); var producing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Producing"); var researchAndDevelopment = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Research & Development", producing); var ivrProducts = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "IVR Related Products", researchAndDevelopment); var voiceTech = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Voice Technologies", researchAndDevelopment); var inhouseProjects = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Inhouse Projects", researchAndDevelopment); var qualityManagement = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Quality Management", producing); var testing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Testing", producing); var selling = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Selling"); var marketing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Marketing", selling); var sales = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Sales", selling); var custRelations = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Customer Relations", selling); var supporting = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Supporting"); var buying = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Buying", supporting); var humanResources = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Human Resources", supporting); //Create users var users = _randomUserGenerator.GetRandomUsers(RandomHelper.GetRandom(12, 26), tenant.Id); foreach (var user in users) { //Create the user await _userManager.CreateAsync(user); await CurrentUnitOfWork.SaveChangesAsync(); //Add to roles await _userManager.AddToRoleAsync(user, StaticRoleNames.Tenants.User); //Add to OUs var randomOus = RandomHelper.GenerateRandomizedList(organizationUnits).Take(RandomHelper.GetRandom(0, 3)); foreach (var ou in randomOus) { await _userManager.AddToOrganizationUnitAsync(user, ou); } //Set profile picture if (RandomHelper.GetRandom(100) < 70) //A user will have a profile picture in 70% probability. { await SetRandomProfilePictureAsync(user); } } //Set a picture to admin! var admin = await _userManager.FindByNameAsync(AbpUserBase.AdminUserName); await SetRandomProfilePictureAsync(admin); //Create Friendships var friends = RandomHelper.GenerateRandomizedList(users).Take(3).ToList(); foreach (var friend in friends) { await _friendshipManager.CreateFriendshipAsync( new Friendship( admin.ToUserIdentifier(), friend.ToUserIdentifier(), tenant.TenancyName, friend.UserName, friend.ProfilePictureId, FriendshipState.Accepted) ); await _friendshipManager.CreateFriendshipAsync( new Friendship( friend.ToUserIdentifier(), admin.ToUserIdentifier(), tenant.TenancyName, admin.UserName, admin.ProfilePictureId, FriendshipState.Accepted) ); } //Create chat message var friendWithMessage = RandomHelper.GenerateRandomizedList(friends).First(); var sharedMessageId = Guid.NewGuid(); _chatMessageRepository.InsertAndGetId( new ChatMessage( friendWithMessage.ToUserIdentifier(), admin.ToUserIdentifier(), ChatSide.Sender, L("Demo_SampleChatMessage"), ChatMessageReadState.Read, sharedMessageId, ChatMessageReadState.Unread ) ); _chatMessageRepository.InsertAndGetId( new ChatMessage( admin.ToUserIdentifier(), friendWithMessage.ToUserIdentifier(), ChatSide.Receiver, L("Demo_SampleChatMessage"), ChatMessageReadState.Unread, sharedMessageId, ChatMessageReadState.Read ) ); }
public async Task <IActionResult> Login(LoginInputModel model, string button) { // check if we are in the context of an authorization request var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); // the user clicked the "cancel" button if (button != "login") { if (context != null) { // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (context.IsNativeClient()) { // The client is native, so this change in how to // return the response is for better UX for the end user. return(this.LoadingPage("Redirect", model.ReturnUrl)); } return(Redirect(model.ReturnUrl)); } else { // since we don't have a valid context, then we just go back to the home page return(Redirect("~/")); } } if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure : true); if (result.Succeeded) { var user = await _userManager.FindByNameAsync(model.Username); await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId : context?.Client.ClientId)); if (context != null) { if (context.IsNativeClient()) { // The client is native, so this change in how to // return the response is for better UX for the end user. return(this.LoadingPage("Redirect", model.ReturnUrl)); } // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return(Redirect(model.ReturnUrl)); } // request for a local page if (Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } else if (string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect("~/")); } else { // user might have clicked on a malicious link - should be logged throw new ArgumentException("invalid return URL"); } } await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId : context?.Client.ClientId)); ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error var vm = await BuildLoginViewModelAsync(model); return(View(vm)); }
public async Task<Post> SetUser(UserManager<User> userManager) { var user = await userManager.FindByNameAsync(UserName); User = user == null ? new User { UserName = "******" } : user; return this; }
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(); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email, EmailConfirmed = true }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { //Agregar usuario a rol de usuario normal var userTemp = await _userManager.FindByNameAsync(Input.UserName); if (!await _roleManager.RoleExistsAsync("User")) { await _roleManager.CreateAsync(new IdentityRole("User")); } if (!await _userManager.IsInRoleAsync(userTemp, "User")) { await _userManager.AddToRoleAsync(userTemp, "User"); } _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) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> Index(string user) { var books = _bookService.GetList(); var userId = 0; AppUser currentUser = new AppUser(); Models.Member member = new Models.Member(); CustomModel model = new CustomModel(); AppUser profileUser = new AppUser(); TempData["Active"] = "profile"; TempData["sa"] = TempData["deneme"]; var userprofile = TempData["currentUser"]; var appUser = await _userManager.FindByNameAsync(User.Identity.Name); if (userprofile == null) { profileUser = null; member.Id = appUser.Id; member.FirstName = appUser.FirstName; member.LastName = appUser.LastName; member.Email = appUser.Email; member.UserName = appUser.UserName; member.Description = appUser.Description; member.Picture = appUser.ProfileImageFile; model.Member = member; userId = appUser.Id; } else { profileUser = await _userManager.FindByNameAsync(userprofile.ToString()); member.Id = profileUser.Id; member.FirstName = profileUser.FirstName; member.LastName = profileUser.LastName; member.Email = profileUser.Email; member.UserName = profileUser.UserName; member.Description = profileUser.Description; member.Picture = profileUser.ProfileImageFile; model.Member = member; userId = profileUser.Id; } if (user == null) { currentUser = null; member.Id = appUser.Id; member.FirstName = appUser.FirstName; member.LastName = appUser.LastName; member.Email = appUser.Email; member.UserName = appUser.UserName; member.Description = appUser.Description; member.Picture = appUser.ProfileImageFile; model.Member = member; userId = appUser.Id; } else { currentUser = await _userManager.FindByNameAsync(user); member.Id = currentUser.Id; member.FirstName = currentUser.FirstName; member.LastName = currentUser.LastName; member.Email = currentUser.Email; member.UserName = currentUser.UserName; member.Description = currentUser.Description; member.Picture = currentUser.ProfileImageFile; model.Member = member; userId = currentUser.Id; } if (currentUser != null) { if (appUser.UserName != currentUser.UserName) { model.IsProfile = false; } else { model.IsProfile = true; } } if (profileUser != null) { if (appUser.UserName == profileUser.UserName) { model.IsProfile = true; } else { model.IsProfile = false; } } List <Review> reviews = new List <Review>(); List <Entities.Concrete.Quotation> quotations = new List <Entities.Concrete.Quotation>(); var userbooks = _bookAppUserService.GetByAppUserId(userId); foreach (var book in userbooks) { if (book.Reviews.Count > 0) { reviews.AddRange(book.Reviews); } if (book.Quotations.Count > 0) { quotations.AddRange(book.Quotations); } } quotations.ShuffleMethod(); reviews.ShuffleMethod(); ViewBag.Comment = reviews; ViewBag.Quotations = quotations; return(View(model)); }
public async Task <IActionResult> Register(RegisterViewModel model) { if (!ModelState.IsValid || String.IsNullOrWhiteSpace(model.Email)) // Note: this means that external logins not providing an email are unusable. { return(View("Register", model)); } var email = _userManager.NormalizeKey(model.Email); UserLoginInfo info = await _signInManager.GetExternalLoginInfoAsync(); var userEmpty = new ApplicationUser() { UserName = model.UserName, Email = email, DateCreated = DateTimeOffset.UtcNow, SecurityStamp = "", FullName = model.FullName, FavColor = model.FavColor, // !! ADDING FIELDS: If you want users to input field on register }; userEmpty.Email = email; //userEmpty.FavColor = "Red"; // !! ADDING FIELDS: If you want to set default value for all registering users if (info == null) // User trying to register locally { userEmpty.EmailConfirmed = true; var userWithConfirmedEmail = await _userManager.FindByLoginAsync("Email", email); userEmpty.Id = email; // Only for token verification, is set to null later var isTokenValid = await _userManager.VerifyUserTokenAsync(userEmpty, "Default", "Register", model.Token); if (isTokenValid && userWithConfirmedEmail == null) // Supplied email is verified & user does not exist { userEmpty.Id = null; info = new UserLoginInfo("Email", userEmpty.Email, "Email"); } else { _notice.AddErrors(ModelState); return(View(nameof(Register), model)); } } else // User trying to register after external login { userEmpty.EmailConfirmed = false; } var createResult = await _userManager.CreateAsync(userEmpty); if (createResult.Succeeded) { var addLoginResult = await _userManager.AddLoginAsync(userEmpty, info); if (addLoginResult.Succeeded) { var user = await _userManager.FindByNameAsync(model.UserName); // This works because usernames are unique // If this is the first user ever created, make an Administrator if (_userManager.Users.Count() == 1) { var makeAdminResult = await _userManager.AddToRoleAsync(user, "Administrator"); } await _events.AddEvent(AuthEventType.Register, JsonConvert.SerializeObject(new { LoginProvider = info?.LoginProvider ?? "Email", ProviderKey = info?.ProviderKey ?? email }), user); await _signInManager.SignInAsync(user, isPersistent : model.RememberMe); return(RedirectToLocal(model.ReturnUrl)); // Success } } else { _notice.AddErrors(ModelState); return(View(nameof(Register), model)); } await _userManager.DeleteAsync(userEmpty); _notice.AddErrors(ModelState); return(View(nameof(Register), model)); }
public async Task <User> FindByNameAsync(string username) { return(await _userManager.FindByNameAsync(username)); }
public async Task <SignInResult> Login(string ip, string sessionCode, LoginRequest login) { ValidationResult validationResult = _loginValidator.Validate(login); if (!validationResult.IsValid) { _logger.LogError($"Invalid LoginRequest. UserName {login?.UserName}"); return(SignInResult.Failed); } await _signInManager.SignOutAsync(); AppUserEntity appUser = await _userManager.FindByNameAsync(login.UserName); if (appUser == null) { _logger.LogInformation($"No user with username {login.UserName}"); return(SignInResult.Failed); } if (sessionCode != null) { _sessionService.Logout(sessionCode, appUser.Id, SessionEndTypes.Expired); } if (!appUser.CanLogin()) { _logger.LogInformation($"User is not allowed to login. User {appUser.Id}"); return(SignInResult.Failed); } appUser.SessionCode = Guid.NewGuid().ToString(); Result addSessionResult = _sessionService.Add(appUser.SessionCode, appUser.Id, ip); if (addSessionResult.Failure) { return(SignInResult.Failed); } SignInResult result = await _signInManager.PasswordSignInAsync(appUser, login.Password, login.RememberMe, lockoutOnFailure : true); if (!result.Succeeded) { if (result.RequiresTwoFactor) { _logger.LogInformation($"Login Requires TwoFactor. User {appUser.Id}"); _sessionService.Logout(appUser.SessionCode, appUser.Id, SessionEndTypes.TwoFactorLogin); } if (!result.IsLockedOut) { _logger.LogInformation($"Failed to log in user. User {appUser.Id}"); _sessionService.Logout(appUser.SessionCode, appUser.Id, SessionEndTypes.InvalidLogin); } return(result); } _logger.LogInformation($"User id loged in. UserId {appUser.Id}"); return(result); }
private string _getCurrentlyLoggedInUserRole(string username) { return(_userManager.FindByNameAsync(username).Result.Role); }
protected async virtual Task <TUser> FindUserAsync(string username) { return(await userManager.FindByNameAsync(username)); }
// GET: Project/ProjectConfigs public ActionResult Index() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (Request.IsAuthenticated) { ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result; if (!userManager.IsInRole(User.Identity.GetUserId(),"Configuration") && !userManager.IsInRole(User.Identity.GetUserId(), "System Admin")) { return RedirectToAction("AccessBlock", "Account", new { area = "" }); } else { return View(); } } else { return RedirectToAction("Login", "Account", new { area = "" }); } }
public async Task <IActionResult> Exchange(OpenIdConnectRequest request) { if (request.IsPasswordGrantType()) { var user = await _userManager.FindByNameAsync(request.Username); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // Ensure the user is allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Reject the token request if two-factor authentication has been enabled by the user. if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Ensure the user is not already locked out. if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // Ensure the password is valid. if (!await _userManager.CheckPasswordAsync(user, request.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } // Create a new authentication ticket. var ticket = await CreateTicketAsync(request, user); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } else if (request.GrantType == "urn:ietf:params:oauth:grant-type:external_identity_token") { //Assertion should be the access_token // Reject the request if the "assertion" parameter is missing. if (string.IsNullOrEmpty(request.Assertion)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "The mandatory 'assertion' parameter was missing." })); } ; ExternalAuthProviders provider; var providerExists = Enum.TryParse(request["provider"].ToString(), out provider); if (!providerExists) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "The mandatory 'provider' parameter was missing." })); } ; var isValid = await _externalAuthManager.VerifyExternalAccessToken(request.Assertion, provider); if (!isValid) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "Invalid access_token, this usually happens when it is expired" })); } var profile = await _externalAuthManager.GetProfile(request.Assertion, provider); var user = await _userManager.FindByEmailAsync(profile.email); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The user does not exist" })); } var ticket = await CreateTicketAsync(request, user); // Create a new ClaimsIdentity containing the claims that // will be used to create an id_token and/or an access token. //var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); // Manually validate the identity token issued by Google, // including the issuer, the signature and the audience. // Then, copy the claims you need to the "identity" instance. // Create a new authentication ticket holding the user identity. //var ticket = new AuthenticationTicket( // new ClaimsPrincipal(identity), // new AuthenticationProperties(), // OpenIdConnectServerDefaults.AuthenticationScheme); //ticket.SetScopes( // OpenIdConnectConstants.Scopes.OpenId, // OpenIdConnectConstants.Scopes.OfflineAccess); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.UnsupportedGrantType, ErrorDescription = "The specified grant type is not supported." })); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } var phoneNumber = await _userManager.GetPhoneNumberAsync(user); if (Input.PhoneNumber != phoneNumber) { var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber); if (!setPhoneResult.Succeeded) { StatusMessage = "Unexpected error when trying to set phone number."; return(RedirectToPage()); } } var firstName = user.FirstName; var lastName = user.LastName; if (Input.FirstName != firstName) { user.FirstName = Input.FirstName; await _userManager.UpdateAsync(user); } if (Input.LastName != lastName) { user.LastName = Input.LastName; await _userManager.UpdateAsync(user); } if (user.UsernameChangeLimit > 0) { if (Input.Username != null) { if (Input.Username != user.UserName) { var userNameExists = await _userManager.FindByNameAsync(Input.Username); if (userNameExists != null) { StatusMessage = "User name already taken. Select a different username."; return(RedirectToPage()); } var setUserName = await _userManager.SetUserNameAsync(user, Input.Username); if (!setUserName.Succeeded) { StatusMessage = "Unexpected error when trying to set user name."; return(RedirectToPage()); } else { user.UsernameChangeLimit -= 1; await _userManager.UpdateAsync(user); } } } } if (Request.Form.Files.Count > 0) { IFormFile file = Request.Form.Files.FirstOrDefault(); using (var dataStream = new MemoryStream()) { await file.CopyToAsync(dataStream); user.ProfilePicture = dataStream.ToArray(); } await _userManager.UpdateAsync(user); } await _signInManager.RefreshSignInAsync(user); StatusMessage = "Your profile has been updated"; return(RedirectToPage()); }
public async Task <IActionResult> UserEdit(UserManagementDetailsViewModel vm) { if (!ModelState.IsValid) { return(View(vm)); } var user = await _userManager.FindByNameAsync(vm.Username); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var email = user.Email; if (vm.Email != email) { var setEmailResult = await _userManager.SetEmailAsync(user, vm.Email); if (!setEmailResult.Succeeded) { throw new ApplicationException( $"Unexpected error occurred setting email for user with ID '{user.Id}'."); } } var phoneNumber = user.PhoneNumber; if (vm.PhoneNumber != phoneNumber) { var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, vm.PhoneNumber); if (!setPhoneResult.Succeeded) { throw new ApplicationException( $"Unexpected error occurred setting phone number for user with ID '{user.Id}'."); } } var firstName = user.FirstName; if (vm.FirstName != firstName) { user.FirstName = vm.FirstName; var result = await _userManager.UpdateAsync(user); if (!result.Succeeded) { throw new ApplicationException( $"Unexpected error occurred setting phone number for user with ID '{user.Id}'."); } } var lastName = user.LastName; if (vm.LastName != lastName) { user.LastName = vm.LastName; var result = await _userManager.UpdateAsync(user); if (!result.Succeeded) { throw new ApplicationException( $"Unexpected error occurred setting phone number for user with ID '{user.Id}'."); } } var country = user.Country; if (vm.Country != country) { user.Country = vm.Country; var result = await _userManager.UpdateAsync(user); if (!result.Succeeded) { throw new ApplicationException( $"Unexpected error occurred setting phone number for user with ID '{user.Id}'."); } } var address = user.Address; if (vm.Address != address) { user.Address = vm.Address; var result = await _userManager.UpdateAsync(user); if (!result.Succeeded) { throw new ApplicationException( $"Unexpected error occurred setting phone number for user with ID '{user.Id}'."); } } var zipcode = user.ZipCode; if (vm.ZipCode != zipcode) { user.ZipCode = vm.ZipCode; var result = await _userManager.UpdateAsync(user); if (!result.Succeeded) { throw new ApplicationException( $"Unexpected error occurred setting phone number for user with ID '{user.Id}'."); } } StatusMessage = "Your profile has been updated"; return(RedirectToAction("UserDetails", new { username = user.UserName })); }
public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null) { Result result = new Result(); try { //if the session USER_NAME is not null, it means that a user is currently logged in //redirect the user to Dashboard page if (HttpContext.Session.GetString(SessionHelper.USER_NAME) != null) { return(RedirectToAction("Index", "Dashboard")); } ViewData["ReturnUrl"] = returnUrl; if (string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.Password)) { ModelState.AddModelError(string.Empty, "Invalid Credentials"); result.Message = "Invalid username or password."; result.Success = false; return(Json(result)); } if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.UserName); if (user != null) { var tempRole = await _userManager.GetRolesAsync(user); ViewBag.userName = user.UserName; var user2 = await _userManager.GetUserAsync(User); if (!await _userManager.IsEmailConfirmedAsync(user)) { // TODO: create a separate action for resending the confirmation token // string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account-Resend"); // Uncomment to debug locally // ViewBag.Link = callbackUrl; // ViewBag.errorMessage = "You must have a confirmed email to log on. " // + "The confirmation token has been resent to your email account."; ModelState.AddModelError(string.Empty, "You must have a confirmed email to log on."); return(View()); } else { bool isSucceeded = false; // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var signIn = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure : false); isSucceeded = signIn.Succeeded; if (isSucceeded) { var role = await _userManager.GetRolesAsync(user); var modules = await _queryService.GetModules(role.First()); var userRole = role.First(); //if DPO or ADMIN is logged, add a 0 value to userDept. string userDept = user.DepartmentId ?? "0"; string companyName = (await _queryService.GetCompanyInfo() == null) ? "" : (await _queryService.GetCompanyInfo()).Name ?? ""; //store in session the neccessary data HttpContext.Session.SetString(SessionHelper.COMPANY_NAME, companyName); HttpContext.Session.SetString(SessionHelper.USER_NAME, user.UserName); HttpContext.Session.SetString(SessionHelper.USER_ID, user.Id.ToString()); HttpContext.Session.SetObjectAsJson(SessionHelper.USER, user); HttpContext.Session.SetString(SessionHelper.USER_NAME, user.UserName); HttpContext.Session.SetString(SessionHelper.ROLES, userRole); HttpContext.Session.SetString(SessionHelper.USER_DEPT, userDept); HttpContext.Session.SetObjectAsJson(SessionHelper.MODULES, modules); HttpContext.Session.SetString(SessionHelper.DONE_SETUP, user.DoneSetUp.ToString()); //this session will be used for redirecting of the user, specifically for DPO and ADMIN. if (tempRole.First() == "ADMINISTRATOR" || tempRole.First() == "DPO") { if (user.HasPasswordChanged == false) { HttpContext.Session.SetString(SessionHelper.HASPASSWORDCHANGED, "0"); } else if (user.HasPasswordChanged == true) { HttpContext.Session.SetString(SessionHelper.HASPASSWORDCHANGED, "1"); } //showmodal for user setup if DoneSetup=0 //ShowModal for Userguide if DoneSetup =1 if ((user.DoneSetUp == 0) || (user.DoneSetUp == 1)) { HttpContext.Session.SetString(SessionHelper.SHOW_MODAL, "1"); } } else if (tempRole.First() == "USER" || tempRole.First() == "DEPTHEAD") { //showModal for userguide in Dashboard if (user.DoneSetUp == 0) { HttpContext.Session.SetString(SessionHelper.DONE_SETUP, "1"); HttpContext.Session.SetString(SessionHelper.SHOW_MODAL, "1"); } } //Update user DoneSetup to 2 to disable force setup and userguide note if (HttpContext.Session.GetString(SessionHelper.DONE_SETUP) == "1") { user.DoneSetUp = 2; var updateUserSetup = await _userManager.UpdateAsync(user); } // userRights var moduleRights = await _queryService.GetModules("ADMINISTRATOR"); List <UserRightsViewModel> rights = new List <UserRightsViewModel>(); // get the user rights per module. // note: DPO and ADMIN rights can not be edited. // also DPO and ADMIN are the only one who can edit other's(DEPTHEAD, and USER) rights. foreach (var item in moduleRights) { var ur = await _queryService.GetUserRights(user.Id.ToString(), item.Id); var ur_model = new UserRightsViewModel(); ur_model.ModuleId = item.Id; ur_model.ModuleName = item.Name; if (ur != null) { ur_model.View = ur.View ? 1 : 0; ur_model.Add = ur.Add ? 1 : 0; ur_model.Edit = ur.Edit ? 1 : 0; } else { ur_model.View = 0; ur_model.Add = 0; ur_model.Edit = 0; } rights.Add(ur_model); } ViewBag.rightsList = rights; HttpContext.Session.SetObjectAsJson(SessionHelper.USER_RIGHTS, rights); result.Message = "Logged in successfully."; result.Success = true; result.IsRedirect = true; result.RedirectUrl = "Dashboard/Index"; return(Json(result)); } else if (!isSucceeded) { result.Message = "Invalid username or password."; result.Success = false; return(Json(result)); } } } else { result.Message = "Invalid username or password."; result.Success = false; return(Json(result)); } } // if program reached here, something failed, redisplay form return(View()); } catch (Exception e) { _logger.LogError("Error calling Login: {0}", e.Message); throw; } }
public async Task<IActionResult> Token([FromBody] UserLogin model) { var user = await userManager.FindByNameAsync(model.UserName); // nếu người dùng không tồn tại if (user == null) { return BadRequest(new { error = "user or password wrong" }); } var passOk = await userManager.CheckPasswordAsync(user, model.Password); // nếu mật khẩu không đúng if (passOk == false) { return BadRequest(new { error = "user or password wrong" }); } // nếu user và pass đúng => sinh token var now = DateTime.UtcNow; var roles = roleManager.Roles.Where(r => r.Users.Any(u => u.UserId == user.Id) ).Select(r => r.Name).ToList(); var claims = new List<Claim>{ new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim("AspNet.Identity.SecurityStamp", user.SecurityStamp), new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(DateTime.Now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64), }; claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r))); var expires = now.Add(TimeSpan.FromDays(15)); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Ngay xua co mot con ga...")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); // Create the JWT and write it to a string var jwt = new JwtSecurityToken( issuer: "RS", audience: "RS", claims: claims, notBefore: now, expires: expires, signingCredentials: creds ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return Json(new { access_token = encodedJwt, expires_in = expires, userId = user.Id }); }
public IActionResult Create() { var user = _userManager.FindByNameAsync(User.Identity.Name).Result; return(View(user)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataInitializer sampleData, UserManager<ApplicationUser> userManager) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859 try { using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>() .CreateScope()) { serviceScope.ServiceProvider.GetService<ApplicationDbContext>() .Database.Migrate(); } } catch { } } app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear()); app.UseStaticFiles(); app.UseIdentity(); // Refactor this into a seperate class // Remove hard coding of the password in the installDevices routine! app.UseBasicAuthentication(o => { o.Realm = $"j64 Alarm"; o.Events = new BasicAuthenticationEvents { OnSignIn = c => { var x = userManager.FindByNameAsync(c.UserName); x.Wait(); if (x.Result != null) { var y = userManager.CheckPasswordAsync(x.Result, c.Password); y.Wait(); if (y.Result == true) { var z = userManager.GetClaimsAsync(x.Result); z.Wait(); var identity = new ClaimsIdentity(z.Result, c.Options.AuthenticationScheme); c.Principal = new ClaimsPrincipal(identity); } } return Task.FromResult(true); } }; }); // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Seed some default entries into the database var task = sampleData.CreateMasterUser(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, UserManager<ApplicationUser> userManager, ApplicationDbContext ctx) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseIdentity(); // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715 // Refactor this into a seperate class // Remove hard coding of the password in the installDevices routine! app.UseBasicAuthentication(o => { o.Realm = $"j64 Alarm"; o.Events = new BasicAuthenticationEvents { OnSignIn = c => { var x = userManager.FindByNameAsync(c.UserName); x.Wait(); if (x.Result != null) { var y = userManager.CheckPasswordAsync(x.Result, c.Password); y.Wait(); if (y.Result == true) { var z = userManager.GetClaimsAsync(x.Result); z.Wait(); var identity = new ClaimsIdentity(z.Result, c.Options.AuthenticationScheme); c.Principal = new ClaimsPrincipal(identity); } } return Task.FromResult(true); } }; }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Seed some default entries into the database var task = new Data.UserDataInitializer(ctx, userManager).CreateMasterUser(); }
public async Task<ActionResult> RegisterFinish(OrderViewModel modelObj, string slug) { if (modelObj == null) modelObj = new OrderViewModel(); TryUpdateModel(modelObj); using (var ctx = new SportDataContext()) { var userManager = new UserManager<User>(new UserStore<User>(ctx)); var currentUser = await userManager.FindByIdAsync(User.Identity.GetUserId()); var team = SearchService.FindTeam(modelObj.Entrant, ctx); if (team == null) team = modelObj.CreateTeam(); var driver1 = await SearchService.FindUser(modelObj.Driver1License, ctx) ?? await SearchService.FindUserById(modelObj.Driver1Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver1FirstName, modelObj.Driver1LastName, ctx); var driver2 = await SearchService.FindUser(modelObj.Driver2License, ctx) ?? await SearchService.FindUserById(modelObj.Driver2Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver2FirstName, modelObj.Driver2LastName, ctx); //Защита от if (driver1==null || string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + "")) { driver1 = modelObj.CreateDriver1(); var existingUser = await userManager.FindByNameAsync(driver1.UserName); if (existingUser != null) driver1.UserName = Guid.NewGuid().ToString(); } if (driver2 == null || string.IsNullOrWhiteSpace(driver2.LastName + driver2.FirstName + "")) { driver2 = modelObj.CreateDriver2(); var existingUser = await userManager.FindByNameAsync(driver2.UserName); if (existingUser != null) driver2.UserName = Guid.NewGuid().ToString(); } var car = modelObj.CreateCar(); var ev = await EventService.GetEvent(slug, ctx); Dictionary<SubEvent, Order> orders = new Dictionary<SubEvent,Order>(); ViewBag.Error = null; if (driver1.Id == driver2.Id) { ViewBag.Error = "В вашей заявке совпадают первый и второй водитель. Пожалуйста, проверьте правильность заполнения заявки. Если у вас в настоящее время нет полной информации о составе экипажа - оставьте недостающие поля пустыми."; } if (string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + driver2.LastName + driver2.FirstName)) { ViewBag.Error = "Укажите пожалуйста в заявке не менее 1 водителя."; } if (modelObj.Groups == null || modelObj.Groups.Count() == 0) { ViewBag.Error = "В вашей заявке на " + ev.Title + " не указано ни одной зачетной группы. Пожалуйста, укажите минимум 1 зачет из списка."; } if(!string.IsNullOrWhiteSpace(ViewBag.Error)) return View("RegistrationError", ev); foreach (var group in modelObj.Groups) { var tokens = group.Split('_'); var subEv = ev.SubEvents.First(e=>e.Id == int.Parse(tokens[0])); if(!orders.ContainsKey(subEv)) { orders.Add(subEv, new Order() { Driver = driver1, CoDriver = driver2, Team = team, Car = car, Redimmed = false, Confirmed = false, CreatedAt= DateTime.Now, StartNumber="", Group = new List<Group>(), CreatedBy = currentUser }); } orders[subEv].Group.Add(subEv.Groups.First(g => g.Id == int.Parse(tokens[1]))); } foreach (var item in orders.Keys) { item.Tag.Orders = item.Tag.Orders ?? new List<Order>(); item.Tag.Orders.Add(orders[item]); } try { await ctx.SaveChangesAsync(); } catch (Exception ex) { throw; } return View("RegistrationComplete", ev); } }
public async Task <string> GetUserIdAsync(string userName) { var user = await UserManager.FindByNameAsync(userName); return(user != null ? user.Id : null); }
public async Task<ApplicationUser> ReturnCurrentUserAsync() { var store = new UserStore<ApplicationUser>(new ApplicationDbContext()); var userManager = new UserManager<ApplicationUser>(store); ApplicationUser user = await userManager.FindByNameAsync(User.Identity.Name); store.Dispose(); userManager.Dispose(); return user; }
public async Task Seed() { if (!_roleManager.Roles.Any()) { await _roleManager.CreateAsync(new AppRole() { Name = "Admin", NormalizedName = "Admin", Description = "Top manager" }); await _roleManager.CreateAsync(new AppRole() { Name = "Staff", NormalizedName = "Staff", Description = "Staff" }); await _roleManager.CreateAsync(new AppRole() { Name = "Customer", NormalizedName = "Customer", Description = "Customer" }); } if (!_userManager.Users.Any()) { await _userManager.CreateAsync(new AppUser() { UserName = "******", FullName = "Administrator", Email = "*****@*****.**", Balance = 0, DateCreated = DateTime.Now, DateModified = DateTime.Now, Status = Status.Active }, "123654$"); var user = await _userManager.FindByNameAsync("admin"); await _userManager.AddToRoleAsync(user, "Admin"); } if (!_context.Contacts.Any()) { _context.Contacts.Add(new Contact() { Id = CommonConstants.DefaultContactId, Address = "No 04 Lane 250/39 Kim giang Hoàng Mai-Đại Kim-Hà Nội", Email = "*****@*****.**", Name = "Shop Online", Phone = "0983491814", Status = Status.Active, Website = "http://pandashop.com", Lat = 21.0435009, Lng = 105.7894758 }); } if (!_context.Functions.Any()) { _context.Functions.AddRange(new List <Function>() { new Function() { Id = "SYSTEM", Name = "System", ParentId = null, SortOrder = 1, Status = Status.Active, URL = "/", IconCss = "fa-desktop" }, new Function() { Id = "ROLE", Name = "Role", ParentId = "SYSTEM", SortOrder = 1, Status = Status.Active, URL = "/admin/role/index", IconCss = "fa-home" }, new Function() { Id = "FUNCTION", Name = "Function", ParentId = "SYSTEM", SortOrder = 2, Status = Status.Active, URL = "/admin/function/index", IconCss = "fa-home" }, new Function() { Id = "USER", Name = "User", ParentId = "SYSTEM", SortOrder = 3, Status = Status.Active, URL = "/admin/user/index", IconCss = "fa-home" }, new Function() { Id = "ACTIVITY", Name = "Activity", ParentId = "SYSTEM", SortOrder = 4, Status = Status.Active, URL = "/admin/activity/index", IconCss = "fa-home" }, new Function() { Id = "ERROR", Name = "Error", ParentId = "SYSTEM", SortOrder = 5, Status = Status.Active, URL = "/admin/error/index", IconCss = "fa-home" }, new Function() { Id = "SETTING", Name = "Configuration", ParentId = "SYSTEM", SortOrder = 6, Status = Status.Active, URL = "/admin/setting/index", IconCss = "fa-home" }, new Function() { Id = "PRODUCT", Name = "Product Management", ParentId = null, SortOrder = 2, Status = Status.Active, URL = "/", IconCss = "fa-chevron-down" }, new Function() { Id = "PRODUCT_CATEGORY", Name = "Category", ParentId = "PRODUCT", SortOrder = 1, Status = Status.Active, URL = "/admin/productcategory/index", IconCss = "fa-chevron-down" }, new Function() { Id = "PRODUCT_LIST", Name = "Product", ParentId = "PRODUCT", SortOrder = 2, Status = Status.Active, URL = "/admin/product/index", IconCss = "fa-chevron-down" }, new Function() { Id = "BILL", Name = "Bill", ParentId = "PRODUCT", SortOrder = 3, Status = Status.Active, URL = "/admin/bill/index", IconCss = "fa-chevron-down" }, new Function() { Id = "CONTENT", Name = "Content", ParentId = null, SortOrder = 3, Status = Status.Active, URL = "/", IconCss = "fa-table" }, new Function() { Id = "BLOG", Name = "Blog", ParentId = "CONTENT", SortOrder = 1, Status = Status.Active, URL = "/admin/blog/index", IconCss = "fa-table" }, new Function() { Id = "PAGE", Name = "Page", ParentId = "CONTENT", SortOrder = 2, Status = Status.Active, URL = "/admin/page/index", IconCss = "fa-table" }, new Function() { Id = "UTILITY", Name = "Utilities", ParentId = null, SortOrder = 4, Status = Status.Active, URL = "/", IconCss = "fa-clone" }, new Function() { Id = "FOOTER", Name = "Footer", ParentId = "UTILITY", SortOrder = 1, Status = Status.Active, URL = "/admin/footer/index", IconCss = "fa-clone" }, new Function() { Id = "FEEDBACK", Name = "Feedback", ParentId = "UTILITY", SortOrder = 2, Status = Status.Active, URL = "/admin/feedback/index", IconCss = "fa-clone" }, new Function() { Id = "ANNOUNCEMENT", Name = "Announcement", ParentId = "UTILITY", SortOrder = 3, Status = Status.Active, URL = "/admin/announcement/index", IconCss = "fa-clone" }, new Function() { Id = "CONTACT", Name = "Contact", ParentId = "UTILITY", SortOrder = 4, Status = Status.Active, URL = "/admin/contact/index", IconCss = "fa-clone" }, new Function() { Id = "SLIDE", Name = "Slide", ParentId = "UTILITY", SortOrder = 5, Status = Status.Active, URL = "/admin/slide/index", IconCss = "fa-clone" }, new Function() { Id = "ADVERTISMENT", Name = "Advertisment", ParentId = "UTILITY", SortOrder = 6, Status = Status.Active, URL = "/admin/advertistment/index", IconCss = "fa-clone" }, new Function() { Id = "REPORT", Name = "Report", ParentId = null, SortOrder = 5, Status = Status.Active, URL = "/", IconCss = "fa-bar-chart-o" }, new Function() { Id = "REVENUES", Name = "Revenue report", ParentId = "REPORT", SortOrder = 1, Status = Status.Active, URL = "/admin/report/revenues", IconCss = "fa-bar-chart-o" }, new Function() { Id = "ACCESS", Name = "Visitor Report", ParentId = "REPORT", SortOrder = 2, Status = Status.Active, URL = "/admin/report/visitor", IconCss = "fa-bar-chart-o" }, new Function() { Id = "READER", Name = "Reader Report", ParentId = "REPORT", SortOrder = 3, Status = Status.Active, URL = "/admin/report/reader", IconCss = "fa-bar-chart-o" }, }); } if (_context.Footers.Count(x => x.Id == CommonConstants.DefaultFooterId) == 0) { string content = "Footer"; _context.Footers.Add(new Footer() { Id = CommonConstants.DefaultFooterId, Content = content }); _context.SaveChanges(); } if (!_context.Colors.Any()) { List <Color> listColor = new List <Color>() { new Color() { Name = "Đen", Code = "#000000" }, new Color() { Name = "Trắng", Code = "#FFFFFF" }, new Color() { Name = "Đỏ", Code = "#ff0000" }, new Color() { Name = "Xanh", Code = "#1000ff" }, }; _context.Colors.AddRange(listColor); } if (!_context.AdvertistmentPages.Any()) { List <AdvertistmentPage> pages = new List <AdvertistmentPage>() { new AdvertistmentPage() { Id = "home", Name = "Trang chủ", AdvertistmentPositions = new List <AdvertistmentPosition>() { new AdvertistmentPosition() { Id = "home-left", Name = "Bên trái" } } }, new AdvertistmentPage() { Id = "product-cate", Name = "Danh mục sản phẩm", AdvertistmentPositions = new List <AdvertistmentPosition>() { new AdvertistmentPosition() { Id = "product-cate-left", Name = "Bên trái" } } }, new AdvertistmentPage() { Id = "product-detail", Name = "Chi tiết sản phẩm", AdvertistmentPositions = new List <AdvertistmentPosition>() { new AdvertistmentPosition() { Id = "product-detail-left", Name = "Bên trái" } } }, }; _context.AdvertistmentPages.AddRange(pages); } if (!_context.Slides.Any()) { List <Slide> slides = new List <Slide>() { new Slide() { Name = "Slide 1", Image = "/client-side/images/slider/slide-1.jpg", Url = "#", DisplayOrder = 0, GroupAlias = "top", Status = true }, new Slide() { Name = "Slide 2", Image = "/client-side/images/slider/slide-2.jpg", Url = "#", DisplayOrder = 1, GroupAlias = "top", Status = true }, new Slide() { Name = "Slide 3", Image = "/client-side/images/slider/slide-3.jpg", Url = "#", DisplayOrder = 2, GroupAlias = "top", Status = true }, new Slide() { Name = "Slide 1", Image = "/client-side/images/brand1.png", Url = "#", DisplayOrder = 1, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 2", Image = "/client-side/images/brand2.png", Url = "#", DisplayOrder = 2, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 3", Image = "/client-side/images/brand3.png", Url = "#", DisplayOrder = 3, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 4", Image = "/client-side/images/brand4.png", Url = "#", DisplayOrder = 4, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 5", Image = "/client-side/images/brand5.png", Url = "#", DisplayOrder = 5, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 6", Image = "/client-side/images/brand6.png", Url = "#", DisplayOrder = 6, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 7", Image = "/client-side/images/brand7.png", Url = "#", DisplayOrder = 7, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 8", Image = "/client-side/images/brand8.png", Url = "#", DisplayOrder = 8, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 9", Image = "/client-side/images/brand9.png", Url = "#", DisplayOrder = 9, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 10", Image = "/client-side/images/brand10.png", Url = "#", DisplayOrder = 10, GroupAlias = "brand", Status = true }, new Slide() { Name = "Slide 11", Image = "/client-side/images/brand11.png", Url = "#", DisplayOrder = 11, GroupAlias = "brand", Status = true }, }; _context.Slides.AddRange(slides); } if (!_context.Sizes.Any()) { List <Size> listSize = new List <Size>() { new Size() { Name = "XXL" }, new Size() { Name = "XL" }, new Size() { Name = "L" }, new Size() { Name = "M" }, new Size() { Name = "S" }, new Size() { Name = "XS" } }; _context.Sizes.AddRange(listSize); } if (!_context.ProductCategories.Any()) { List <ProductCategory> listProductCategory = new List <ProductCategory>() { new ProductCategory() { Name = "Áo nam", SeoAlias = "ao-nam", ParentId = null, Status = Status.Active, SortOrder = 1, Products = new List <Product>() { new Product() { Name = "Sản phẩm 1", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-1", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 2", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-2", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 3", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-3", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 4", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-4", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 5", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-5", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, } }, new ProductCategory() { Name = "Áo nữ", SeoAlias = "ao-nu", ParentId = null, Status = Status.Active, SortOrder = 2, Products = new List <Product>() { new Product() { Name = "Sản phẩm 6", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-6", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 7", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-7", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 8", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-8", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 9", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-9", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 10", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-10", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, } }, new ProductCategory() { Name = "Giày nam", SeoAlias = "giay-nam", ParentId = null, Status = Status.Active, SortOrder = 3, Products = new List <Product>() { new Product() { Name = "Sản phẩm 11", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-11", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 12", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-12", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 13", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-13", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 14", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-14", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 15", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-15", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, } }, new ProductCategory() { Name = "Giày nữ", SeoAlias = "giay-nu", ParentId = null, Status = Status.Active, SortOrder = 4, Products = new List <Product>() { new Product() { Name = "Sản phẩm 16", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-16", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 17", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-17", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 18", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-18", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 19", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-19", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, new Product() { Name = "Sản phẩm 20", Image = "/client-side/images/products/product-1.jpg", SeoAlias = "san-pham-20", Price = 1000, Status = Status.Active, OriginalPrice = 1000 }, } } }; _context.ProductCategories.AddRange(listProductCategory); } if (!_context.SystemConfigs.Any(x => x.Id == "HomeTitle")) { _context.SystemConfigs.Add(new SystemConfig() { Id = "HomeTitle", Name = "Tiêu đề trang chủ", Value1 = "Trang chủ Shop", Status = Status.Active }); } if (!_context.SystemConfigs.Any(x => x.Id == "HomeMetaKeyword")) { _context.SystemConfigs.Add(new SystemConfig() { Id = "HomeMetaKeyword", Name = "Từ khoá trang chủ", Value1 = "Trang chủ Shop", Status = Status.Active }); } if (!_context.SystemConfigs.Any(x => x.Id == "HomeMetaDescription")) { _context.SystemConfigs.Add(new SystemConfig() { Id = "HomeMetaDescription", Name = "Mô tả trang chủ", Value1 = "Trang chủ Shop", Status = Status.Active }); } _context.SaveChanges(); }
public string GetGender() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result; if (user.Gender == "M") { return "Male"; } else if (user.Gender == "F") { return "Female"; } else { return ""; } }
public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = null; //_logger.LogInformation("access login page"); if (ModelState.IsValid) { if (model.ClientDate.ToShortDateString() != DateTime.Now.ToShortDateString()) { ModelState.AddModelError(string.Empty, "Date Not Up-to-Date !!"); return(View(model)); } //first try to login with username IdentityUser user = await _userManager.FindByNameAsync(model.Email); var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false); if (!result.Succeeded && !result.RequiresTwoFactor && !result.IsLockedOut) { //now try to login with email user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure : false); } } if (result.Succeeded) { // HttpContext.User = await _signInManager.CreateUserPrincipalAsync(user); //first check username already loggedin Config config = ConfigJSON.Read(); Store store = _context.Store.FirstOrDefault(); if (!User.Identity.IsAuthenticated && config.LoggedInUsers.Contains(user.UserName)) { //ModelState.AddModelError(string.Empty, "You're currently logged in to another system !!"); //await _signInManager.SignOutAsync(); //return View(model); } else { config.LoggedInUsers.Remove(user.UserName); config.LoggedInUsers.Add(user.UserName); ConfigJSON.Write(config); } //get user role var role = _context.UserViewModel.FirstOrDefault(x => x.UserName == user.UserName); var rolePermission = _context.RoleWisePermission.FirstOrDefault(x => x.RoleId == role.RoleId || x.RoleId == role.Role); //save to session HttpContext.Session.SetString("Role", JsonConvert.SerializeObject(role)); HttpContext.Session.SetString("TotalMenu", JsonConvert.SerializeObject(_context.Menu)); HttpContext.Session.SetString("Menus", JsonConvert.SerializeObject(_context.RoleWiseMenuPermission.Where(x => x.RoleId == role.Role).Include(x => x.Menu))); HttpContext.Session.SetString("Store", JsonConvert.SerializeObject(store)); HttpContext.Session.SetString("RolePermission", JsonConvert.SerializeObject(rolePermission)); if (model.TerminalId != 0) { HttpContext.Session.SetString("TerminalId", model.TerminalId.ToString()); HttpContext.Session.SetString("Terminal", model.TerminalName); //await _userManager.AddClaimAsync(user, new Claim("Terminal", model.TerminalId.ToString())); //await _userManager.AddClaimAsync(user, new Claim("TerminalName", model.TerminalName.ToString())); } else { //check if user required terminal //var roleName = User.FindFirstValue(ClaimTypes.Role); //var role = _roleManager.FindByNameAsync(roleName); bool requireTerminalToLogin = rolePermission == null ? false : rolePermission.Require_Terminal_To_Login; if (requireTerminalToLogin) { ModelState.AddModelError(string.Empty, "You can only login from Terminals"); await _signInManager.SignOutAsync(); return(View(model)); } else { //select default terminal var terminal = _context.Terminal.FirstOrDefault(); if (terminal != null) { HttpContext.Session.SetString("TerminalId", terminal.Id.ToString()); HttpContext.Session.SetString("Terminal", terminal.Name.ToString()); //await _userManager.AddClaimAsync(user, new Claim("Terminal", terminal.Id.ToString())); //await _userManager.AddClaimAsync(user, new Claim("TerminalName", terminal.Name.ToString())); } } } config.Environment = "successfully login"; ConfigJSON.Write(config); if (!string.IsNullOrEmpty(returnUrl) && returnUrl != "/") { return(RedirectToLocal(returnUrl)); } else { if (store.INITIAL == "WHS") { return(RedirectToAction("CrLanding", "SalesInvoice", new { Mode = "tax" })); } else { return(RedirectToAction("Landing", "SalesInvoice")); } //return RedirectToAction("CrLanding", "SalesInvoice", new { Mode = "tax" }); } } if (result.RequiresTwoFactor) { return(RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return(View("Lockout")); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(View(model)); } } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <bool> CheckAccountExist(string username) { var accountExist = await _userManager.FindByNameAsync(username); return(accountExist != null); }
public ActionResult SchemeAddToUser(string UserName, string[] SchemeName) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); ApplicationUser user = userManager.FindByNameAsync(UserName).Result; user.Scheme = string.Join(",", SchemeName); userManager.Update(user); ViewBag.ResultMessageAddScheme = "Scheme's added to User successfully"; // prepopulat roles for the view dropdown var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); var schemeList = db.Schemes.Select(m => new { Value = m.Name, Text = m.Name }).Distinct().ToList(); ViewBag.Roles = list; var listUsers = context.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList(); ViewBag.Users = listUsers; ViewBag.SchemeList = new MultiSelectList(schemeList, "Value", "Text"); return View("Index"); }
public static async Task InitializeAsync(UserManager <User> userManager, RoleManager <IdentityRole> roleManager) { const string password = "******"; const string adminEmail = "*****@*****.**"; const string userEmail = "*****@*****.**"; const string masEmail = "*****@*****.**"; const string clientEmail = "*****@*****.**"; // Инициализация ролей if (await roleManager.FindByNameAsync("Админ") == null) { await roleManager.CreateAsync(new IdentityRole("Админ")); } // if if (await roleManager.FindByNameAsync("Пользователь") == null) { await roleManager.CreateAsync(new IdentityRole("Пользователь")); } // if if (await roleManager.FindByNameAsync("Модератор") == null) { await roleManager.CreateAsync(new IdentityRole("Модератор")); } // if if (await roleManager.FindByNameAsync("Менеджер") == null) { await roleManager.CreateAsync(new IdentityRole("Менеджер")); } // if if (await roleManager.FindByNameAsync("Мастер") == null) { await roleManager.CreateAsync(new IdentityRole("Мастер")); } // if if (await roleManager.FindByNameAsync("Клиент") == null) { await roleManager.CreateAsync(new IdentityRole("Клиент")); } // if // Регистрируем первого админа, если его нет if (await userManager.FindByNameAsync(adminEmail) == null) { var admin = new User { Email = adminEmail, UserName = adminEmail }; var result = await userManager.CreateAsync(admin, password); if (result.Succeeded) { await userManager.AddToRoleAsync(admin, "Админ"); } // if } // if // Первый пользователь if (await userManager.FindByNameAsync(userEmail) == null) { var user = new User { Email = userEmail, UserName = userEmail }; var result = await userManager.CreateAsync(user, password); if (result.Succeeded) { await userManager.AddToRoleAsync(user, "Пользователь"); } // if } // if // Клиент if (await userManager.FindByNameAsync(clientEmail) == null) { var client = new User { Email = clientEmail, UserName = clientEmail }; var result = await userManager.CreateAsync(client, password); if (result.Succeeded) { await userManager.AddToRoleAsync(client, "Клиент"); await userManager.AddToRoleAsync(client, "Пользователь"); } // if } // if // Мастер if (await userManager.FindByNameAsync(masEmail) == null) { var master = new User { Email = masEmail, UserName = masEmail }; var result = await userManager.CreateAsync(master, password); if (result.Succeeded) { await userManager.AddToRoleAsync(master, "Мастер"); await userManager.AddToRoleAsync(master, "Пользователь"); } // if } // if }
public async Task <AppUser> GetUserByUserNameAsync(string userName) { return(await _applicationUserManager.FindByNameAsync(userName)); }
public async Task <Unit> Handle(Command request, CancellationToken cancellationToken) { var user = await _userManager.FindByNameAsync(_userAccessor.GetCurrentUsername()); var play = await _dataContext.Plays.Where(x => x.Title == request.Title).SingleOrDefaultAsync(); if (play != null) { Console.WriteLine(play.Title); } if (user != null) { Console.WriteLine(user.UserName); } if (user == null) { Console.WriteLine("nu"); } if (user != null && play != null) { Reservation reservation = new Reservation { ReservationId = Guid.NewGuid(), SeatsReserved = request.Column.Count, AppUser = user, AppUserId = Guid.Parse(user.Id), Play = play, PlayId = play.PlayId }; _dataContext.Reservations.Add(reservation); for (var index = 0; index < request.Row.Count; index++) { var seat = await _dataContext.Seats.Where(x => (x.Row == request.Row[index] && x.Column == request.Column[index] && x.Auditorium.AuditoriumId == play.AuditoriumId)).SingleOrDefaultAsync(); Console.WriteLine(seat.SeatId); Seat newSeat = new Seat { SeatId = seat.SeatId, Reservation = reservation, ReservationId = reservation.ReservationId, Column = seat.Column, Row = seat.Row, AuditoriumId = seat.AuditoriumId, Auditorium = seat.Auditorium }; _dataContext.Remove(seat); _dataContext.Seats.Add(newSeat); } var success = await _dataContext.SaveChangesAsync() > 0; Console.WriteLine(success); if (success) { return(Unit.Value); } throw new Exception("Problem saving changes"); } return(Unit.Value); throw new Exception("user or play does not exist"); }
public async static Task ResetDatabase(ApplicationDbContext context, UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager) { Random random = new Random(); // Deletes all past users and roles from previous session //List<Task> Tasks = new List<Task>(); foreach (ApplicationUser user_to_be_deleted in context.Users) { await userManager.DeleteAsync(user_to_be_deleted); } foreach (IdentityRole role_to_be_deleted in roleManager.Roles.ToList()) { await roleManager.DeleteAsync(role_to_be_deleted); } //Task.WaitAll(Tasks.ToArray()); //Tasks.Clear(); // Create Roles foreach (string role in AuthorizationRoles.AllRoles) { await roleManager.CreateAsync(new IdentityRole(role)); } // Create a normal user ApplicationUser user = new ApplicationUser { UserName = "******", Name = "name", Email = "*****@*****.**", TwoFactorEnabled = true }; //Task.WaitAll(Tasks.ToArray()); //Tasks.Clear(); await userManager.CreateAsync(user, "asd"); await userManager.AddToRoleAsync(await userManager.FindByNameAsync(user.UserName), AuthorizationRoles.User); // Create a secure user ApplicationUser user2 = new ApplicationUser { UserName = "******" + random.Next(0, 99).ToString("00"), Name = "name" + random.Next(0, 99).ToString("00"), Email = "*****@*****.**", Answer1 = RandomString(5), Answer2 = RandomString(5), TwoFactorEnabled = true }; await userManager.CreateAsync(user2, RandomString(5)); await userManager.AddToRoleAsync(await userManager.FindByNameAsync(user2.UserName), AuthorizationRoles.User); // Create an admin user ApplicationUser admin = new ApplicationUser { UserName = "******", Name = "admin", Email = "*****@*****.**", Answer1 = "asd", Answer2 = "asd", TwoFactorEnabled = true }; await userManager.CreateAsync(admin, "asd"); await userManager.AddToRoleAsync(await userManager.FindByEmailAsync(admin.Email), AuthorizationRoles.Administrator); // Create a secure admin user ApplicationUser admin2 = new ApplicationUser { UserName = "******" + random.Next(0, 99).ToString("00"), Name = "admin" + random.Next(0, 99).ToString("00"), Email = "*****@*****.**", Answer1 = RandomString(5), Answer2 = RandomString(5), TwoFactorEnabled = true }; await userManager.CreateAsync(admin2, RandomString(5)); await userManager.AddToRoleAsync(await userManager.FindByNameAsync(admin2.UserName), AuthorizationRoles.Administrator); var users = userManager.Users.ToList(); }