public async Task Add_Should_Add_New_Login_Just_After_UserManager_CreateAsync_Get_Called()
        {
            const string userName = "******";
            const string loginProvider = "Twitter";
            const string providerKey = "12345678";

            using (IDocumentStore store = CreateEmbeddableStore())
            {
                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    RavenUserStore<RavenUser> userStore = new RavenUserStore<RavenUser>(ses);
                    UserManager<RavenUser> userManager = new UserManager<RavenUser>(userStore);

                    RavenUser user = new RavenUser(userName);
                    UserLoginInfo loginToAdd = new UserLoginInfo(loginProvider, providerKey);
                    await userManager.CreateAsync(user);
                    await userManager.AddLoginAsync(user.Id, loginToAdd);
                    await ses.SaveChangesAsync();
                }

                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    IUserLoginStore<RavenUser, string> userLoginStore = new RavenUserStore<RavenUser>(ses);
                    RavenUser user = await ses.LoadAsync<RavenUser>(RavenUser.GenerateKey(userName));
                    RavenUserLogin foundLogin = await ses.LoadAsync<RavenUserLogin>(RavenUserLogin.GenerateKey(loginProvider, providerKey));

                    // Assert
                    Assert.Equal(1, user.Logins.Count());
                    Assert.NotNull(foundLogin);
                }
            }
        }
Example #2
45
 public async Task AddDuplicateLoginFailsTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var mgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("dupeLogintest");
     UnitTestHelper.IsSuccess(await mgr.CreateAsync(user));
     var userLogin1 = new UserLoginInfo("provider1", "p1-1");
     UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1));
     UnitTestHelper.IsFailure(await mgr.AddLoginAsync(user.Id, userLogin1));
 }
        // GET: Home
        public async Task<ActionResult> Index()
        {
            var context = new ApplicationDbContext(); // DefaultConnection
            var store = new UserStore<CustomUser>(context);
            var manager = new UserManager<CustomUser>(store);

            var email = "*****@*****.**";
            var password = "******";
            var user = await manager.FindByEmailAsync(email);

            if (user == null)
            {
                user = new CustomUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = "Super",
                    LastName = "Admin"
                };

                await manager.CreateAsync(user, password);
            }
            else
            {
                user.FirstName = "Super";
                user.LastName = "Admin";

                await manager.UpdateAsync(user);
            }


            return Content("Hello, Index");
        }
        // GET: Home
        public async Task<ActionResult> Index()
        {
            var context = new ApplicationDbContext(); // DefaultConnection
            var store = new UserStore<CustomUser>(context);
            var manager = new UserManager<CustomUser>(store);
            var signInManager = new SignInManager<CustomUser, string>(manager,
                HttpContext.GetOwinContext().Authentication);

            var email = "*****@*****.**";
            var password = "******";
            var user = await manager.FindByEmailAsync(email);

            if (user == null)
            {
                user = new CustomUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = "Super",
                    LastName = "Admin"
                };

                await manager.CreateAsync(user, password);
            }
            else
            {
                var result = await signInManager.PasswordSignInAsync(user.UserName, password, true, false);

                if (result == SignInStatus.Success)
                {
                    return Content("Hello, " + user.FirstName + " " + user.LastName);
                }
                //user.FirstName = "Super";
                //user.LastName = "Admin";

                //await manager.UpdateAsync(user);
            }


            return Content("Hello, Index");
        }
Example #5
1
        public async Task SetupAsync()
        {
            _evnt = new EventViewModel
            {
                Title = "Title event",
                Description = "Test event",
                Start = "11:00",
                End = "14:27",
                Date = "2016-02-01"
            };

            var userViewModel = new LoginViewModel
            {
                Email = "*****@*****.**",
                Password = "******",
                RememberMe = false
            };
            var context = new DataContext();
            var manager = new UserManager(new UserStore(context));
            var user = await manager.FindAsync(userViewModel.Email, userViewModel.Password);
            if (user == null)
            {
                await manager.CreateAsync(new User { Email = userViewModel.Email, UserName = userViewModel.Email }, userViewModel.Password);
            }
            _calendarController = new CalendarController(context);

            var mockCp = new Mock<IClaimsPrincipal>();
            if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
            _calendarController.CurrentUser = mockCp.Object;

            var mockAuthenticationManager = new Mock<IAuthenticationManager>();
            mockAuthenticationManager.Setup(am => am.SignOut());
            mockAuthenticationManager.Setup(am => am.SignIn());
            _calendarController.AuthenticationManager = mockAuthenticationManager.Object;
        }
        public async Task<ActionResult> Create(DoctorViewModel DoctorViewModel)
        {
            if (ModelState.IsValid)
            {
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
                var user = new ApplicationUser() { UserName = DoctorViewModel.Email };
                var result = await UserManager.CreateAsync(user, DoctorViewModel.Password);
                string roleName = "Doctor";
                IdentityResult roleResult;
                if (!RoleManager.RoleExists(roleName))
                {
                    roleResult = RoleManager.Create(new IdentityRole(roleName));
                }
                try
                {
                    var findUser = UserManager.FindByName(DoctorViewModel.Email);
                    UserManager.AddToRole(findUser.Id, "Doctor");
                    context.SaveChanges();
                }
                catch
                {
                    throw;
                }
                Doctor_Detail doctor = MapDoctor(DoctorViewModel);
                db.Doctor_Details.Add(doctor);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(DoctorViewModel);
        }
        public async Task<ActionResult> Default(RegisterViewModel model)
        {
            var context = new MyDbContext();
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            
            // The default Validators that the UserManager uses are UserValidator and MinimumLengthValidator
            // You can tweak some of the settings as follows
            // This example sets the Password length to be 3 characters
            UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
            {
                AllowOnlyAlphanumericUserNames = false
            };
             UserManager.PasswordValidator = new MinimumLengthValidator(3);


            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                user.HomeTown = model.HomeTown;
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var authManager = HttpContext.GetOwinContext().Authentication;
                    var claimsIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authManager.SignIn(claimsIdentity);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Example #8
0
		public static async void ConfigureUsers(IEnumerable<InMemoryUser> users, EntityFrameworkServiceOptions options, UserManager userManager) {
			using(var db = new Contexto(options.ConnectionString)) {
				
				if(!db.Users.Any()) {
					
					foreach(var u in users) {
						var entity = new Usuario { Email = u.Claims.First(x=>x.Type==Constants.ClaimTypes.Email).Value , UserName = u.Username };
						var response = await userManager.CreateAsync(entity, u.Password);
						
						if(!response.Succeeded) {
							throw new Exception("Não foi possível criar o usuario" + u.Username + response.Errors.ToString());
						}
						else {
							
							var user = await userManager.FindAsync(u.Username,u.Password);
							foreach(var c in u.Claims) {

								await userManager.AddClaimAsync(user.Id,c);
							}
														
							await userManager.UpdateAsync(user);
						}
					}
					db.SaveChanges();
				}
			}
		}
Example #9
0
 public async Task GetUserClaimTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("u1");
     var result = await manager.CreateAsync(user);
     UnitTestHelper.IsSuccess(result);
     Assert.NotNull(user);
     var claims = new[]
     {
         new Claim("c1", "v1"),
         new Claim("c2", "v2"),
         new Claim("c3", "v3")
     };
     foreach (Claim c in claims)
     {
         UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
     }
     var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id));
     Assert.Equal(3, userClaims.Count);
     foreach (Claim c in claims)
     {
         Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
     }
 }
Example #10
0
 protected void btnRegistrar_Click(object sender, EventArgs e)
 {
     var manager = new UserManager();
     var user = new ApplicationUser();
     user.UserName = txtUserName.Text;
     user.Direccion = txtDireccion.Text;
     manager.CreateAsync(user);
 }
Example #11
0
 public async Task AddLoginNullLoginFailsTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("Hao");
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => manager.AddLoginAsync(user.Id, null)),
         "login");
 }
            public static async Task<IdentityResult> CreateUser(PlatformUser user, string password)
            {

                var userManager = new UserManager<PlatformUser>(
                    new UserStore<PlatformUser>(new PlatformUserIdentityDbContext()));

                //Allows for use of email address as username:
                userManager.UserValidator = new UserValidator<PlatformUser>(userManager) { AllowOnlyAlphanumericUserNames = false };


                var idResult = await userManager.CreateAsync(user, password);

                return idResult;

            }
		/// <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 void WhenCeateUserAsync()
        {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_session));
            var user = new ApplicationUser() { UserName = "******" };

            using (var transaction = new TransactionScope())
            {
                var result = userManager.CreateAsync(user, "RealPassword");
                transaction.Complete();
                Assert.IsNull(result.Exception);
            }

            var actual = _session.Query<ApplicationUser>().FirstOrDefault(x => x.UserName == user.UserName);

            Assert.IsNotNull(actual);
            Assert.AreEqual(user.UserName, actual.UserName);
        }
 private static async System.Threading.Tasks.Task CreateUserIfNotExist(UserManager<ApplicationUser> userManager, string email, string password, string role, string loginProvider = null, string providerKey = null)
 {
     var user = await userManager.FindByEmailAsync(email);
     if (user == null)
     {
         user = new ApplicationUser { UserName = email, Email = email };
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
 }
        private static void AddAppointments(SMDbContext context, UserManager<ApplicationUser> userManager)
        {
            var esth = context.Estheticians.Single(x => x.Id == 1);
            var services = context.SpaServices.Take(3).ToList();
            var clientUser = new ApplicationUser
            {
                UserName = "******",
                Email = "*****@*****.**",
                FirstName = "Claire",
                LastName = "Smith",
                PhoneNumber = "5625551212"
            };

            Task.FromResult(userManager.CreateAsync(clientUser, "client11").Result);

            var client = new Client
            {
                ApplicationUserId = userManager.FindByEmailAsync("*****@*****.**").Result.Id,
                AppointmentRemindersViaText = true,
                Appointments = new List<Appointment>()
            };
            context.Clients.Add(client);
            context.SaveChanges();

            var appt = new Appointment
            {
                ClientId = client.Id,
                FirstName = clientUser.FirstName,
                LastName = clientUser.LastName,
                Email = clientUser.Email,
                PhoneNumber = clientUser.PhoneNumber,
                Services = services,
                Esthetician = esth,
                StartTime = DateTime.Parse("10/21/2016 17:15"),
                LocationId = 1,
                EndTime = DateTime.Parse("10/21/2016 18:30"),
                RemindViaEmail = client.AppointmentRemindersViaEmail,
                RemindViaText = client.AppointmentRemindersViaText,
                Gender = Gender.Male
            };

            context.Appointments.Add(appt);
            context.SaveChanges();
        }
        public async Task<ActionResult> Create(PatientViewModel PatientViewModel)
        {
            
            if (ModelState.IsValid)
            {
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
                var user = new ApplicationUser() { UserName = PatientViewModel.Email };
                var result = await UserManager.CreateAsync(user, PatientViewModel.Password);
                string roleName = "Patient";
                IdentityResult roleResult;
                if (!RoleManager.RoleExists(roleName))
                {
                    roleResult = RoleManager.Create(new IdentityRole(roleName));
                }
                try
                {
                    var findUser = UserManager.FindByName(PatientViewModel.Email);
                    UserManager.AddToRole(findUser.Id, "Patient");
                    context.SaveChanges();
                }
                catch
                {
                    throw;
                }

                var patient = new Patient_Detail();
                patient.address = PatientViewModel.address;
                patient.cellno = PatientViewModel.cellno;
                patient.first_name = PatientViewModel.first_name;
                patient.med_aid_dep_no = PatientViewModel.med_aid_dep_no;
                patient.med_aid_no = PatientViewModel.med_aid_no;
                patient.post_code = PatientViewModel.post_code;
                patient.surname = PatientViewModel.surname;
                patient.telno = PatientViewModel.telno;

                db.Patient_Details.Add(patient);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(PatientViewModel);
        }
        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;
        }
Example #19
0
        private async void Seed()
        {
            const string roleName = "administrator";
            const string userName = "******";
            var userContext = new ApplicationDbContext();
            var roleStore = new RoleStore<IdentityRole>(userContext);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            if (roleManager.RoleExists(roleName)) return;
            await roleManager.CreateAsync(new IdentityRole(roleName));
            var userStore = new UserStore<ApplicationUser>(userContext);
            var userManager = new UserManager<ApplicationUser>(userStore);
            var admin = new ApplicationUser() {UserName = userName};
            await userManager.CreateAsync(admin, "Koekoek!IsNummer1");
            await userManager.AddToRoleAsync(admin.Id, roleName);

            var pandContext = new ExclimmoContext();
            pandContext.SeedPanden();

        }
Example #20
0
 private static async Task<ApplicationUser> CreateUserIfNotExist(UserManager<ApplicationUser> userManager, ApplicationUser user, string password, string role, string loginProvider = null, string providerKey = null)
 {
     //Debugger.Launch();
     user.EmailConfirmed = true;
     user.Email = user.Email ?? user.UserName;
     if (await userManager.FindByEmailAsync(user.Email) == null)
     {
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
     return user;
 }
        public async Task ClaimsIdentityTest()
        {
            var db = UnitTestHelper.CreateDefaultDb();
            var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
            var role = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
            var user = new IdentityUser("Hao");
            UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
            UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Admin")));
            UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Local")));
            UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Admin"));
            UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Local"));
            Claim[] userClaims =
            {
                new Claim("Whatever", "Value"),
                new Claim("Whatever2", "Value2")
            };
            foreach (var c in userClaims)
            {
                UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
            }

            var identity = await manager.CreateIdentityAsync(user, "test");
            var claimsFactory = manager.ClaimsIdentityFactory as ClaimsIdentityFactory<IdentityUser, string>;
            Assert.NotNull(claimsFactory);
            var claims = identity.Claims;
            Assert.NotNull(claims);
            Assert.True(
                claims.Any(c => c.Type == claimsFactory.UserNameClaimType && c.Value == user.UserName));
            Assert.True(claims.Any(c => c.Type == claimsFactory.UserIdClaimType && c.Value == user.Id));
            Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Admin"));
            Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Local"));
            Assert.True(
                claims.Any(
                    c =>
                        c.Type == ClaimsIdentityFactory<IdentityUser>.IdentityProviderClaimType &&
                        c.Value == ClaimsIdentityFactory<IdentityUser>.DefaultIdentityProviderClaimValue));
            foreach (var cl in userClaims)
            {
                Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
            }
        }
        public async Task<ActionResult> Create(NurseViewModel NurseViewModel)
        {
            if (ModelState.IsValid)
            {
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
                var user = new ApplicationUser() { UserName = NurseViewModel.Email };
                var result = await UserManager.CreateAsync(user, NurseViewModel.Password);
                string roleName = "Nurse";
                IdentityResult roleResult;
                if (!RoleManager.RoleExists(roleName))
                {
                    roleResult = RoleManager.Create(new IdentityRole(roleName));
                }
                try
                {
                    var findUser = UserManager.FindByName(NurseViewModel.Email);
                    UserManager.AddToRole(findUser.Id, "Nurse");
                    context.SaveChanges();
                }
                catch
                {
                    throw;
                }
                var nurse = new Nurse_Detail();
                nurse.address = NurseViewModel.address;
                nurse.cellno = NurseViewModel.cellno;
                nurse.first_name = NurseViewModel.first_name;
                nurse.med_practice_no = NurseViewModel.med_practice_no;
                nurse.post_code = NurseViewModel.post_code;
                nurse.surname = NurseViewModel.surname;
                nurse.telno = NurseViewModel.telno;
                db.Nurse_Details.Add(nurse);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(NurseViewModel);
        }
Example #23
0
 public async Task LinkUnlinkDeletesTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var mgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("linkunlinktest");
     UnitTestHelper.IsSuccess(await mgr.CreateAsync(user));
     var userLogin1 = new UserLoginInfo("provider1", "p1-1");
     var userLogin2 = new UserLoginInfo("provider2", "p2-1");
     Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count);
     UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1));
     Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p1-1"));
     Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count);
     UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin2));
     Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1"));
     Assert.Equal(2, (await mgr.GetLoginsAsync(user.Id)).Count);
     UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin1));
     Assert.Equal(0, user.Logins.Count(l => l.ProviderKey == "p1-1"));
     Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1"));
     Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count());
     UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin2));
     Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count);
     Assert.Equal(0, db.Set<IdentityUserLogin>().Count());
 }
        // GET: Home
        public async Task<ActionResult> Index()
        {
            var context = new IdentityDbContext<IdentityUser>(); // DefaultConnection
            var store = new UserStore<IdentityUser>(context);
            var manager = new UserManager<IdentityUser>(store);

            var email = "*****@*****.**";
            var password = "******";
            var user = await manager.FindByEmailAsync(email);

            if (user == null)
            {
                user = new IdentityUser
                {
                    UserName = email,
                    Email = email
                };

                await manager.CreateAsync(user, password);
            }


            return Content("Hello, Index");
        }
Example #25
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                IdentityRole irs = await _roleManager.FindByNameAsync("supplier");

                IdentityRole supplierRole = new IdentityRole("supplier");
                IdentityRole irw          = await _roleManager.FindByNameAsync("wholesaler");

                IdentityRole wholesalerRole = new IdentityRole("wholesaler");

                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (model.Role == "Supplier")
                {
                    if (irs == null)
                    {
                        await _roleManager.CreateAsync(supplierRole);
                    }
                    createSupplier(model.Location, model.CompanyName, model.Email, model.Phone, model.Name);
                    await _userManager.AddToRoleAsync(user, "supplier");
                }
                else if (model.Role == "Wholesaler")
                {
                    if (irw == null)
                    {
                        await _roleManager.CreateAsync(wholesalerRole);
                    }
                    createWholesaler(model.Location, model.Name, model.Email, model.Phone);
                    await _userManager.AddToRoleAsync(user, "wholesaler");
                }
                else if (model.Role == "Both")
                {
                    createSupplier(model.Location, model.CompanyName, model.Email, model.Phone, model.Name);
                    createWholesaler(model.Location, model.Name, model.Email, model.Phone);
                    await _userManager.AddToRoleAsync(user, "wholesaler");

                    await _userManager.AddToRoleAsync(user, "supplier");
                }


                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    //await _userManager.AddToRoleAsync(user, "admin");
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation(3, "User created a new account with password.");

                    if (model.Role == "Supplier" || model.Role == "Both")
                    {
                        return(RedirectToAction("authen", new { returnUrl = "/Supplier/SupplierEdit" }));
                    }
                    //return RedirectToAction("Index", "Supplier");
                    else
                    {
                        return(RedirectToAction("authen", new { returnUrl = "/Wholesaler/Account" }));
                    }
                    //return RedirectToAction("Index", "Wholesaler");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #26
0
        public async Task <IActionResult> Register(IFormFile uploadFile, RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                if (uploadFile != null)
                {
                    if (Path.GetExtension(uploadFile.FileName) == ".jpg" ||
                        Path.GetExtension(uploadFile.FileName) == ".gif" ||
                        Path.GetExtension(uploadFile.FileName) == ".png")
                    {
                        string category    = DateTime.Now.Month + "-" + DateTime.Now.Year + "-CampaignImages";
                        string FilePath    = env.WebRootPath + "\\uploads\\" + category + "\\";
                        string dosyaismi   = Path.GetFileName(uploadFile.FileName);
                        var    yuklemeYeri = Path.Combine(FilePath, dosyaismi);
                        model.Logo = "uploads/" + category + "/" + dosyaismi;
                        try
                        {
                            if (!Directory.Exists(FilePath))
                            {
                                Directory.CreateDirectory(FilePath);//Eðer klasör yoksa oluþtur
                            }
                            using (var stream = new FileStream(yuklemeYeri, FileMode.Create))
                            {
                                await uploadFile.CopyToAsync(stream);
                            }

                            _context.Add(model);
                            await _context.SaveChangesAsync();

                            return(RedirectToAction("Index"));
                        }
                        catch (Exception exc) { ModelState.AddModelError("Image", "Hata: " + exc.Message); }
                    }
                    else
                    {
                        ModelState.AddModelError("Image", "Dosya uzantısı izin verilen uzantılardan olmalıdır.");
                    }
                }

                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };


                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation(3, "Kullanıcı yeni bir hesap oluşturdu.");
                    var lastUser   = _context.Users.OrderByDescending(x => x.CreateDate).FirstOrDefault();
                    var newCompany = new Company {
                        Name = model.Name, Address = model.Address, Phone = model.Phone, Logo = model.Logo, CreateDate = DateTime.Now, UpdateDate = DateTime.Now, UserId = lastUser.Id
                    };
                    _context.Add(newCompany);
                    _context.SaveChanges();



                    MailSetting mailSetting2;
                    SendMessage sendMessage2;
                    mailSetting2 = _context.MailSettings.Where(a => a.Id == 1).FirstOrDefault();
                    sendMessage2 = _context.SendMessages.Where(x => x.Id == 2).FirstOrDefault();
                    string FromAddress      = mailSetting2.FromAddress;
                    string FromAddressTitle = mailSetting2.FromAddressTitle;

                    string ToAddress      = model.Email;
                    string ToAddressTitle = model.Name;
                    string Subject        = sendMessage2.Subject;
                    string BodyContent    = sendMessage2.BodyContent;

                    string SmptServer     = mailSetting2.SmptServer;
                    int    SmptPortNumber = mailSetting2.SmptPortNumber;

                    var mimeMessage = new MimeMessage();
                    mimeMessage.From.Add(new MailboxAddress(FromAddressTitle, FromAddress));
                    mimeMessage.To.Add(new MailboxAddress(ToAddressTitle, ToAddress));
                    mimeMessage.Subject = Subject;
                    mimeMessage.Body    = new TextPart("plain")
                    {
                        Text = BodyContent
                    };

                    using (var client = new SmtpClient())
                    {
                        client.Connect(SmptServer, SmptPortNumber, false);
                        client.Authenticate(mailSetting2.FromAddress, mailSetting2.FromAddressPassword);
                        client.Send(mimeMessage);
                        client.Disconnect(true);
                    }



                    return(RedirectToLocal(returnUrl));
                }



                AddErrors(result);
            }



            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #27
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            UserProfile user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                             externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);

                // FIX
                var info = await Authentication.GetExternalLoginInfoAsync();

                var username = info.Email ?? (info.DefaultUserName + "@vk.com");

                user = new UserProfile {
                    Email = username, UserName = info.DefaultUserName
                };
                var result = await UserManager.CreateAsync(user);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                result = await UserManager.AddLoginAsync(user.Id, info.Login);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
            }

            return(Ok());
        }
Example #28
0
        private async Task <ApplicationUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable <Claim> claims)
        {
            // create a list of claims that we want to transfer into our store
            var filtered = new List <Claim>();

            // user's display name
            var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
                       claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;

            if (name != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Name, name));
            }
            else
            {
                var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
                            claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
                var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
                           claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
                if (first != null && last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
                }
                else if (first != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first));
                }
                else if (last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, last));
                }
            }

            // email
            var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
                        claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;

            if (email != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Email, email));
            }

            var user = new ApplicationUser
            {
                UserName = Guid.NewGuid().ToString(),
            };
            var identityResult = await _userManager.CreateAsync(user);

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            if (filtered.Any())
            {
                identityResult = await _userManager.AddClaimsAsync(user, filtered);

                if (!identityResult.Succeeded)
                {
                    throw new Exception(identityResult.Errors.First().Description);
                }
            }

            identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            return(user);
        }
Example #29
0
        public static async Task AddAdmin(IServiceProvider serviceProvider)
        {
            AppDbContext               _db          = serviceProvider.GetRequiredService <AppDbContext>();
            UserManager <AppUser>      _userManager = serviceProvider.GetRequiredService <UserManager <AppUser> >();
            RoleManager <IdentityRole> _roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();

            //TODO: Add the needed roles
            //if role doesn't exist, add it
            if (await _roleManager.RoleExistsAsync("Manager") == false)
            {
                await _roleManager.CreateAsync(new IdentityRole("Manager"));
            }

            if (await _roleManager.RoleExistsAsync("Customer") == false)
            {
                await _roleManager.CreateAsync(new IdentityRole("Customer"));
            }

            if (await _roleManager.RoleExistsAsync("Employee") == false)
            {
                await _roleManager.CreateAsync(new IdentityRole("Employee"));
            }


            //check to see if the manager has been added
            AppUser manager = _db.Users.FirstOrDefault(u => u.Email == "*****@*****.**");

            //if manager hasn't been created, then add them
            if (manager == null)
            {
                manager             = new AppUser();
                manager.UserName    = "******";
                manager.Email       = "*****@*****.**";
                manager.PhoneNumber = "(512)555-5555";
                manager.FirstName   = "Admin";


                //TODO: Add any other fields for your app user class here
                manager.LastName = "Example";
                manager.Address  = "123 Bevo Ln.";
                manager.City     = "Austin";
                manager.State    = "TX";
                manager.Zip      = "78705";
                //manager.DateAdded = DateTime.Today;

                //NOTE: Ask the user manager to create the new user
                //The second parameter for .CreateAsync is the user's password
                var result = await _userManager.CreateAsync(manager, "Abc123!");

                if (result.Succeeded == false)
                {
                    throw new Exception("This user can't be added - " + result.ToString());
                }
                _db.SaveChanges();
                manager = _db.Users.FirstOrDefault(u => u.UserName == "*****@*****.**");
            }

            //make sure user is in role
            if (await _userManager.IsInRoleAsync(manager, "Manager") == false)
            {
                await _userManager.AddToRoleAsync(manager, "Manager");
            }

            //save changes
            _db.SaveChanges();
        }
Example #30
0
        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.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var roleCheck = false;

                    switch (Input.Email)
                    {
                    case "*****@*****.**":
                        roleCheck = await _roleManager.RoleExistsAsync("Laboratory");

                        if (!roleCheck)
                        {
                            await _roleManager.CreateAsync(new IdentityRole("Laboratory"));
                        }

                        await _userManager.AddToRoleAsync(user, "Laboratory");

                        break;

                    case "*****@*****.**":
                        roleCheck = await _roleManager.RoleExistsAsync("CEO");

                        if (!roleCheck)
                        {
                            await _roleManager.CreateAsync(new IdentityRole("CEO"));
                        }

                        await _userManager.AddToRoleAsync(user, "CEO");

                        break;

                    default:
                        roleCheck = await _roleManager.RoleExistsAsync("Taster");

                        if (!roleCheck)
                        {
                            await _roleManager.CreateAsync(new IdentityRole("Taster"));
                        }

                        await _userManager.AddToRoleAsync(user, "Taster");

                        if (await _userManager.IsInRoleAsync(user, "Taster"))
                        {
                            var taster = new Taster {
                                TasterEmail = Input.Email, TasterName = Input.FirstName, TasterSecondName = Input.SecondName
                            };
                            _context.Add(taster);
                            await _context.SaveChangesAsync();
                        }
                        break;
                    }

                    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 },
                        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 }));
                    }
                    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());
        }
Example #31
0
        public async Task <IdentityResult> Create(User user, string password)
        {
            var result = await _userManager.CreateAsync(user, password);

            return(result);
        }
        public async Task <IdentityResult> RegisterAccount(RegisterViewModel model)
        {
            var user = new ApplicationUser
            {
                UserName       = model.Email,
                Email          = model.Email,
                FirstName      = model.FirstName,
                LastName       = model.LastName,
                RegisterDate   = DateTime.Now,
                RegisterIP     = System.Web.HttpContext.Current.Request.GetVisitorIP(),
                LastAccessDate = DateTime.Now,
                LastAccessIP   = System.Web.HttpContext.Current.Request.GetVisitorIP()
            };

            var result = await UserManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                // Send Message
                var roleAdministrator = await RoleManager.FindByNameAsync(BeYourMarket.Model.Enum.Enum_UserRole.Administrator.ToString());

                var administrator = roleAdministrator.Users.FirstOrDefault();

                var message = new MessageSendModel()
                {
                    UserFrom = administrator.UserId,
                    UserTo   = user.Id,
                    Subject  = HttpContext.ParseAndTranslate(string.Format("[[[Welcome to {0}!]]]", CacheHelper.Settings.Name)),
                    Body     = HttpContext.ParseAndTranslate(string.Format("[[[Hi, Welcome to {0}! I am happy to assist you if you has any questions.]]]", CacheHelper.Settings.Name))
                };

                await MessageHelper.SendMessage(message);

                // Send an email with this link
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var urlHelper   = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
                var callbackUrl = urlHelper.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: System.Web.HttpContext.Current.Request.Url.Scheme);

                var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "signup").SelectAsync();

                var emailTemplate = emailTemplateQuery.FirstOrDefault();

                if (emailTemplate != null)
                {
                    dynamic email = new Postal.Email("Email");
                    email.To          = user.Email;
                    email.From        = CacheHelper.Settings.EmailAddress;
                    email.Subject     = emailTemplate.Subject;
                    email.Body        = emailTemplate.Body;
                    email.CallbackUrl = callbackUrl;
                    EmailHelper.SendEmail(email);
                }
            }

            return(result);
        }
Example #33
0
        public async Task <IActionResult> Create(RegisterViewModel registerViewModel)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Login", "Account"));
            }

            if (!User.IsInRole("Admin"))
            {
                return(RedirectToAction("Login", "Account"));
            }
            if (!ModelState.IsValid)
            {
                ViewBag.Active = "Home";

                return(View(registerViewModel));
            }

            AppUser newUser;

            if (registerViewModel.Photo != null)
            {
                if (!registerViewModel.Photo.IsImage())
                {
                    ViewBag.Active = "Home";

                    ModelState.AddModelError("Photo", "File type should be image");
                    return(View(registerViewModel));
                }

                string filename = await registerViewModel.Photo.SaveAsync(_env.WebRootPath);

                registerViewModel.PhotoURL = filename;

                newUser = new AppUser
                {
                    Firstname   = registerViewModel.Firstname.Trim(),
                    Lastname    = registerViewModel.Lastname.Trim(),
                    Email       = registerViewModel.Email.Trim(),
                    UserName    = registerViewModel.Username.Trim(),
                    PhoneNumber = registerViewModel.Phone.Trim(),
                    PhotoURL    = registerViewModel.PhotoURL
                };
            }
            else
            {
                newUser = new AppUser
                {
                    Firstname   = registerViewModel.Firstname.Trim(),
                    Lastname    = registerViewModel.Lastname.Trim(),
                    Email       = registerViewModel.Email.Trim(),
                    UserName    = registerViewModel.Username.Trim(),
                    PhoneNumber = registerViewModel.Phone.Trim(),
                    PhotoURL    = "Person-icon.png"
                };
            }



            IdentityResult identityResult = await _usermanager.CreateAsync(newUser, registerViewModel.Password);

            if (!identityResult.Succeeded)
            {
                foreach (var error in identityResult.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
                ViewBag.Active = "Home";

                return(View(registerViewModel));
            }

            //add default member role to user

            await _usermanager.AddToRoleAsync(newUser, StaticUsers.Member);

            ViewBag.Active = "Home";


            return(RedirectToAction("Index"));
        }
Example #34
0
 public async Task <IdentityResult> AddUserAsync(User user, string password)
 {
     return(await _userManager.CreateAsync(user, password));
 }
Example #35
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName      = Input.Email,
                    Email         = Input.Email,
                    CompanyId     = Input.CompanyId,
                    StreetAddress = Input.StreetAddress,
                    City          = Input.City,
                    State         = Input.State,
                    PostalCode    = Input.PostalCode,
                    Name          = Input.Name,
                    PhoneNumber   = Input.PhoneNumber,
                    Role          = Input.Role
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    if (user.Role == null)
                    {
                        await _userManager.AddToRoleAsync(user, SD.Role_User_Indi);
                    }
                    else
                    {
                        if (user.CompanyId > 0)
                        {
                            await _userManager.AddToRoleAsync(user, SD.Role_User_Comp);
                        }
                        await _userManager.AddToRoleAsync(user, user.Role);
                    }

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        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 }));
                    }
                    else
                    {
                        if (user.Role == null)
                        {
                            await _signInManager.SignInAsync(user, isPersistent : false);

                            return(LocalRedirect(returnUrl));
                        }
                        else
                        {
                            //admin is registering a new user
                            return(RedirectToAction("Index", "User", new { Area = "Admin" }));
                        }
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            Input = new InputModel()
            {
                CompanyList = _unitOfWork.Company.GetAll().Select(i => new SelectListItem
                {
                    Text  = i.Name,
                    Value = i.Id.ToString()
                }),
                RoleList = _roleManager.Roles.Where(u => u.Name != SD.Role_User_Indi).Select(x => x.Name).Select(i => new SelectListItem
                {
                    Text  = i,
                    Value = i
                })
            };

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Example #36
0
        public async Task <OperationResult> Register(string userName, string email, string password, Profile profile, string role)
        {
            if (await UserManager.FindByEmailAsync(email) != null)
            {
                return new OperationResult()
                       {
                           Success = false, Message = $"User {email} already exists"
                       }
            }
            ;
            if (await UserManager.FindByNameAsync(userName) != null)
            {
                return new OperationResult()
                       {
                           Success = false, Message = $"User {userName} already exists"
                       }
            }
            ;
            using var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions, TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                var createPersonOperation = await _pbo.CreateAsync(profile);

                if (!createPersonOperation.Success)
                {
                    transactionScope.Dispose();
                    return(createPersonOperation);
                }
                var user = new User()
                {
                    Email     = email,
                    UserName  = userName,
                    ProfileId = profile.Id
                };
                var result = await UserManager.CreateAsync(user, password);

                if (!result.Succeeded)
                {
                    transactionScope.Dispose();
                    return(new OperationResult()
                    {
                        Success = false, Message = result.ToString()
                    });
                }
                var roleData = await RoleManager.FindByNameAsync(role);

                if (roleData == null)
                {
                    transactionScope.Dispose();
                    return(new OperationResult()
                    {
                        Success = false, Message = $"Role {role} does not exist"
                    });
                }
                var roleOpt = await UserManager.AddToRoleAsync(user, role);

                if (!roleOpt.Succeeded)
                {
                    transactionScope.Dispose();
                    return(new OperationResult()
                    {
                        Success = false, Message = roleOpt.ToString()
                    });
                }
                transactionScope.Complete();
                return(new OperationResult()
                {
                    Success = true
                });
            }
            catch (Exception e)
            {
                return(new OperationResult()
                {
                    Success = false, Exception = e
                });
            }
        }
Example #37
0
        //AdminUser - manages user roles, can access admin dashboard, can delete profiles
        public static async Task CreateRoles(IServiceProvider serviceProvider, IConfiguration configuration)
        {
            UserManager <ApplicationUser> userManager =
                serviceProvider.GetRequiredService <UserManager <ApplicationUser> >();
            RoleManager <IdentityRole> roleManager =
                serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();

            string adminUsername = configuration["Data:AdminUser:Name"];
            string adminEmail    = configuration["Data:AdminUser:Email"];
            string adminPassword = configuration["Data:AdminUser:Password"];
            string adminRole     = configuration["Data:AdminUser:Role"];

            if (await userManager.FindByNameAsync(adminUsername) == null)
            {
                if (await roleManager.FindByNameAsync(adminRole) == null)
                {
                    await roleManager.CreateAsync(new IdentityRole(adminRole));
                }

                ApplicationUser user = new ApplicationUser
                {
                    UserName = adminUsername,
                    Email    = adminEmail
                };

                IdentityResult result1 = await userManager.CreateAsync(user, adminPassword);

                if (result1.Succeeded)
                {
                    await userManager.AddToRoleAsync(user, adminRole);
                }
            }

            string newUsername = configuration["Data:NewUser:Name"];
            string newEmail    = configuration["Data:NewUser:Email"];
            string newPassword = configuration["Data:NewUser:Password"];
            string newRole     = configuration["Data:NewUser:Role"];

            if (await userManager.FindByNameAsync(newUsername) == null)
            {
                if (await roleManager.FindByNameAsync(newRole) == null)
                {
                    await roleManager.CreateAsync(new IdentityRole(newRole));
                }

                ApplicationUser user = new ApplicationUser
                {
                    UserName = newUsername,
                    Email    = newEmail
                };

                IdentityResult result2 = await userManager.CreateAsync(user, newPassword);

                if (result2.Succeeded)
                {
                    await userManager.AddToRoleAsync(user, newRole);
                }
            }

            string approvedUsername = configuration["Data:ApprovedUser:Name"];
            string approvedEmail    = configuration["Data:ApprovedUser:Email"];
            string approvedPassword = configuration["Data:ApprovedUser:Password"];
            string approvedRole     = configuration["Data:ApprovedUser:Role"];

            if (await userManager.FindByNameAsync(approvedUsername) == null)
            {
                if (await roleManager.FindByNameAsync(approvedRole) == null)
                {
                    await roleManager.CreateAsync(new IdentityRole(approvedRole));
                }

                ApplicationUser user = new ApplicationUser
                {
                    UserName = approvedUsername,
                    Email    = approvedEmail
                };

                IdentityResult result3 = await userManager.CreateAsync(user, approvedPassword);

                if (result3.Succeeded)
                {
                    await userManager.AddToRoleAsync(user, approvedRole);
                }
            }
        }
Example #38
0
        public async Task <IActionResult> Register(string Username, string Email, string Password, string Token, string FirstName, string LastName, string FBToken)
        {
            Users user = null;

            if (!string.IsNullOrEmpty(FBToken))
            {
                user = _context.Users.Where(x => x.FBToken == FBToken).FirstOrDefault();
                if (user == null)
                {
                    user = _context.Users.Where(x => x.Email == Email).FirstOrDefault();
                }
            }
            if (user == null)
            {
                user = new Users {
                    UserName = Username, Email = Email, CreationDate = DateTime.Now, FirstName = FirstName, LastName = LastName, UserType = UserType.Planner, FBToken = FBToken
                };
                var result = await _userManager.CreateAsync(user, Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "Planner");


                    await _signInManager.SignInAsync(user, isPersistent : false);

                    var token = _context.UserPushToken.Where(x => x.Token == Token).FirstOrDefault();
                    if (token != null)
                    {
                        token.User = user;
                    }
                    _context.SaveChanges();
                    string   Address      = !string.IsNullOrEmpty(user.Address) ? user.Address : "";
                    string   Age          = !string.IsNullOrEmpty(user.Age) ? user.Age : "";
                    string   City         = !string.IsNullOrEmpty(user.City) ? user.City : "";
                    string   Country      = !string.IsNullOrEmpty(user.Country) ? user.Country : "";
                    DateTime CreationDate = user.CreationDate;
                    Gender   VGender      = user.Gender;
                    string   Id           = user.Id;
                    string   Image        = user.Image;
                    string   PhoneNumber  = !string.IsNullOrEmpty(user.PhoneNumber) ? user.PhoneNumber : "";
                    UserType UserType     = user.UserType;
                    var      events       = _context.Events.Where(x => x.UserId == user.Id).FirstOrDefault();
                    if (events != null)
                    {
                        if (!string.IsNullOrEmpty(events.Image))
                        {
                            events.Image = "http://" + Request.Host + "/Media/" + events.Image;
                        }
                    }
                    else
                    {
                        events = new Events {
                        }
                    };
                    ApiUsersViewModel api = new ApiUsersViewModel {
                        Address = Address, Age = Age, City = City, Country = Country, CreationDate = CreationDate, Email = Email, FirstName = FirstName, Gender = VGender, Id = Id, Image = Image, LastName = LastName, PhoneNumber = PhoneNumber, UserName = Username, UserType = user.UserType, Events = events
                    };
                    return(Ok(api));
                }
                else
                {
                    return(Ok(result));
                }
            }
            else
            {
                await _signInManager.SignInAsync(user, isPersistent : false);

                var token = _context.UserPushToken.Where(x => x.Token == Token).FirstOrDefault();
                if (token != null)
                {
                    token.User = user;
                }
                _context.SaveChanges();
                string   Address      = !string.IsNullOrEmpty(user.Address) ? user.Address : "";
                string   Age          = !string.IsNullOrEmpty(user.Age) ? user.Age : "";
                string   City         = !string.IsNullOrEmpty(user.City) ? user.City : "";
                string   Country      = !string.IsNullOrEmpty(user.Country) ? user.Country : "";
                DateTime CreationDate = user.CreationDate;
                Gender   VGender      = user.Gender;
                string   Id           = user.Id;
                string   Image        = user.Image;
                string   PhoneNumber  = !string.IsNullOrEmpty(user.PhoneNumber) ? user.PhoneNumber : "";
                UserType UserType     = user.UserType;
                var      events       = _context.Events.Where(x => x.UserId == user.Id).FirstOrDefault();
                if (events != null)
                {
                    if (!string.IsNullOrEmpty(events.Image))
                    {
                        events.Image = "http://" + Request.Host + "/Media/" + events.Image;
                    }
                }
                else
                {
                    events = new Events {
                    }
                };
                ApiUsersViewModel api = new ApiUsersViewModel {
                    Address = Address, Age = Age, City = City, Country = Country, CreationDate = CreationDate, Email = Email, FirstName = FirstName, Gender = VGender, Id = Id, Image = Image, LastName = LastName, PhoneNumber = PhoneNumber, UserName = Username, UserType = user.UserType, Events = events
                };
                return(Ok(api));
            }
        }
Example #39
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
        {
            IoCContainer.Provider = serviceProvider;

            using (var context = serviceProvider.GetService <ApplicationDbContext>())
            {
                //This only runs when the server starts
                context.Database.EnsureCreated();

                /**** MOVE ADD ROLES TO SQL FILE? ****/
                #region Add Roles
                if (context.Roles.Any() == false)
                {
                    RoleManager <IdentityRole> roleManager =
                        serviceProvider.GetService <RoleManager <IdentityRole> >();

                    // admin
                    roleManager.CreateAsync(new IdentityRole()
                    {
                        Name = "Administrator"
                    }).Wait();

                    // manager
                    roleManager.CreateAsync(new IdentityRole()
                    {
                        Name = "Manager"
                    }).Wait();

                    // user who has created an account
                    roleManager.CreateAsync(new IdentityRole()
                    {
                        Name = "GenericUser"
                    }).Wait();

                    // voter who has completed registration
                    roleManager.CreateAsync(new IdentityRole()
                    {
                        Name = "RegisteredVoter"
                    }).Wait();

                    // voter who has been varified by an admin or manager
                    roleManager.CreateAsync(new IdentityRole()
                    {
                        Name = "VerifiedVoter"
                    }).Wait();
                }
                #endregion

                #region Add Users
                if (context.Users.Any() == false)
                {
                    Random          random = new Random();
                    const string    chars  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    char[]          userName, email;
                    ApplicationUser user;
                    UserManager <ApplicationUser> userManager =
                        serviceProvider.GetService <UserManager <ApplicationUser> >();

                    user = new ApplicationUser
                    {
                        UserName       = "******",
                        Email          = "complete@random",
                        EmailConfirmed = true
                    };

                    //create an easy to login user
                    userManager.CreateAsync(user, "hello").Wait();

                    userManager.AddToRoleAsync(user, "Administrator").Wait();

                    //create 100 users for presenting
                    for (int i = 0; i < 100; i++)
                    {
                        userName = Enumerable.Repeat(chars, 10)
                                   .Select(s => s[random.Next(s.Length)]).ToArray();
                        email = Enumerable.Repeat(chars, 20)
                                .Select(s => s[random.Next(s.Length)]).ToArray();
                        email[10] = '@';

                        user = new ApplicationUser
                        {
                            UserName       = new string(userName),
                            Email          = new string(email),
                            EmailConfirmed = true
                        };

                        userManager.CreateAsync(user, "hello").Wait();
                        userManager.AddToRoleAsync(user, "GenericUser").Wait();
                    }
                }
                #endregion

                /**** MOVE ADD OFFICES TO SQL FILE? ****/
                #region Add Offices
                if (context.Office.Any() == false)
                {
                    // from: http://www.politicalcampaigningtips.com/the-big-list-of-local-elected-offices-for-political-candidates/
                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "State Senator",
                        OfficeDescription = "The State Senate consists of representatives who are elected in districts that usually span several cities and counties.",
                        OfficeLevel       = "High-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "State Representative",
                        OfficeDescription = "The State House of Representatives, or State Assembly as it is called in some states, generally consists of members who are elected in from districts for terms of two years.",
                        OfficeLevel       = "High-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "Board of County Commissioners",
                        OfficeDescription = "The position of County Commissioner is usually a full-time position with a term of four years.",
                        OfficeLevel       = "High-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "County Executive",
                        OfficeDescription = "Some counties have an elected County Executive in addition to, or instead of, County Commissioners.",
                        OfficeLevel       = "High-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "County Auditor",
                        OfficeDescription = "This position is appointed in some counties, but is a elected office in most with a four-year term.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "County Engineer",
                        OfficeDescription = "Many states only allow certified engineers to run for this position, which handles building, construction and road projects in the county.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "County Treasurer",
                        OfficeDescription = "The County Treasurer usually caries an elected, four-year term, but isn’t as much of a high-profile county race as Commissioner or Prosecutor.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "County Prosecuting Attorney",
                        OfficeDescription = "The County Prosecutor is among the most powerful and influential elected positions you can run for on the county level, but not everyone can qualify for the seat: you need to be an attorney to run. It is usually a full-time, four-year term.",
                        OfficeLevel       = "High-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "County Coroner",
                        OfficeDescription = "Surprisingly, this is actually an elected position in many counties, and to run for it you usually need to have your medical license or degree.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "County Recorder",
                        OfficeDescription = "This is another four-year elected county office which, like County Treasurer, is a bit more low-profile. In some counties, this position is appointed, not elected.",
                        OfficeLevel       = "Low-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "Common Pleas Court Judge",
                        OfficeDescription = "This is another elected office that has requirements to run: in order to be a candidate, you need to have your law degree or license, and most candidates are practicing attorneys.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "Clerk of Court",
                        OfficeDescription = "You do not generally have to have a law degree to run for Clerk of Courts, but most candidates who run a political campaign for the office are attorneys. Clerk of Courts usually carries a four-year, full-time term.",
                        OfficeLevel       = "Low-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "Mayor",
                        OfficeDescription = "This is usually a full-time, four-year elected position, although the Mayor can also be part-time in smaller cities, villages, towns and townships. Mayor is generally considered the most powerful local elected position in a city.",
                        OfficeLevel       = "High-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "City Manager",
                        OfficeDescription = "In some cities, a City Manager is elected–or appointed by City Council–instead of a Mayor. Generally, City Managers have experience in urban planning and related fields. If the position is appointed, then City Council usually launches a recruitment campaign and interviews candidates from around the state or country for the job.",
                        OfficeLevel       = "High-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "City Treasurer",
                        OfficeDescription = "The City Treasurer keeps track of municipal bank accounts, income, taxes and other money matters. It is usually a four-year term, but is not considered full-time.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "City Auditor",
                        OfficeDescription = "The Auditor for a given city is also usually a four-year, part-time elected position. In most cases, successful City Auditor candidates also have similar careers and educational backgrounds.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "City Law Director",
                        OfficeDescription = "This is another local elected office that usually carries the requirement of having a law degree or license. The four-year, part-time position is in many cases held by a practicing attorney.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "President of City Council",
                        OfficeDescription = "Council President is usually in charge of setting agendas, committee assignments and chairing city council meetings. Many City Council Presidents hold office for two-year, part-time terms and are elected by the entire city.",
                        OfficeLevel       = "High-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "City Ward Councilman",
                        OfficeDescription = "City Council is in many cases made up of councilpersons who are elected in individual city wards, as well as at-large council members who are elected by the entire city.",
                        OfficeLevel       = "Low-Profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "At-Large Councilman",
                        OfficeDescription = "A Councilman/Councilwoman At-Large has the same duties as a ward councilperson, but they are elected by voters across the entire city instead of voters only in a specific ward.",
                        OfficeLevel       = "Low-Profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "Town Council",
                        OfficeDescription = "The legislative body of smaller villages, towns and townships are usually made up of trustees, which perform duties similar to that of city councilpersons and hold two-year, part-time terms.",
                        OfficeLevel       = "Low-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "School Board Member",
                        OfficeDescription = "Candidates for School Board run for elected office in the school districts where they reside, and are in charge of voting on school issues. It is usually a two-year, part-time, paid position.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.Office.Add(new OfficeDataModel
                    {
                        OfficeName        = "Precinct Committeeman",
                        OfficeDescription = "Each political party in a given county–Democrats and Republicans–is usually made up of elected precinct committee members, and they vote on county party issues like leadership and appointments to vacant offices. Precinct committee members are usually elected during presidential primary elections, and you can only run for precinct committeeman or committeewoman in your own precinct and for the party in which you are registered.",
                        OfficeLevel       = "Medium-profile"
                    });

                    context.SaveChanges();
                }
                #endregion

                #region Add District for each state
                string StateAbbreviation(string abbreviation)
                {
                    switch (abbreviation.ToUpper())
                    {
                    case "AL": return("Alabama");

                    case "AK": return("Alaska");

                    case "AZ": return("Arizona");

                    case "AR": return("Arkansas");

                    case "CA": return("California");

                    case "CO": return("Colorado");

                    case "CT": return("Connecticut");

                    case "DE": return("Delaware");

                    case "FL": return("Florida");

                    case "GA": return("Georgia");

                    case "HI": return("Hawaii");

                    case "ID": return("Idaho");

                    case "IL": return("Illinois");

                    case "IN": return("Indiana");

                    case "IA": return("Iowa");

                    case "KS": return("Kansas");

                    case "KY": return("Kentucky");

                    case "LA": return("Louisiana");

                    case "ME": return("Maine");

                    case "MD": return("Maryland");

                    case "MA": return("Massachusetts");

                    case "MI": return("Michigan");

                    case "MN": return("Minnesota");

                    case "MS": return("Mississippi");

                    case "MO": return("Missouri");

                    case "MT": return("Montana");

                    case "NE": return("Nebraska");

                    case "NV": return("Nevada");

                    case "NH": return("New Hampshire");

                    case "NJ": return("New Jersey");

                    case "NM": return("New Mexico");

                    case "NY": return("New York");

                    case "NC": return("North Carolina");

                    case "ND": return("North Dakota");

                    case "OH": return("Ohio");

                    case "OK": return("Oklahoma");

                    case "OR": return("Oregon");

                    case "PA": return("Pennsylvania");

                    case "RI": return("Rhode Island");

                    case "SC": return("South Carolina");

                    case "SD": return("South Dakota");

                    case "TN": return("Tennessee");

                    case "TX": return("Texas");

                    case "UT": return("Utah");

                    case "VT": return("Vermont");

                    case "VA": return("Virginia");

                    case "WA": return("Washington");

                    case "WV": return("West Virginia");

                    case "WI": return("Wisconsin");

                    case "WY": return("Wyoming");

                    case "GU": return("Guam");

                    case "PR": return("Puerto Rico");

                    case "VI": return("Virgin Islands");

                    default: return(abbreviation);
                    }
                }

                if (context.Zip.Any() == true)
                {
                    if (context.District.Any() == false)
                    {
                        IEnumerable <string> states = context.Zip.GroupBy(z => z.State).Select(grp => grp.FirstOrDefault().State);

                        foreach (string state in states)
                        {
                            if (StateAbbreviation(state) == "Empty")
                            {
                                continue;
                            }

                            var district = new DistrictDataModel()
                            {
                                DistrictName = "State of " + StateAbbreviation(state)
                            };
                            district.Zip = context.Zip.Where(z => z.State == state).Select(z => new ZipFillsDistrict()
                            {
                                DistrictName = district.DistrictName,
                                District     = district,
                                ZipCode      = z.ZipCode,
                                Zip          = z
                            }).ToList();
                            context.District.Add(district);
                        }

                        context.SaveChanges();
                    }
                }
                #endregion
            }

            // setup identity
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Shared/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Example #40
0
        public static void Seed(UserManager <AppUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            using var context = new BlogDbContext();
            context.Database.Migrate();

            if (!context.Users.Any())
            {
                var user = new AppUser {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };

                var result = userManager?.CreateAsync(user, "123");
                if (result != null && result.Result.Succeeded)
                {
                    var role       = new IdentityRole(ConstStrings.Admin);
                    var resultRole = roleManager?.CreateAsync(role);

                    if (resultRole != null && resultRole.Result.Succeeded)
                    {
                        var resultAddTole = userManager.AddToRoleAsync(user, role.Name);

                        if (resultAddTole.Result.Succeeded)
                        {
                            context.SaveChanges();
                        }
                    }
                }
            }

            if (!context.Categories.Any())
            {
                context.Categories.AddRange(
                    new Category {
                    Name = "Category1"
                },
                    new Category {
                    Name = "Category2"
                },
                    new Category {
                    Name = "Category3"
                },
                    new Category {
                    Name = "Category4"
                },
                    new Category {
                    Name = "Category5"
                }
                    );
                context.SaveChanges();
            }

            if (!context.Blogs.Any())
            {
                const string body             = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sed ligula a nunc euismod elementum sit amet sed ipsum. Suspendisse potenti. Morbi in risus efficitur, tincidunt dui id, malesuada diam. Fusce faucibus ante mi, nec rutrum metus laoreet eu. Quisque sit amet diam pellentesque, aliquet neque sed, vulputate lectus. Praesent at libero risus. Phasellus a dignissim mauris, sit amet suscipit risus. Integer ultricies eu turpis a convallis. Morbi vehicula, purus at ultricies dapibus, enim neque porta nunc, eu posuere quam tortor ut neque. Maecenas et sapien scelerisque, tempus mauris in, porttitor lacus.";
                const string bodyWithLightBox = @"<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sed ligula a nunc euismod elementum sit amet sed ipsum. Suspendisse potenti.
                                                Morbi in risus efficitur, tincidunt dui id, malesuada diam. Fusce faucibus ante mi, nec rutrum metus laoreet eu. Quisque sit amet diam pellentesque, aliquet neque sed, vulputate lectus.
                                                Praesent at libero risus. Phasellus a dignissim mauris, sit amet suscipit risus. Integer ultricies eu turpis a convallis. Morbi vehicula, purus at ultricies dapibus, enim neque porta nunc,
                                                eu posuere quam tortor ut neque. Maecenas et sapien scelerisque, tempus mauris in, porttitor lacus.</p>
                                                
                                                <p><a href='https://images.pexels.com/photos/1292301/pexels-photo-1292301.jpeg?auto=compress&amp;cs=tinysrgb' data-lightbox='trees' data-title='Sample image1'>
                                                <img alt='image-1' src='https://images.pexels.com/photos/1292301/pexels-photo-1292301.jpeg?auto=compress&amp;cs=tinysrgb' /> </a></p>
                                                
                                                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sed ligula a nunc euismod elementum sit amet sed ipsum. Suspendisse potenti. Morbi in risus efficitur, tincidunt dui id, malesuada diam. 
                                                Fusce faucibus ante mi, nec rutrum metus laoreet eu. Quisque sit amet diam pellentesque, aliquet neque sed, vulputate lectus. Praesent at libero risus. Phasellus a dignissim mauris, sit amet suscipit risus.
                                                Integer ultricies eu turpis a convallis. Morbi vehicula, purus at ultricies dapibus, enim neque porta nunc, eu posuere quam tortor ut neque. Maecenas et sapien scelerisque, tempus mauris in, porttitor lacus.</p>
                                                
                                                <p><a href='https://images.pexels.com/photos/774861/pexels-photo-774861.jpeg?auto=compress&cs=tinysrgb' data-lightbox='trees' data-title='Sample image2'>
                                                <img alt='image-2' src='https://images.pexels.com/photos/774861/pexels-photo-774861.jpeg?auto=compress&cs=tinysrgb' /> </a></p>";
                const string desc             = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sed ligula a nunc euismod elementum sit amet sed ipsum.";

                context.Set <Blog>().AddRange(
                    new Blog {
                    Title       = "Title1",
                    Body        = bodyWithLightBox,
                    Date        = DateTime.Now,
                    CategoryId  = context.Categories.FirstOrDefault(x => x.Name == "Category1")?.Id,
                    Description = desc,
                    Image       = "1.jpg",
                    ImageThumb  = "1_thumb.jpg",
                    IsApproved  = true
                },
                    new Blog {
                    Title       = "Title2",
                    Body        = body,
                    Date        = DateTime.Now,
                    CategoryId  = context.Categories.FirstOrDefault(x => x.Name == "Category1")?.Id,
                    Description = desc,
                    Image       = "2.jpg",
                    ImageThumb  = "2_thumb.jpg",
                    IsApproved  = true
                },
                    new Blog {
                    Title       = "Title3",
                    Body        = body,
                    Date        = DateTime.Now,
                    CategoryId  = context.Categories.FirstOrDefault(x => x.Name == "Category2")?.Id,
                    Description = desc,
                    Image       = "3.jpg",
                    ImageThumb  = "3_thumb.jpg",
                    IsApproved  = true
                },
                    new Blog {
                    Title       = "Title4",
                    Body        = body,
                    Date        = DateTime.Now,
                    CategoryId  = context.Categories.FirstOrDefault(x => x.Name == "Category2")?.Id,
                    Description = desc,
                    Image       = "4.jpg",
                    ImageThumb  = "4_thumb.jpg",
                    IsApproved  = true
                },
                    new Blog {
                    Title       = "Title5",
                    Body        = body,
                    Date        = DateTime.Now,
                    CategoryId  = context.Categories.FirstOrDefault(x => x.Name == "Category3")?.Id,
                    Description = desc,
                    Image       = "5.jpg",
                    ImageThumb  = "5_thumb.jpg",
                    IsApproved  = true
                },
                    new Blog {
                    Title       = "Title6",
                    Body        = body,
                    Date        = DateTime.Now,
                    CategoryId  = context.Categories.FirstOrDefault(x => x.Name == "Category3")?.Id,
                    Description = desc,
                    Image       = "6.jpg",
                    ImageThumb  = "6_thumb.jpg",
                    IsApproved  = true
                },
                    new Blog {
                    Title       = "Title7",
                    Body        = body,
                    Date        = DateTime.Now,
                    CategoryId  = context.Categories.FirstOrDefault(x => x.Name == "Category4")?.Id,
                    Description = desc,
                    Image       = "7.jpg",
                    ImageThumb  = "7_thumb.jpg",
                    IsApproved  = true
                },
                    new Blog {
                    Title       = "Title8",
                    Body        = body,
                    Date        = DateTime.Now,
                    CategoryId  = context.Categories.FirstOrDefault(x => x.Name == "Category4")?.Id,
                    Description = desc,
                    Image       = "8.jpg",
                    ImageThumb  = "8_thumb.jpg",
                    IsApproved  = true
                },
                    new Blog {
                    Title       = "Title9",
                    Body        = bodyWithLightBox,
                    Date        = DateTime.Now,
                    CategoryId  = context.Categories.FirstOrDefault(x => x.Name == "Category4")?.Id,
                    Description = desc,
                    Image       = "9.jpg",
                    ImageThumb  = "9_thumb.jpg",
                    IsApproved  = true
                }
                    );

                context.SaveChanges();
            }
        }
Example #41
0
        public async Task <ActionResult <BatchRegisterResponse> > Register(BatchRegisterRequest request)
        {
            if (request.StartIndex < 0)
            {
                return(BadRequest(nameof(request.StartIndex)));
            }

            if (request.EndIndex < request.StartIndex)
            {
                return(BadRequest(nameof(request.EndIndex)));
            }

            if (string.IsNullOrEmpty(request.Prefix))
            {
                return(BadRequest(nameof(request.Prefix)));
            }

            var numberCount = (int)MathF.Floor(MathF.Log10(request.EndIndex) + 1);
            var format      = request.Prefix + "{0:" + new string('0', numberCount) + "}";

            var users = new List <PasswordResponse>(request.EndIndex - request.StartIndex + 1);

            for (var i = request.StartIndex; i <= request.EndIndex; i++)
            {
                var userName = string.Format(format, i);
                var password = _passwordGenerator.GeneratePassword();

                var user = new ApplicationUser
                {
                    Id       = Guid.NewGuid().ToString(),
                    UserName = userName
                };

                var result = await _userManager.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    users.Add(new PasswordResponse
                    {
                        Id       = user.Id,
                        UserName = user.UserName,
                        Password = password
                    });
                }
                else
                {
                    var errorResponse = new BatchRegisterResponse
                    {
                        Errors             = result.Errors,
                        GeneratedPasswords = users
                    };

                    return(errorResponse);
                }
            }

            var response = new BatchRegisterResponse
            {
                GeneratedPasswords = users
            };

            return(response);
        }
        public async Task <IActionResult> TrainerProfile(int trainerId, string email, string password, string phoneNumber)
        {
            //AppUser user = await userManager.FindByIdAsync(id);
            AppUser user = userManager.Users.FirstOrDefault(u => u.TrainerId == trainerId);

            if (user != null)
            {
                IdentityResult validUser = null;
                IdentityResult validPass = null;

                user.Email       = email;
                user.UserName    = email;
                user.PhoneNumber = phoneNumber;

                if (string.IsNullOrEmpty(email))
                {
                    ModelState.AddModelError("", "Email cannot be empty");
                }

                validUser = await userValidator.ValidateAsync(userManager, user);

                if (!validUser.Succeeded)
                {
                    Errors(validUser);
                }

                if (!string.IsNullOrEmpty(password))
                {
                    validPass = await passwordValidator.ValidateAsync(userManager, user, password);

                    if (validPass.Succeeded)
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user, password);
                    }
                    else
                    {
                        Errors(validPass);
                    }
                }

                if (validUser != null && validUser.Succeeded && (string.IsNullOrEmpty(password) || validPass.Succeeded))
                {
                    IdentityResult result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction(nameof(TrainerProfile), new { trainerId }));
                    }
                    else
                    {
                        Errors(result);
                    }
                }
            }
            else
            {
                AppUser        newuser   = new AppUser();
                IdentityResult validUser = null;
                IdentityResult validPass = null;

                newuser.Email       = email;
                newuser.UserName    = email;
                newuser.PhoneNumber = phoneNumber;
                newuser.TrainerId   = trainerId;
                newuser.Role        = "Trainer";

                if (string.IsNullOrEmpty(email))
                {
                    ModelState.AddModelError("", "Email cannot be empty");
                }

                validUser = await userValidator.ValidateAsync(userManager, newuser);

                if (!validUser.Succeeded)
                {
                    Errors(validUser);
                }

                if (!string.IsNullOrEmpty(password))
                {
                    validPass = await passwordValidator.ValidateAsync(userManager, newuser, password);

                    if (validPass.Succeeded)
                    {
                        newuser.PasswordHash = passwordHasher.HashPassword(newuser, password);
                    }
                    else
                    {
                        Errors(validPass);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Password cannot be empty");
                }

                if (validUser != null && validUser.Succeeded && validPass != null && validPass.Succeeded)
                {
                    IdentityResult result = await userManager.CreateAsync(newuser, password);

                    if (result.Succeeded)
                    {
                        await userManager.AddToRoleAsync(newuser, "Trainer");

                        return(RedirectToAction(nameof(TrainerProfile), new { trainerId }));
                    }
                    else
                    {
                        Errors(result);
                    }
                }
                user = newuser;
            }
            Trainer trainer = _context.Trainer.Where(s => s.Id == trainerId).FirstOrDefault();

            if (trainer != null)
            {
                ViewData["Name"]      = trainer.FullName;
                ViewData["TrainerId"] = trainer.Id;
            }
            return(View(user));
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            string role = Request.Form["rdUseRole"].ToString();   //--> We declare a variable and fetch the name of the role inside a Role variable.

            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName      = Input.Email,
                    Email         = Input.Email,
                    Name          = Input.Name,
                    City          = Input.City,
                    StreetAddress = Input.StreetAddress,
                    State         = Input.State,
                    PostalCode    = Input.PostalCode,
                    PhoneNumber   = Input.PhoneNumber
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    if (!await _roleManager.RoleExistsAsync(SD.ManegerUser))   //--> We create a user Role.
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.ManegerUser));
                    }

                    if (!await _roleManager.RoleExistsAsync(SD.kitchenUser))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.kitchenUser));
                    }

                    if (!await _roleManager.RoleExistsAsync(SD.FrontDeskUser))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.FrontDeskUser));
                    }

                    if (!await _roleManager.RoleExistsAsync(SD.CustomerEndUser))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.CustomerEndUser));
                    }

                    //-------------------------We declare user's role--------------------//

                    if (role == SD.kitchenUser)
                    {
                        await _userManager.AddToRoleAsync(user, SD.kitchenUser); //--> We asign specific role to user.
                    }
                    else
                    {
                        if (role == SD.FrontDeskUser)
                        {
                            await _userManager.AddToRoleAsync(user, SD.FrontDeskUser); //--> We asign specific role to user.
                        }
                        else
                        {
                            if (role == SD.ManegerUser)
                            {
                                await _userManager.AddToRoleAsync(user, SD.ManegerUser); //--> We asign specific role to user.
                            }
                            else
                            {
                                await _userManager.AddToRoleAsync(user, SD.CustomerEndUser); //--> We asign specific role to user.

                                await _signInManager.SignInAsync(user, isPersistent : false);

                                return(LocalRedirect(returnUrl));  //--> When we create a user we want to redirect to User list page.
                            }
                        }
                    }

                    return(RedirectToAction("Index", "User", new { area = "Admin" }));  //-> If it is not a user we want to redirect it o the Index page.

                    //-----------------------------------------------------------------------//

                    _logger.LogInformation("User created a new account with password.");

                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Page(
                    //    "/Account/ConfirmEmail",
                    //    pageHandler: null,
                    //    values: new { userId = user.Id, code = code },
                    //    protocol: Request.Scheme);

                    //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Example #44
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, CheckNoteContext dbContext, UserManager<User> userManager, RoleManager<Role> roleManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseGraphQL<Schema.Schema>();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToPage("/_Host");
            });

            try
            {
                dbContext.Database.ExecuteSqlRaw("CREATE UNIQUE INDEX UK_CourseNote ON CourseNotes (NoteId, CourseId);");
                dbContext.Database.ExecuteSqlRaw("CREATE UNIQUE INDEX UK_NoteTag ON NoteTags (NoteId, TagId);");
                dbContext.Database.ExecuteSqlRaw("CREATE UNIQUE INDEX UK_CourseLike ON CourseLikes (UserId, CourseId);");
                dbContext.Database.ExecuteSqlRaw("CREATE UNIQUE INDEX UK_NoteLike ON NoteLikes (UserId, NoteId);");
                dbContext.Database.ExecuteSqlRaw(@"
                    CREATE TRIGGER NoteModifiedAt
                        ON [dbo].[Notes]
                        FOR INSERT, UPDATE
                    AS
                    BEGIN
                        SET NOCOUNT ON;

	                    IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;

	                    DECLARE @Id INT

	                    SELECT @Id = INSERTED.Id
	                    FROM INSERTED

	                    UPDATE dbo.Notes
	                    SET ModifiedAt = GETDATE()
	                    WHERE Id = @Id
                    END
                ");
            }
            catch (SqlException e) when (e.Number == 1913) { }

            if (!roleManager.RoleExistsAsync(Role.Admin).Result)
            {
                roleManager.CreateAsync(new Role { Name = Role.Admin }).Wait();
            }

            var admin = userManager.FindByNameAsync("admin").Result;

            if (admin == null)
            {
                var newAdmin = new User { UserName = "******", Email = "*****@*****.**" };

                userManager.CreateAsync(newAdmin, "admin").Wait();
                userManager.AddToRoleAsync(newAdmin, Role.Admin).Wait();
            }
        }
Example #45
0
        /// <summary>
        /// Invites a user
        /// </summary>
        /// <param name="userSave"></param>
        /// <returns></returns>
        /// <remarks>
        /// This will email the user an invite and generate a token that will be validated in the email
        /// </remarks>
        public async Task <UserDisplay> PostInviteUser(UserInvite userSave)
        {
            if (userSave == null)
            {
                throw new ArgumentNullException("userSave");
            }

            if (userSave.Message.IsNullOrWhiteSpace())
            {
                ModelState.AddModelError("Message", "Message cannot be empty");
            }

            if (ModelState.IsValid == false)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            IUser user;

            if (Current.Configs.Settings().Security.UsernameIsEmail)
            {
                //ensure it's the same
                userSave.Username = userSave.Email;
            }
            else
            {
                //first validate the username if we're showing it
                user = CheckUniqueUsername(userSave.Username, u => u.LastLoginDate != default || u.EmailConfirmedDate.HasValue);
            }
            user = CheckUniqueEmail(userSave.Email, u => u.LastLoginDate != default || u.EmailConfirmedDate.HasValue);

            var userMgr = TryGetOwinContext().Result.GetBackOfficeUserManager();

            if (!EmailSender.CanSendRequiredEmail && !userMgr.HasSendingUserInviteEventHandler)
            {
                throw new HttpResponseException(
                          Request.CreateNotificationValidationErrorResponse("No Email server is configured"));
            }

            //Perform authorization here to see if the current user can actually save this user with the info being requested
            var authHelper  = new UserEditorAuthorizationHelper(Services.ContentService, Services.MediaService, Services.UserService, Services.EntityService);
            var canSaveUser = authHelper.IsAuthorized(Security.CurrentUser, user, null, null, userSave.UserGroups);

            if (canSaveUser == false)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized, canSaveUser.Result));
            }

            if (user == null)
            {
                //we want to create the user with the UserManager, this ensures the 'empty' (special) password
                //format is applied without us having to duplicate that logic
                var identityUser = BackOfficeIdentityUser.CreateNew(userSave.Username, userSave.Email, GlobalSettings.DefaultUILanguage);
                identityUser.Name = userSave.Name;

                var created = await UserManager.CreateAsync(identityUser);

                if (created.Succeeded == false)
                {
                    throw new HttpResponseException(
                              Request.CreateNotificationValidationErrorResponse(string.Join(", ", created.Errors)));
                }

                //now re-look the user back up
                user = Services.UserService.GetByEmail(userSave.Email);
            }

            //map the save info over onto the user
            user = Mapper.Map(userSave, user);

            //ensure the invited date is set
            user.InvitedDate = DateTime.Now;

            //Save the updated user (which will process the user groups too)
            Services.UserService.Save(user);
            var display = Mapper.Map <UserDisplay>(user);

            var inviteArgs = new UserInviteEventArgs(
                Request.TryGetHttpContext().Result.GetCurrentRequestIpAddress(),
                performingUser: Security.GetUserId().Result,
                userSave,
                user);

            try
            {
                userMgr.RaiseSendingUserInvite(inviteArgs);
            }
            catch (Exception ex)
            {
                Logger.Error <UsersController>(ex, "An error occured in a custom event handler while inviting the user");
                throw new HttpResponseException(
                          Request.CreateNotificationValidationErrorResponse($"An error occured inviting the user (check logs for more info): {ex.Message}"));
            }

            // If the event is handled then no need to send the email
            if (inviteArgs.InviteHandled)
            {
                // if no user result was created then map the minimum args manually for the UI
                if (!inviteArgs.ShowUserResult)
                {
                    display = new UserDisplay
                    {
                        Name     = userSave.Name,
                        Email    = userSave.Email,
                        Username = userSave.Username
                    };
                }
            }
            else
            {
                //send the email
                await SendUserInviteEmailAsync(display, Security.CurrentUser.Name, Security.CurrentUser.Email, user, userSave.Message);
            }

            display.AddSuccessNotification(Services.TextService.Localize("speechBubbles/resendInviteHeader"), Services.TextService.Localize("speechBubbles/resendInviteSuccess", new[] { user.Name }));
            return(display);
        }
Example #46
0
        public async Task <IActionResult> Criar(Guid idDesafio, InscricaoRequest inscricaoRequest)
        {
            if (!ModelState.IsValid)
            {
                return(CustomResponse(ModelState));
            }

            var desafio = await _desafioService.FindAsNoTracking(idDesafio);

            if (desafio == null)
            {
                return(NotFound("Desafio não encontrado."));
            }

            if (desafio.Id != inscricaoRequest.DesafioId)
            {
                return(BadRequest("O id do desafio informado no payload é diferende do informado na rota."));
            }

            if (desafio.LimiteInscricao.HasValue)
            {
                var inscricoes = await _inscricaoService.ObterInscricoesDesafioCandidato(idDesafio);

                if (inscricoes.Count() >= desafio.LimiteInscricao)
                {
                    return(BadRequest("Este desafio já atingiu seu limite de inscrições."));
                }
            }

            if (desafio.DataFechamento.HasValue)
            {
                if (desafio.DataFechamento.Value <= DateTime.Now)
                {
                    return(BadRequest("Este desafio já foi fechado e não permite novas inscrições."));
                }
            }

            var user = new ApplicationUser
            {
                DataNascimento = inscricaoRequest.DataNascimento,
                Email          = inscricaoRequest.Email,
                LinkGithub     = inscricaoRequest.LinkGithub,
                LinkLinkedin   = inscricaoRequest.LinkLinkedin,
                Nome           = inscricaoRequest.Nome,
                PhoneNumber    = inscricaoRequest.Celular,
                UserName       = inscricaoRequest.Email
            };

            var result = await _userManager.CreateAsync(user, "Senhapadrao#1234");

            if (!result.Succeeded)
            {
                foreach (var erro in result.Errors)
                {
                    NotificarErro(erro.Description);
                }

                return(CustomResponse());
            }

            var candidato = new Candidato
            {
                ApplicationUserId = user.Id,
                Profissao         = inscricaoRequest.Profissao,
                Endereco          = _mapper.Map <Endereco>(inscricaoRequest.Endereco)
            };
            await _candidatoService.Add(candidato);

            await _userManager.AddToRoleAsync(user, "Candidato");

            var inscricao = new Inscricao
            {
                DesafioId         = idDesafio,
                CandidatoId       = candidato.Id,
                DataInscricao     = DateTime.Now,
                DataInicializacao = DateTime.Now,
                DataFinalizacao   = DateTime.Now
            };
            await _inscricaoService.Add(inscricao);

            foreach (var resposta in inscricaoRequest.Respostas)
            {
                await _respostaService.Add(new Resposta
                {
                    InscricaoId = inscricao.Id,
                    QuestaoId   = resposta.QuestaoId,
                    Descricao   = resposta.Descricao
                });
            }

            return(CustomResponse(new InscricaoCreateResponse
            {
                IdInscricao = inscricao.Id,
                Message = "Inscrição realizada com sucesso!"
            }));
        }
Example #47
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Example #48
0
        public async Task DupeUserClaimTest()
        {
            var db = UnitTestHelper.CreateDefaultDb();
            var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
            var user = new IdentityUser("u1");
            var result = await manager.CreateAsync(user);
            Assert.NotNull(user);
            var claims = new[]
            {
                new Claim("c1", "v1"),
                new Claim("c2", "v2"),
                new Claim("c3", "v3")
            };
            foreach (Claim c in claims)
            {
                // Add dupes
                UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
                UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
            }

            var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id));
            Assert.Equal(6, userClaims.Count);
            var currentExpected = 6;
            foreach (Claim c in claims)
            {
                Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
                UnitTestHelper.IsSuccess(await manager.RemoveClaimAsync(user.Id, c));
                var cs = await manager.GetClaimsAsync(user.Id);
                currentExpected -= 2;
                Assert.Equal(currentExpected, cs.Count());
                Assert.Equal(currentExpected, db.Set<IdentityUserClaim>().Count());
            }
        }
Example #49
0
        public virtual async Task <ActionResult> Register(RegisterViewModel model)
        {
            try
            {
                CheckModelState();

                //Get tenancy name and tenant
                if (!_multiTenancyConfig.IsEnabled)
                {
                    model.TenancyName = Tenant.DefaultTenantName;
                }
                else if (model.TenancyName.IsNullOrEmpty())
                {
                    throw new UserFriendlyException(L("TenantNameCanNotBeEmpty"));
                }

                var tenant = await GetActiveTenantAsync(model.TenancyName);

                //Create user
                var user = new User
                {
                    TenantId     = tenant.Id,
                    Name         = model.Name,
                    Surname      = model.Surname,
                    EmailAddress = model.EmailAddress,
                    IsActive     = true
                };

                //Get external login info if possible
                ExternalLoginInfo externalLoginInfo = null;
                if (model.IsExternalLogin)
                {
                    externalLoginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

                    if (externalLoginInfo == null)
                    {
                        throw new ApplicationException("Can not external login!");
                    }

                    user.Logins = new List <UserLogin>
                    {
                        new UserLogin
                        {
                            TenantId      = tenant.Id,
                            LoginProvider = externalLoginInfo.Login.LoginProvider,
                            ProviderKey   = externalLoginInfo.Login.ProviderKey
                        }
                    };

                    if (model.UserName.IsNullOrEmpty())
                    {
                        model.UserName = model.EmailAddress;
                    }

                    model.Password = Users.User.CreateRandomPassword();

                    if (string.Equals(externalLoginInfo.Email, model.EmailAddress, StringComparison.InvariantCultureIgnoreCase))
                    {
                        user.IsEmailConfirmed = true;
                    }
                }
                else
                {
                    //Username and Password are required if not external login
                    if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
                    {
                        throw new UserFriendlyException(L("FormIsNotValidMessage"));
                    }
                }

                user.UserName = model.UserName;
                user.Password = new PasswordHasher().HashPassword(model.Password);

                //Switch to the tenant
                _unitOfWorkManager.Current.EnableFilter(AbpDataFilters.MayHaveTenant); //TODO: Needed?
                _unitOfWorkManager.Current.SetTenantId(tenant.Id);

                //Add default roles
                user.Roles = new List <UserRole>();
                foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
                {
                    user.Roles.Add(new UserRole {
                        RoleId = defaultRole.Id
                    });
                }

                //Save user
                CheckErrors(await _userManager.CreateAsync(user));
                await _unitOfWorkManager.Current.SaveChangesAsync();

                //Directly login if possible
                if (user.IsActive)
                {
                    AbpLoginResult <Tenant, User> loginResult;
                    if (externalLoginInfo != null)
                    {
                        loginResult = await _logInManager.LoginAsync(externalLoginInfo.Login, tenant.TenancyName);
                    }
                    else
                    {
                        loginResult = await GetLoginResultAsync(user.UserName, model.Password, tenant.TenancyName);
                    }

                    if (loginResult.Result == AbpLoginResultType.Success)
                    {
                        await SignInAsync(loginResult.User, loginResult.Identity);

                        return(Redirect(Url.Action("Index", "Home")));
                    }

                    Logger.Warn("New registered user could not be login. This should not be normally. login result: " + loginResult.Result);
                }

                //If can not login, show a register result page
                return(View("RegisterResult", new RegisterResultViewModel
                {
                    TenancyName = tenant.TenancyName,
                    NameAndSurname = user.Name + " " + user.Surname,
                    UserName = user.UserName,
                    EmailAddress = user.EmailAddress,
                    IsActive = user.IsActive
                }));
            }
            catch (UserFriendlyException ex)
            {
                ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;
                ViewBag.ErrorMessage          = ex.Message;

                return(View("Register", model));
            }
        }
Example #50
0
        /// <summary>
        /// Creates a new user
        /// </summary>
        /// <param name="userSave"></param>
        /// <returns></returns>
        public async Task <UserDisplay> PostCreateUser(UserInvite userSave)
        {
            if (userSave == null)
            {
                throw new ArgumentNullException("userSave");
            }

            if (ModelState.IsValid == false)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (Current.Configs.Settings().Security.UsernameIsEmail)
            {
                //ensure they are the same if we're using it
                userSave.Username = userSave.Email;
            }
            else
            {
                //first validate the username if were showing it
                CheckUniqueUsername(userSave.Username, null);
            }
            CheckUniqueEmail(userSave.Email, null);

            //Perform authorization here to see if the current user can actually save this user with the info being requested
            var authHelper  = new UserEditorAuthorizationHelper(Services.ContentService, Services.MediaService, Services.UserService, Services.EntityService);
            var canSaveUser = authHelper.IsAuthorized(Security.CurrentUser, null, null, null, userSave.UserGroups);

            if (canSaveUser == false)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized, canSaveUser.Result));
            }

            //we want to create the user with the UserManager, this ensures the 'empty' (special) password
            //format is applied without us having to duplicate that logic
            var identityUser = BackOfficeIdentityUser.CreateNew(userSave.Username, userSave.Email, GlobalSettings.DefaultUILanguage);

            identityUser.Name = userSave.Name;

            var created = await UserManager.CreateAsync(identityUser);

            if (created.Succeeded == false)
            {
                throw new HttpResponseException(
                          Request.CreateNotificationValidationErrorResponse(string.Join(", ", created.Errors)));
            }

            //we need to generate a password, however we can only do that if the user manager has a password validator that
            //we can read values from
            var passwordValidator = UserManager.PasswordValidator as PasswordValidator;
            var resetPassword     = string.Empty;

            if (passwordValidator != null)
            {
                var password = UserManager.GeneratePassword();

                var result = await UserManager.AddPasswordAsync(identityUser.Id, password);

                if (result.Succeeded == false)
                {
                    throw new HttpResponseException(
                              Request.CreateNotificationValidationErrorResponse(string.Join(", ", created.Errors)));
                }
                resetPassword = password;
            }

            //now re-look the user back up which will now exist
            var user = Services.UserService.GetByEmail(userSave.Email);

            //map the save info over onto the user
            user = Mapper.Map(userSave, user);

            //since the back office user is creating this user, they will be set to approved
            user.IsApproved = true;

            Services.UserService.Save(user);

            var display = Mapper.Map <UserDisplay>(user);

            display.ResetPasswordValue = resetPassword;
            return(display);
        }
        public async Task<ActionResult> Customize(RegisterViewModel model)
        {
            var context = new MyDbContext();
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            // The default Validators that the UserManager uses are UserValidator and MinimumLengthValidator
            // If you want to have complete control over validation then you can write your own validators.
            UserManager.UserValidator = new MyUserValidation();
            UserManager.PasswordValidator = new MyPasswordValidation();
            UserManager.PasswordHasher = new PasswordHasher();


            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                user.HomeTown = model.HomeTown;
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var authManager = HttpContext.GetOwinContext().Authentication;
                    var claimsIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authManager.SignIn(claimsIdentity);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View("Index",model);
        }
        public async Task <User> LoginAndRegisterIfNeeded(string user, string pass)
        {
            if (_btcTransmuterOptions.BTCPayAuthServer is null)
            {
                return(null);
            }

            var response = await BasicAuthLogin(user, pass);

            if (response == null)
            {
                return(null);
            }

            var matchedUser = await FindUserByBTCPayUserId(response.Id);

            if (matchedUser == null)
            {
                var key = await GenerateKey(user, pass);

                if (string.IsNullOrEmpty(key))
                {
                    return(null);
                }

                //create account
                matchedUser = new User()
                {
                    Email    = response.Email,
                    Id       = response.Id,
                    UserName = response.Email,
                };
                matchedUser.Set(new UserBlob()
                {
                    BTCPayAuthDetails = new BTCPayAuthDetails()
                    {
                        UserId      = response.Id,
                        AccessToken = key
                    }
                });
                if ((await _userManager.CreateAsync(matchedUser)).Succeeded)
                {
                    if (response.Roles.Contains("ServerAdmin") || await _userManager.Users.CountAsync() == 1)
                    {
                        await _userManager.AddToRoleAsync(matchedUser, "Admin");
                    }
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                var tokenResponse = await CheckToken(matchedUser);

                if (!(tokenResponse?.ToString()?.Equals(response.ToString()) is true) &&
                    await GenerateKeyAndSet(user, pass, matchedUser))
                {
                    await _userManager.UpdateAsync(matchedUser);
                }
Example #53
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            var dbmgtm = new ApplicationDbContext();

            IdentityResult result;
            
            using (var securitytrans = dbmgtm.Database.BeginTransaction())
            {
                        try 
                        {
                                if (ModelState.IsValid)
                                {
                                    var user = new ApplicationUser()
                                    {
                                        UserName = model.UserName,
                                        FirstName = model.FirstName,
                                        LastName = model.LastName,
                                        Email = model.Email
                                    };
                

                                    var um = new UserManager<ApplicationUser>(
                                    new UserStore<ApplicationUser>(dbmgtm));

                                    result = await um.CreateAsync(user, model.Password);
                                    

                                    if (result.Succeeded)
                                    {   
                                        
                                        UserPreference userpref = new UserPreference()
                                        {
                                            UserID = user.Id,
                                            UserName = model.UserName,
                                            SchoolRefID = model.SchoolID,
                                            AcademicYearRefID = model.AcademicYearID
                                        };
                                        dbmgtm.UserPreferences.Add(userpref);

                                        await dbmgtm.SaveChangesAsync();
                                        securitytrans.Commit();
                                        //await SignInAsync(user, isPersistent: false);
                                        return RedirectToAction("Index", "Account");
                                    }
                            }
                          
                    }
                    catch (Exception e)
                    {
                                                                         
                        securitytrans.Rollback();
                        ModelState.AddModelError("", e.Message);
                        ViewBag.SchoolID = new SelectList(dbmgtm.Schools.AsNoTracking().Select(x => new { x.SchoolID, x.SchoolName }), "SchoolID", "SchoolName", model.SchoolID);
                        ViewBag.AcademicYearID = new SelectList(dbmgtm.AcademicYears.AsNoTracking().Select(x => new { x.AcademicYearID, x.DisplayYear }), "AcademicYearID", "DisplayYear", model.AcademicYearID);
                       return View(model);
                    }
                }
            
                ViewBag.SchoolID = new SelectList(dbmgtm.Schools.AsNoTracking().Select(x => new { x.SchoolID, x.SchoolName }), "SchoolID", "SchoolName", model.SchoolID);
                ViewBag.AcademicYearID = new SelectList(dbmgtm.AcademicYears.AsNoTracking().Select(x => new { x.AcademicYearID, x.DisplayYear }), "AcademicYearID", "DisplayYear", model.AcademicYearID);
            
            return View(model);                
                      
            } 
        public async Task EnsureSeedData()
        {
            if (await _userManager.FindByEmailAsync("*****@*****.**") == null)
            {
                var user = new WorldUser()
                {
                    UserName = "******",
                    Email    = "*****@*****.**",
                };

                await _userManager.CreateAsync(user, "P@ssw0rd!");
            }


            if (await _userManager.FindByEmailAsync("*****@*****.**") == null)
            {
                var user = new WorldUser()
                {
                    UserName = "******",
                    Email    = "*****@*****.**",
                };

                await _userManager.CreateAsync(user, "P@ssw0rd!");
            }


            if (!_context.Trips.Any())
            {
                var usTrip = new Trip()
                {
                    DateCreated = DateTime.UtcNow,

                    Name     = "US Trip",
                    UserName = "******",
                    Stops    = new List <Stop>()
                    {
                        new Stop()
                        {
                            Name = "Atlanta, GA", Arrival = new DateTime(2014, 6, 4), Latitude = 33.748995, Longitude = -84.387982, Order = 0
                        },
                        new Stop()
                        {
                            Name = "New York, NY", Arrival = new DateTime(2014, 6, 9), Latitude = 40.712784, Longitude = -74.005941, Order = 1
                        },
                        new Stop()
                        {
                            Name = "Boston, MA", Arrival = new DateTime(2014, 7, 1), Latitude = 42.360082, Longitude = -71.058880, Order = 2
                        },
                        new Stop()
                        {
                            Name = "Chicago, IL", Arrival = new DateTime(2014, 7, 10), Latitude = 41.878114, Longitude = -87.629798, Order = 3
                        },
                        new Stop()
                        {
                            Name = "Seattle, WA", Arrival = new DateTime(2014, 8, 13), Latitude = 47.606209, Longitude = -122.332071, Order = 4
                        },
                        new Stop()
                        {
                            Name = "Atlanta, GA", Arrival = new DateTime(2014, 8, 23), Latitude = 33.748995, Longitude = -84.387982, Order = 5
                        },
                    }
                };

                _context.Trips.Add(usTrip);

                _context.Stops.AddRange(usTrip.Stops);

                var worldTrip = new Trip()
                {
                    DateCreated = DateTime.UtcNow,
                    Name        = "WorldTrip",
                    UserName    = "",
                    Stops       = new List <Stop>()
                    {
                        new Stop()
                        {
                            Order = 0, Latitude = 33.748995, Longitude = -84.387982, Name = "Atlanta, Georgia", Arrival = DateTime.Parse("Jun 3, 2014")
                        },
                        new Stop()
                        {
                            Order = 1, Latitude = 48.856614, Longitude = 2.352222, Name = "Paris, France", Arrival = DateTime.Parse("Jun 4, 2014")
                        },
                        new Stop()
                        {
                            Order = 2, Latitude = 50.850000, Longitude = 4.350000, Name = "Brussels, Belgium", Arrival = DateTime.Parse("Jun 25, 2014")
                        },
                        new Stop()
                        {
                            Order = 3, Latitude = 51.209348, Longitude = 3.224700, Name = "Bruges, Belgium", Arrival = DateTime.Parse("Jun 28, 2014")
                        },
                        new Stop()
                        {
                            Order = 4, Latitude = 48.856614, Longitude = 2.352222, Name = "Paris, France", Arrival = DateTime.Parse("Jun 30, 2014")
                        },
                        new Stop()
                        {
                            Order = 5, Latitude = 51.508515, Longitude = -0.125487, Name = "London, UK", Arrival = DateTime.Parse("Jul 8, 2014")
                        },
                        new Stop()
                        {
                            Order = 6, Latitude = 51.454513, Longitude = -2.587910, Name = "Bristol, UK", Arrival = DateTime.Parse("Jul 24, 2014")
                        },
                        new Stop()
                        {
                            Order = 7, Latitude = 52.078000, Longitude = -2.783000, Name = "Stretton Sugwas, UK", Arrival = DateTime.Parse("Jul 29, 2014")
                        },
                        new Stop()
                        {
                            Order = 8, Latitude = 51.864211, Longitude = -2.238034, Name = "Gloucestershire, UK", Arrival = DateTime.Parse("Jul 30, 2014")
                        },
                        new Stop()
                        {
                            Order = 9, Latitude = 52.954783, Longitude = -1.158109, Name = "Nottingham, UK", Arrival = DateTime.Parse("Jul 31, 2014")
                        },
                        new Stop()
                        {
                            Order = 10, Latitude = 51.508515, Longitude = -0.125487, Name = "London, UK", Arrival = DateTime.Parse("Aug 1, 2014")
                        },
                        new Stop()
                        {
                            Order = 11, Latitude = 55.953252, Longitude = -3.188267, Name = "Edinburgh, UK", Arrival = DateTime.Parse("Aug 5, 2014")
                        },
                        new Stop()
                        {
                            Order = 12, Latitude = 55.864237, Longitude = -4.251806, Name = "Glasgow, UK", Arrival = DateTime.Parse("Aug 6, 2014")
                        },
                        new Stop()
                        {
                            Order = 13, Latitude = 57.149717, Longitude = -2.094278, Name = "Aberdeen, UK", Arrival = DateTime.Parse("Aug 7, 2014")
                        },
                        new Stop()
                        {
                            Order = 14, Latitude = 55.953252, Longitude = -3.188267, Name = "Edinburgh, UK", Arrival = DateTime.Parse("Aug 8, 2014")
                        },
                        new Stop()
                        {
                            Order = 15, Latitude = 51.508515, Longitude = -0.125487, Name = "London, UK", Arrival = DateTime.Parse("Aug 10, 2014")
                        },
                        new Stop()
                        {
                            Order = 16, Latitude = 52.370216, Longitude = 4.895168, Name = "Amsterdam, Netherlands", Arrival = DateTime.Parse("Aug 14, 2014")
                        },
                        new Stop()
                        {
                            Order = 17, Latitude = 48.583148, Longitude = 7.747882, Name = "Strasbourg, France", Arrival = DateTime.Parse("Aug 17, 2014")
                        },
                        new Stop()
                        {
                            Order = 18, Latitude = 46.519962, Longitude = 6.633597, Name = "Lausanne, Switzerland", Arrival = DateTime.Parse("Aug 19, 2014")
                        },
                        new Stop()
                        {
                            Order = 19, Latitude = 46.021073, Longitude = 7.747937, Name = "Zermatt, Switzerland", Arrival = DateTime.Parse("Aug 27, 2014")
                        },
                        new Stop()
                        {
                            Order = 20, Latitude = 46.519962, Longitude = 6.633597, Name = "Lausanne, Switzerland", Arrival = DateTime.Parse("Aug 29, 2014")
                        },
                        new Stop()
                        {
                            Order = 21, Latitude = 53.349805, Longitude = -6.260310, Name = "Dublin, Ireland", Arrival = DateTime.Parse("Sep 2, 2014")
                        },
                        new Stop()
                        {
                            Order = 22, Latitude = 54.597285, Longitude = -5.930120, Name = "Belfast, Northern Ireland", Arrival = DateTime.Parse("Sep 7, 2014")
                        },
                        new Stop()
                        {
                            Order = 23, Latitude = 53.349805, Longitude = -6.260310, Name = "Dublin, Ireland", Arrival = DateTime.Parse("Sep 9, 2014")
                        },
                        new Stop()
                        {
                            Order = 24, Latitude = 47.368650, Longitude = 8.539183, Name = "Zurich, Switzerland", Arrival = DateTime.Parse("Sep 16, 2014")
                        },
                        new Stop()
                        {
                            Order = 25, Latitude = 48.135125, Longitude = 11.581981, Name = "Munich, Germany", Arrival = DateTime.Parse("Sep 19, 2014")
                        },
                        new Stop()
                        {
                            Order = 26, Latitude = 50.075538, Longitude = 14.437800, Name = "Prague, Czech Republic", Arrival = DateTime.Parse("Sep 21, 2014")
                        },
                        new Stop()
                        {
                            Order = 27, Latitude = 51.050409, Longitude = 13.737262, Name = "Dresden, Germany", Arrival = DateTime.Parse("Oct 1, 2014")
                        },
                        new Stop()
                        {
                            Order = 28, Latitude = 50.075538, Longitude = 14.437800, Name = "Prague, Czech Republic", Arrival = DateTime.Parse("Oct 4, 2014")
                        },
                        new Stop()
                        {
                            Order = 29, Latitude = 42.650661, Longitude = 18.094424, Name = "Dubrovnik, Croatia", Arrival = DateTime.Parse("Oct 10, 2014")
                        },
                        new Stop()
                        {
                            Order = 30, Latitude = 42.697708, Longitude = 23.321868, Name = "Sofia, Bulgaria", Arrival = DateTime.Parse("Oct 16, 2014")
                        },
                        new Stop()
                        {
                            Order = 31, Latitude = 45.658928, Longitude = 25.539608, Name = "Brosov, Romania", Arrival = DateTime.Parse("Oct 20, 2014")
                        },
                        new Stop()
                        {
                            Order = 32, Latitude = 41.005270, Longitude = 28.976960, Name = "Istanbul, Turkey", Arrival = DateTime.Parse("Nov 1, 2014")
                        },
                        new Stop()
                        {
                            Order = 33, Latitude = 45.815011, Longitude = 15.981919, Name = "Zagreb, Croatia", Arrival = DateTime.Parse("Nov 11, 2014")
                        },
                        new Stop()
                        {
                            Order = 34, Latitude = 41.005270, Longitude = 28.976960, Name = "Istanbul, Turkey", Arrival = DateTime.Parse("Nov 15, 2014")
                        },
                        new Stop()
                        {
                            Order = 35, Latitude = 50.850000, Longitude = 4.350000, Name = "Brussels, Belgium", Arrival = DateTime.Parse("Nov 25, 2014")
                        },
                        new Stop()
                        {
                            Order = 36, Latitude = 50.937531, Longitude = 6.960279, Name = "Cologne, Germany", Arrival = DateTime.Parse("Nov 30, 2014")
                        },
                        new Stop()
                        {
                            Order = 37, Latitude = 48.208174, Longitude = 16.373819, Name = "Vienna, Austria", Arrival = DateTime.Parse("Dec 4, 2014")
                        },
                        new Stop()
                        {
                            Order = 38, Latitude = 47.497912, Longitude = 19.040235, Name = "Budapest, Hungary", Arrival = DateTime.Parse("Dec 28,2014")
                        },
                        new Stop()
                        {
                            Order = 39, Latitude = 37.983716, Longitude = 23.729310, Name = "Athens, Greece", Arrival = DateTime.Parse("Jan 2, 2015")
                        },
                        new Stop()
                        {
                            Order = 40, Latitude = -25.746111, Longitude = 28.188056, Name = "Pretoria, South Africa", Arrival = DateTime.Parse("Jan 19, 2015")
                        },
                        new Stop()
                        {
                            Order = 41, Latitude = 43.771033, Longitude = 11.248001, Name = "Florence, Italy", Arrival = DateTime.Parse("Feb 1, 2015")
                        },
                        new Stop()
                        {
                            Order = 42, Latitude = 45.440847, Longitude = 12.315515, Name = "Venice, Italy", Arrival = DateTime.Parse("Feb 9, 2015")
                        },
                        new Stop()
                        {
                            Order = 43, Latitude = 43.771033, Longitude = 11.248001, Name = "Florence, Italy", Arrival = DateTime.Parse("Feb 13, 2015")
                        },
                        new Stop()
                        {
                            Order = 44, Latitude = 41.872389, Longitude = 12.480180, Name = "Rome, Italy", Arrival = DateTime.Parse("Feb 17, 2015")
                        },
                        new Stop()
                        {
                            Order = 45, Latitude = 28.632244, Longitude = 77.220724, Name = "New Delhi, India", Arrival = DateTime.Parse("Mar 4, 2015")
                        },
                        new Stop()
                        {
                            Order = 46, Latitude = 27.700000, Longitude = 85.333333, Name = "Kathmandu, Nepal", Arrival = DateTime.Parse("Mar 10, 2015")
                        },
                        new Stop()
                        {
                            Order = 47, Latitude = 28.632244, Longitude = 77.220724, Name = "New Delhi, India", Arrival = DateTime.Parse("Mar 11, 2015")
                        },
                        new Stop()
                        {
                            Order = 48, Latitude = 22.1667, Longitude = 113.5500, Name = "Macau", Arrival = DateTime.Parse("Mar 21, 2015")
                        },
                        new Stop()
                        {
                            Order = 49, Latitude = 22.396428, Longitude = 114.109497, Name = "Hong Kong", Arrival = DateTime.Parse("Mar 24, 2015")
                        },
                        new Stop()
                        {
                            Order = 50, Latitude = 39.904030, Longitude = 116.407526, Name = "Beijing, China", Arrival = DateTime.Parse("Apr 19, 2015")
                        },
                        new Stop()
                        {
                            Order = 51, Latitude = 22.396428, Longitude = 114.109497, Name = "Hong Kong", Arrival = DateTime.Parse("Apr 24, 2015")
                        },
                        new Stop()
                        {
                            Order = 52, Latitude = 1.352083, Longitude = 103.819836, Name = "Singapore", Arrival = DateTime.Parse("Apr 30, 2015")
                        },
                        new Stop()
                        {
                            Order = 53, Latitude = 3.139003, Longitude = 101.686855, Name = "Kuala Lumpor, Malaysia", Arrival = DateTime.Parse("May 7, 2015")
                        },
                        new Stop()
                        {
                            Order = 54, Latitude = 13.727896, Longitude = 100.524123, Name = "Bangkok, Thailand", Arrival = DateTime.Parse("May 24, 2015")
                        },
                        new Stop()
                        {
                            Order = 55, Latitude = 33.748995, Longitude = -84.387982, Name = "Atlanta, Georgia", Arrival = DateTime.Parse("Jun 17, 2015")
                        },
                    }
                };

                _context.Trips.Add(worldTrip);

                _context.Stops.AddRange(worldTrip.Stops);

                await _context.SaveChangesAsync();
            }
        }
        public void LoginTest()
        {
            var userManager = new UserManager<ApplicationUser>(new TestUserStore());

            AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager);
            var mockAuthenticationManager = new Mock<IAuthenticationManager>();
            mockAuthenticationManager.Setup(am => am.SignOut());
            mockAuthenticationManager.Setup(am => am.SignIn());
            controller.AuthenticationManager = mockAuthenticationManager.Object;
            ApplicationUser user=new ApplicationUser()
            {
                UserName="******"
            };
            userManager.CreateAsync(user, "123456");
            var result = controller.Login(new LoginViewModel { Email = "adarsh", Password = "******", RememberMe = false }, "abcd").Result;
            Assert.IsNotNull(result);
            var addedUser = userManager.FindByName("adarsh");
            Assert.IsNotNull(addedUser);
            Assert.AreEqual("adarsh", addedUser.UserName);
        }
Example #56
-1
 private async static void InitializeUserAdmin(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
 {
     ApplicationUser admin = new ApplicationUser
     {
         UserName = "******",
         Email = "*****@*****.**",
         DateOfBirth = new DateTime(1990, 1, 1),
         EmailConfirmed = true
     };
     Thread.Sleep(2000);
     await userManager.CreateAsync(admin, "Beast@2"); //password must match constraints of 6 char min, case-change, min 1 number and non-letter character
     Thread.Sleep(2000);
     await userManager.AddToRoleAsync(admin, "admin");
     context.SaveChanges();
 }
Example #57
-6
        public async Task SetupAsync()
        {
            _userViewModel = new LoginViewModel
            {
                Email = "*****@*****.**",
                Password = "******",
                RememberMe = false
            };
            var context = new DataContext();
            _manager = new UserManager(new UserStore(context));
            _controller = new AccountController(_manager);

            var user = await _manager.FindAsync(_userViewModel.Email, _userViewModel.Password);
            if (user == null)
            {
                await _manager.CreateAsync(new User { Email = _userViewModel.Email, UserName = _userViewModel.Email }, _userViewModel.Password);
            }
            var mockCp = new Mock<IClaimsPrincipal>();
            if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
            _controller.CurrentUser = mockCp.Object;

            var mockAuthenticationManager = new Mock<IAuthenticationManager>();
            mockAuthenticationManager.Setup(am => am.SignOut());
            mockAuthenticationManager.Setup(am => am.SignIn());
            _controller.AuthenticationManager = mockAuthenticationManager.Object;
        }