// 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");
        }
 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();
        }
Example #5
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;
 }
        // 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 #7
0
        public async Task <IActionResult> Login([FromBody] LoginVM model)
        {
            if (ModelState.IsValid)
            {
                // Retrieve user by email or username
                User currentUser = await userManager.FindByEmailAsync(model.EmailOrUsername) ?? await userManager.FindByNameAsync(model.EmailOrUsername);

                // If no user is found by email or username, just return unauthorized and give nothing away of existing user info
                if (currentUser == null)
                {
                    return(Unauthorized("invalid"));
                }

                // Log the user in by password
                var result = await signInManager.PasswordSignInAsync(currentUser, model.Password, model.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    logger.LogInformation("User " + currentUser.Id + " logged in.");

                    // Retrieve roles of user
                    currentUser.Roles = (List <string>) await userManager.GetRolesAsync(currentUser);

                    // Set claims of user
                    List <Claim> claims = new List <Claim>()
                    {
                        new Claim(JwtRegisteredClaimNames.NameId, currentUser.Id.ToString()),
                        new Claim(JwtRegisteredClaimNames.UniqueName, currentUser.UserName),
                        new Claim(JwtRegisteredClaimNames.Email, currentUser.Email),
                        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(CultureInfo.CurrentCulture))
                    };
                    if (!string.IsNullOrEmpty(currentUser.FirstName))
                    {
                        claims.Add(new Claim(JwtRegisteredClaimNames.GivenName, currentUser.FirstName));
                    }
                    if (!string.IsNullOrEmpty(currentUser.LastName))
                    {
                        claims.Add(new Claim(JwtRegisteredClaimNames.FamilyName, currentUser.LastName));
                    }

                    // Add roles as claims
                    foreach (var role in currentUser.Roles)
                    {
                        claims.Add(new Claim(ClaimTypes.Role, role));
                    }

                    // Retrieve player if player type user
                    if (currentUser.PlayerId != null)
                    {
                        currentUser.Player = await playerRepository.GetByIdAsync((Guid)currentUser.PlayerId);
                    }

                    // Authentication successful => Generate jwt token
                    // TODO: This code could be moved to another layer
                    var tokenHandler    = new JwtSecurityTokenHandler();
                    var key             = Encoding.ASCII.GetBytes(configuration.GetSection("Authentication").GetValue <string>("Secret"));
                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                        Subject            = new ClaimsIdentity(claims),
                        Expires            = DateTime.UtcNow.AddMinutes(double.Parse(configuration.GetSection("Authentication").GetValue <string>("TokenExpiresInMinutes"))),
                        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                    };

                    // Return user with token
                    return(Ok(new AuthenticatedVM()
                    {
                        User = mapper.Map <User, UserVM>(currentUser),
                        Token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)),
                        RememberMe = model.RememberMe
                    }));
                }
                //if (result.RequiresTwoFactor)
                //{
                //    logger.LogInformation("Requires two factor.");
                //    return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
                //}
                if (result.IsLockedOut)
                {
                    // INFO: This is possible to split some code
                    //return RedirectToAction(nameof(Lockout));

                    logger.LogWarning("User is locked out.");
                    return(Unauthorized("locked-out"));
                }
                if (result.IsNotAllowed)
                {
                    logger.LogWarning("User is not allowed to login.");
                    return(Unauthorized("not-allowed"));
                }
                else
                {
                    logger.LogWarning("Invalid login attempt.");
                    return(Unauthorized("invalid"));
                }
            }

            // If we got this far, something failed
            return(BadRequest());
        }
        private void SetValidateEmail(UserManager<IdentityUser> manager, 
            UserStore<IdentityUser> store,
            IdentityUser user, 
            string strNewEmail)
        {
            string originalEmail = user.Email;
            var taskUserSet = manager.SetEmailAsync(user.Id, strNewEmail);
            taskUserSet.Wait();
            Assert.IsTrue(taskUserSet.Result.Succeeded, string.Concat(taskUserSet.Result.Errors));

            var taskUser = manager.GetEmailAsync(user.Id);
            taskUser.Wait();
            Assert.AreEqual<string>(strNewEmail, taskUser.Result, "GetEmailAsync: Email not equal");

            if (!string.IsNullOrWhiteSpace(strNewEmail))
            {
                var taskFind = manager.FindByEmailAsync(strNewEmail);
                taskFind.Wait();
                Assert.AreEqual<string>(strNewEmail, taskFind.Result.Email, "FindByEmailAsync: Email not equal");
            }
            else
            {
                //TableQuery query = new TableQuery();
                //query.SelectColumns = new List<string>() { "Id" };
                //query.FilterString = TableQuery.GenerateFilterCondition("Id", QueryComparisons.Equal, user.Id);
                //query.Take(1);
                //var results = store.Context.IndexTable.ExecuteQuery(query);
                //Assert.IsTrue(results.Where(x=> x.RowKey.StartsWith("E_")).Count() == 0, string.Format("Email index not deleted for user {0}", user.Id));
            }
            //Should not find old by old email.
            if (!string.IsNullOrWhiteSpace(originalEmail))
            {
                var taskFind = manager.FindByEmailAsync(originalEmail);
                taskFind.Wait();
                Assert.IsNull(taskFind.Result, "FindByEmailAsync: Old email should not yield a find result.");
            }
        }
        private async Task <bool> IsValidUsernameAndPassword(string username, string password)
        {
            var user = await _usermanager.FindByEmailAsync(username);

            return(await _usermanager.CheckPasswordAsync(user, password));
        }
Example #10
0
        public async Task <AppUserDomain> GetOrCreateUser(HackneyTokenDomain hackneyTokenDomain)
        {
            var user = await _userManager.FindByEmailAsync(hackneyTokenDomain.Email).ConfigureAwait(false);

            switch (user)
            {
            case null:
            {
                var userEntity = new User
                {
                    Email                = hackneyTokenDomain.Email,
                    EmailConfirmed       = false,
                    LockoutEnabled       = false,
                    NormalizedEmail      = hackneyTokenDomain.Email.ToUpperInvariant(),
                    NormalizedUserName   = hackneyTokenDomain.Email.ToUpperInvariant(),
                    PasswordHash         = null,
                    PhoneNumber          = null,
                    PhoneNumberConfirmed = false,
                    TwoFactorEnabled     = false,
                    UserName             = hackneyTokenDomain.Email,
                    Name = hackneyTokenDomain.Name
                };

                var result = await _userManager.CreateAsync(userEntity).ConfigureAwait(false);

                if (result.Succeeded)
                {
                    var defaultRoles = new List <string> {
                        RolesEnum.Broker.GetDisplayName()
                    };
                    var newUserRoles = new List <string>();
                    foreach (var userRole in defaultRoles)
                    {
                        if (await _roleManager.RoleExistsAsync(userRole).ConfigureAwait(false))
                        {
                            newUserRoles.Add(userRole);
                        }
                    }

                    if (newUserRoles.Count > 0)
                    {
                        await _userManager.AddToRolesAsync(userEntity, newUserRoles).ConfigureAwait(false);
                    }

                    return(userEntity?.ToDomain());
                }

                var validationErrorCollection = new ValidationErrorCollection();

                foreach (var error in result.Errors)
                {
                    validationErrorCollection.Add(new ValidationError
                        {
                            Message   = error.Description,
                            ControlID = error.Code,
                            ID        = error.Code
                        });
                }

                throw new ApiException($"User creation failed", (int)StatusCodes.Status400BadRequest,
                                       validationErrorCollection);
            }
            }

            return(user.ToDomain());
        }
Example #11
0
        //Seed Demo User
        public static async Task SeedDemoUsersAsync(UserManager <CustomUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            //Seed Demo Admin User
            var defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Demo",
                LastName       = "Admin",
                EmailConfirmed = true,
                CompanyId      = company2Id
            };

            try
            {
                var user = await userManager.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManager.CreateAsync(defaultUser, "Abc123!");

                    await userManager.AddToRoleAsync(defaultUser, Roles.Admin.ToString());

                    await userManager.AddToRoleAsync(defaultUser, Roles.DemoUser.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Demo Admin User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Demo ProjectManager User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Demo",
                LastName       = "ProjectManager",
                EmailConfirmed = true,
                CompanyId      = company2Id
            };
            try
            {
                var user = await userManager.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManager.CreateAsync(defaultUser, "Abc123!");

                    await userManager.AddToRoleAsync(defaultUser, Roles.ProjectManager.ToString());

                    await userManager.AddToRoleAsync(defaultUser, Roles.DemoUser.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Demo ProjectManager1 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Demo Developer User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Demo",
                LastName       = "Developer",
                EmailConfirmed = true,
                CompanyId      = company2Id
            };
            try
            {
                var user = await userManager.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManager.CreateAsync(defaultUser, "Abc123!");

                    await userManager.AddToRoleAsync(defaultUser, Roles.Developer.ToString());

                    await userManager.AddToRoleAsync(defaultUser, Roles.DemoUser.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Demo Developer1 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Demo Submitter User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Demo",
                LastName       = "Submitter",
                EmailConfirmed = true,
                CompanyId      = company2Id
            };
            try
            {
                var user = await userManager.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManager.CreateAsync(defaultUser, "Abc123!");

                    await userManager.AddToRoleAsync(defaultUser, Roles.Submitter.ToString());

                    await userManager.AddToRoleAsync(defaultUser, Roles.DemoUser.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Demo Submitter User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Demo New User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Demo",
                LastName       = "NewUser",
                EmailConfirmed = true,
                CompanyId      = company2Id
            };
            try
            {
                var user = await userManager.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManager.CreateAsync(defaultUser, "Abc123!");

                    await userManager.AddToRoleAsync(defaultUser, Roles.Submitter.ToString());

                    await userManager.AddToRoleAsync(defaultUser, Roles.DemoUser.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Demo Submitter User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }
        }
Example #12
0
        public async Task SeedAsync()
        {
            try
            {
                if (_env.IsDevelopment())
                {
                    if (_config["Data:IterateDatabase"].ToLower() == "true")
                    {
                        await _ctx.Database.EnsureDeletedAsync();

                        await _ctx.Database.EnsureCreatedAsync();
                    }

                    var admin = await _userManager.FindByEmailAsync(_config["Admin:SuperUser:Email"]);

                    // If no Admin, then we haven't seeded the database
                    if (admin == null)
                    {
                        admin = new CodeCampUser()
                        {
                            UserName       = _config["Admin:SuperUser:Email"],
                            Email          = _config["Admin:SuperUser:Email"],
                            Name           = _config["Admin:SuperUser:Name"],
                            EmailConfirmed = true
                        };

                        // Create Super User
                        if (!(await _userManager.CreateAsync(admin, _config["Admin:SuperUser:TempPassword"])).Succeeded)
                        {
                            throw new InvalidOperationException("Failed to create Super User");
                        }

                        if (!(await _roleManager.CreateAsync(new IdentityRole(Consts.ADMINROLE))).Succeeded)
                        {
                            throw new InvalidOperationException("Failed to create Admin Role");
                        }

                        // Add to Admin Role
                        if (!(await _userManager.AddToRoleAsync(admin, Consts.ADMINROLE)).Succeeded)
                        {
                            throw new InvalidOperationException("Failed to update Super User Role");
                        }
                    }

                    EventInfo[] codeCamps;
                    if (!_ctx.CodeCampEvents.Any())
                    {
                        codeCamps = new EventInfo[]
                        {
                            new EventInfo()
                            {
                                Moniker               = "2017",
                                Name                  = "Atlanta Code Camp 2017",
                                EventDate             = new DateTime(2017, 9, 17),
                                EventLength           = 1,
                                Description           = "The Atlanta Code Camp is awesome! The Atlanta Code Camp is awesome! The Atlanta Code Camp is awesome!",
                                IsDefault             = true,
                                TwitterLink           = "https://twitter.com/atlcodecamp",
                                ContactEmail          = "*****@*****.**",
                                CallForSpeakersOpened = new DateTime(2017, 5, 25),
                                CallForSpeakersClosed = new DateTime(2016, 9, 1),
                                Location              = new EventLocation()
                                {
                                    Facility      = "Kennesaw State University",
                                    Address1      = "1100 S Marietta Pkwy",
                                    Address2      = "",
                                    City          = "Marietta",
                                    StateProvince = "GA",
                                    PostalCode    = "30060",
                                    Country       = "USA",
                                    Link          = ""
                                }
                            },
                            new EventInfo()
                            {
                                Moniker               = "2016",
                                Name                  = "Atlanta Code Camp 2016",
                                EventDate             = new DateTime(2016, 10, 15),
                                EventLength           = 1,
                                Description           = "The Atlanta Code Camp is awesome",
                                IsDefault             = true,
                                TwitterLink           = "https://twitter.com/atlcodecamp",
                                ContactEmail          = "*****@*****.**",
                                CallForSpeakersOpened = new DateTime(2016, 7, 1),
                                CallForSpeakersClosed = new DateTime(2016, 10, 1),
                                Location              = new EventLocation()
                                {
                                    Facility      = "Kennesaw State University",
                                    Address1      = "1100 S Marietta Pkwy",
                                    Address2      = "",
                                    City          = "Marietta",
                                    StateProvince = "GA",
                                    PostalCode    = "30060",
                                    Country       = "USA",
                                    Link          = ""
                                }
                            },
                            new EventInfo()
                            {
                                Moniker               = "2015",
                                Name                  = "Atlanta Code Camp 2015",
                                EventDate             = new DateTime(2015, 10, 24),
                                EventLength           = 1,
                                Description           = "The Atlanta Code Camp is awesome",
                                IsDefault             = false,
                                CallForSpeakersOpened = new DateTime(2015, 8, 1),
                                CallForSpeakersClosed = new DateTime(2015, 10, 1),
                                Location              = new EventLocation()
                                {
                                    Facility      = "Kennesaw State University (Formerly Southern Polytechnic)",
                                    Address1      = "1100 S Marietta Pkwy",
                                    Address2      = "",
                                    City          = "Marietta",
                                    StateProvince = "GA",
                                    PostalCode    = "30060",
                                    Country       = "USA",
                                    Link          = ""
                                }
                            },
                            new EventInfo()
                            {
                                Moniker               = "2014",
                                Name                  = "Atlanta Code Camp 2014",
                                EventDate             = new DateTime(2014, 10, 11),
                                EventLength           = 1,
                                Description           = "The Atlanta Code Camp is awesome",
                                IsDefault             = false,
                                CallForSpeakersOpened = new DateTime(2014, 8, 1),
                                CallForSpeakersClosed = new DateTime(2014, 9, 15),
                                Location              = new EventLocation()
                                {
                                    Facility      = "Southern Polytechnic",
                                    Address1      = "1100 S Marietta Pkwy",
                                    Address2      = "",
                                    City          = "Marietta",
                                    StateProvince = "GA",
                                    PostalCode    = "30060",
                                    Country       = "USA",
                                    Link          = ""
                                }
                            },
                            new EventInfo()
                            {
                                Moniker               = "2013",
                                Name                  = "Atlanta Code Camp 2013",
                                EventDate             = new DateTime(2013, 8, 24),
                                EventLength           = 1,
                                Description           = "The Atlanta Code Camp is awesome",
                                IsDefault             = false,
                                CallForSpeakersOpened = new DateTime(2013, 6, 1),
                                CallForSpeakersClosed = new DateTime(2013, 8, 1),
                                Location              = new EventLocation()
                                {
                                    Facility      = "Southern Polytechnic",
                                    Address1      = "1100 S Marietta Pkwy",
                                    Address2      = "",
                                    City          = "Marietta",
                                    StateProvince = "GA",
                                    PostalCode    = "30060",
                                    Country       = "USA",
                                    Link          = ""
                                }
                            }
                        };

                        _ctx.AddRange(codeCamps);

                        await _ctx.SaveChangesAsync();
                    }
                    else
                    {
                        codeCamps = _ctx.CodeCampEvents.ToArray();
                    }

                    if (!_ctx.Sponsors.Any())
                    {
                        var sponsor = new Sponsor()
                        {
                            Name         = "Wilder Minds",
                            Link         = "http://wilderminds.com",
                            Event        = codeCamps[0],
                            Paid         = true,
                            ImageUrl     = "/img/2016/sponsors/wilder-minds.jpg",
                            SponsorLevel = "Silver"
                        };
                        _ctx.Add(sponsor);

                        sponsor = new Sponsor()
                        {
                            Name         = "Wilder Minds",
                            Link         = "http://wilderminds.com",
                            Event        = codeCamps[1],
                            Paid         = true,
                            ImageUrl     = "/img/2016/sponsors/wilder-minds.jpg",
                            SponsorLevel = "Silver"
                        };
                        _ctx.Add(sponsor);



                        _ctx.AddRange(Add2015Sponsors(codeCamps.Where(s => s.Moniker == "2015").First()));
                        _ctx.AddRange(Add2014Sponsors(codeCamps.Where(s => s.Moniker == "2014").First()));
                        _ctx.AddRange(Add2013Sponsors(codeCamps.Where(s => s.Moniker == "2013").First()));

                        await _ctx.SaveChangesAsync();
                    }

                    if (!_ctx.Speakers.Any())
                    {
                        await Migrate();
                    }
                }
            }
            catch (Exception ex)
            {
                // TODO
                ex.ToString();
            }
        }
Example #13
0
File: Seed.cs Project: 07-donny/CC
        public static void SeedUsers(UserManager <User> userManager,
                                     RoleManager <IdentityRole> roleManager)
        {
            //Create Roles
            if (roleManager.FindByNameAsync("Player").Result == null)
            {
                IdentityRole playerRole = new IdentityRole("Player");
                roleManager.CreateAsync(playerRole).Wait();
            }

            if (roleManager.FindByNameAsync("Moderator").Result == null)
            {
                IdentityRole moderatorRole = new IdentityRole("Moderator");
                roleManager.CreateAsync(moderatorRole).Wait();
            }

            if (roleManager.FindByNameAsync("Admin").Result == null)
            {
                IdentityRole role = new IdentityRole {
                    Name = "Admin"
                };
                roleManager.CreateAsync(role).Wait();
            }


            //Create standard Player user
            if (userManager.FindByEmailAsync("*****@*****.**").Result == null)
            {
                User user = new User
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };

                IdentityResult result = userManager.CreateAsync(user, "Password123!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "Player").Wait();
                }
            }

            //Create standard Moderator user
            if (userManager.FindByEmailAsync("*****@*****.**").Result == null)
            {
                User user = new User
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };

                IdentityResult result = userManager.CreateAsync(user, "Password123!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "Moderator").Wait();
                }
            }

            //Create standard Admin user
            if (userManager.FindByEmailAsync("*****@*****.**").Result == null)
            {
                User user = new User
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };

                IdentityResult result = userManager.CreateAsync(user, "Password123!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "Admin").Wait();
                }
            }
        }
Example #14
0
 public async Task <ApplicationUser> FindByEmail(string userName)
 {
     return(await _userManager.FindByEmailAsync(userName));
 }
Example #15
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var userName = Input.Email;
                if (IsValidEmail(Input.Email))
                {
                    var userCheck = await _userManager.FindByEmailAsync(Input.Email);

                    if (userCheck != null)
                    {
                        userName = userCheck.UserName;
                    }
                }
                var user = await _userManager.FindByNameAsync(userName);

                if (user != null)
                {
                    if (!user.IsActive)
                    {
                        return(RedirectToPage("./Deactivated"));
                    }
                    else if (!user.EmailConfirmed)
                    {
                        _notyf.Error("Email Not Confirmed.");
                        ModelState.AddModelError(string.Empty, "Email Not Confirmed.");
                        return(Page());
                    }
                    else
                    {
                        var result = await _signInManager.PasswordSignInAsync(userName, Input.Password, Input.RememberMe, lockoutOnFailure : false);

                        if (result.Succeeded)
                        {
                            await _mediator.Send(new AddActivityLogCommand()
                            {
                                userId = user.Id, Action = "Logged In"
                            });

                            _logger.LogInformation("User logged in.");
                            _notyf.Success($"Logged in as {userName}.");
                            return(LocalRedirect(returnUrl));
                        }
                        await _mediator.Send(new AddActivityLogCommand()
                        {
                            userId = user.Id, Action = "Log-In Failed"
                        });

                        if (result.RequiresTwoFactor)
                        {
                            return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                        }
                        if (result.IsLockedOut)
                        {
                            _notyf.Warning("User account locked out.");
                            _logger.LogWarning("User account locked out.");
                            return(RedirectToPage("./Lockout"));
                        }
                        else
                        {
                            _notyf.Error("Invalid login attempt.");
                            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                            return(Page());
                        }
                    }
                }
                else
                {
                    _notyf.Error("Email / Username Not Found.");
                    ModelState.AddModelError(string.Empty, "Email / Username Not Found.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        private static void AddEstheticians(UserManager<ApplicationUser> users, RoleManager<ApplicationRole> roles, SMDbContext context)
        {
            var esthUser = users.FindByEmailAsync("*****@*****.**").Result;
            var allServices = context.SpaServices.ToList();

            var esthetician = new Esthetician
            {
                ApplicationUserId = esthUser.Id,
                Services = allServices.OrderBy(x => x.Id).Take(12).ToList(),
                Color = "33cc33"
            };

            context.Estheticians.Add(esthetician);

            var nextUser = users.FindByEmailAsync("*****@*****.**").Result;
            var nextEsth = new Esthetician
            {
                ApplicationUserId = nextUser.Id,
                Services = allServices.ToList(),
                Color = "cc33ff"
            };

            context.Estheticians.Add(nextEsth);

            context.SaveChanges();
        }
Example #17
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                // Require the user to have a confirmed email before they can log on.
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    if (user.RequiresEmailConfirmation && !await _userManager.IsEmailConfirmedAsync(user))
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "You must have a confirmed email to log in.");
                        return(View(model));
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }

                if (!await _userManager.IsLockedOutAsync(user) && await _u2FService.HasDevices(user.Id))
                {
                    if (await _userManager.CheckPasswordAsync(user, model.Password))
                    {
                        LoginWith2faViewModel twoFModel = null;

                        if (user.TwoFactorEnabled)
                        {
                            // we need to do an actual sign in attempt so that 2fa can function in next step
                            await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : true);

                            twoFModel = new LoginWith2faViewModel
                            {
                                RememberMe = model.RememberMe
                            };
                        }

                        return(View("SecondaryLogin", new SecondaryLoginViewModel()
                        {
                            LoginWith2FaViewModel = twoFModel,
                            LoginWithU2FViewModel = await BuildU2FViewModel(model.RememberMe, user)
                        }));
                    }
                    else
                    {
                        var incrementAccessFailedResult = await _userManager.AccessFailedAsync(user);

                        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                        return(View(model));
                    }
                }


                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(RedirectToLocal(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(View("SecondaryLogin", new SecondaryLoginViewModel()
                    {
                        LoginWith2FaViewModel = new LoginWith2faViewModel()
                        {
                            RememberMe = model.RememberMe
                        }
                    }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToAction(nameof(Lockout)));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <IHttpActionResult> Register(dtoRegistration user)
        {
            if (user == null)
            {
                return(BadRequest("Invalid Request"));
            }

            if (string.IsNullOrEmpty(user.Email))
            {
                return(BadRequest("Invalid email address"));
            }

            if (string.IsNullOrEmpty(user.PostalCode))
            {
                return(BadRequest("Invalid post/zip code"));
            }

            if (string.IsNullOrEmpty(user.Telephone))
            {
                return(BadRequest("Invalid telephone number"));
            }

            var userIdentity = UserManager.FindByEmailAsync(user.Email).Result;

            if (userIdentity != null)
            {
                return(BadRequest("A user for that e-mail address already exists. Please enter a different e-mail address."));
            }

            var newUser = new ApplicationUser()
            {
                Email       = user.Email,
                UserName    = user.Email,
                PhoneNumber = user.Telephone
            };

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

            if (result.Succeeded)
            {
                var code = await UserManager.GenerateEmailConfirmationTokenAsync(newUser.Id);

                var callbackUrl = this.Url.Link("Default", new { Controller = "Account", Action = "ConfirmEmail", userId = newUser.Id, code = code });
                await UserManager.SendEmailAsync(newUser.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">Activate Account</a>");

                var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Email));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, newUser.Id));
                AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

                dtoRegistered registered = new dtoRegistered
                {
                    UserName   = user.Email,
                    Token      = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket),
                    IssuedUtc  = ticket.Properties.IssuedUtc,
                    ExpiresUtc = ticket.Properties.ExpiresUtc
                };

                return(Ok(registered));
            }

            var errors = string.Join(",", result.Errors);

            return(BadRequest(errors));
        }
Example #19
0
        /// <summary>
        /// Setting up site.
        /// </summary>
        /// <remarks>
        /// It creates the first user, system roles, assign Administrator role to the user,
        /// core settings, first blog post and blog settings.
        /// </remarks>
        public async Task <IActionResult> OnPostAsync([FromBody] SetupModel model)
        {
            try
            {
                _logger.LogInformation("Fanray Setup Begins");

                var validator = new SetupValidator();
                var valResult = await validator.ValidateAsync(model);

                if (!valResult.IsValid)
                {
                    throw new FanException($"Failed to create blog.", valResult.Errors);
                }

                // first user
                var user = new User
                {
                    UserName    = model.UserName,
                    Email       = model.Email,
                    DisplayName = model.DisplayName
                };

                IdentityResult result = IdentityResult.Success;

                // create user if not found
                var foundUser = await _userManager.FindByEmailAsync(model.Email);

                if (foundUser == null)
                {
                    result = await _userManager.CreateAsync(user, model.Password);
                }
                else // update username
                {
                    foundUser.UserName = model.UserName;
                    await _userManager.UpdateNormalizedUserNameAsync(foundUser);
                }

                // create system roles
                if (result.Succeeded)
                {
                    _logger.LogInformation("{@User} account created.", user);

                    result = await CreateSystemRolesAsync();
                }

                // assign Administrator role to the user
                if (result.Succeeded)
                {
                    // get the actual user object before look up IsInRole
                    user = await _userManager.FindByEmailAsync(user.Email);

                    if (!await _userManager.IsInRoleAsync(user, Role.ADMINISTRATOR_ROLE))
                    {
                        result = await _userManager.AddToRoleAsync(user, Role.ADMINISTRATOR_ROLE);
                    }
                }

                if (result.Succeeded)
                {
                    _logger.LogInformation($"{Role.ADMINISTRATOR_ROLE} role has been assigned to user {@User}.", user);

                    // update or create core settings
                    var settings = await _settingSvc.GetSettingsAsync <CoreSettings>();

                    if (settings != null)
                    {
                        settings.Title      = model.Title;
                        settings.TimeZoneId = model.TimeZoneId;
                        settings.SetupDone  = true;
                        await _settingSvc.UpsertSettingsAsync(settings);
                    }
                    else
                    {
                        await _settingSvc.UpsertSettingsAsync(new CoreSettings
                        {
                            Title      = model.Title,
                            TimeZoneId = model.TimeZoneId,
                            SetupDone  = true,
                        });
                    }
                    _logger.LogInformation("Setup is done, CoreSettings created!");

                    // sign-in user
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation("User has been signed in.");

                    // setup blog
                    await SetupBlogAsync();

                    // setup widgets
                    await SetupThemeAndWidgets();

                    return(new JsonResult(true));
                }

                return(BadRequest(result.Errors.ToList()[0].Description));
            }
            catch (FanException ex)
            {
                return(BadRequest(ex.ValidationFailures[0].ErrorMessage));
            }
        }
Example #20
0
        public async Task <ActionResult <Boolean> > CheckAvailableUserName(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            return(user == null);
        }
        private static void AddUsersToRoles(UserManager<ApplicationUser> users, RoleManager<ApplicationRole> roleManager)
        {
            var admin = users.FindByEmailAsync("*****@*****.**").Result;
            var esthetician = users.FindByEmailAsync("*****@*****.**").Result;

            Task.FromResult(users.AddToRolesAsync(admin, new[] { "Admin", "Esthetician" }).Result);
            Task.FromResult(users.AddToRoleAsync(esthetician, "Esthetician").Result);
        }
        public async Task <IActionResult> CreateDefaultUsers()
        {
            #region Roles

            var rolesDetails = new List <string>
            {
                Constants.Roles.Customer,
                Constants.Roles.Restaurant,
                Constants.Roles.Admin
            };

            foreach (string roleName in rolesDetails)
            {
                if (!await _roleManager.RoleExistsAsync(roleName))
                {
                    await _roleManager.CreateAsync(new IdentityRole(roleName));
                }
            }

            #endregion

            #region Users

            var userDetails = new Dictionary <string, IdentityUser> {
                {
                    Constants.Roles.Customer,
                    new IdentityUser {
                        Email = "*****@*****.**", UserName = "******", EmailConfirmed = true
                    }
                },
                {
                    Constants.Roles.Restaurant,
                    new IdentityUser {
                        Email = "*****@*****.**", UserName = "******", EmailConfirmed = true
                    }
                },
                {
                    Constants.Roles.Admin,
                    new IdentityUser {
                        Email = "*****@*****.**", UserName = "******", EmailConfirmed = true
                    }
                }
            };

            foreach (var details in userDetails)
            {
                var existingUserDetails = await _userManager.FindByEmailAsync(details.Value.Email);

                if (existingUserDetails == null)
                {
                    await _userManager.CreateAsync(details.Value);

                    await _userManager.AddPasswordAsync(details.Value, "Password");

                    await _userManager.AddToRoleAsync(details.Value, details.Key);
                }
            }

            #endregion

            return(Ok("Default User has been created"));
        }
        public async Task Seed()
        {
            var adminRole = new IdentityRole("Administrator");

            // Setup base roles
            if (await _roleManager.FindByNameAsync(adminRole.Name) == null)
            {
                await _roleManager.CreateAsync(adminRole);
            }

            ApplicationUser[] newUsers =
            {
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Joe Taylor", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Gabrielle Manning", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Connor Thomson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Rose Rutherford", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Lily Morrison", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "William McDonald", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Steven Bower", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Lillian Smith", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Brian Gibson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Ella Coleman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Warren Rutherford", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Amelia Hemmings", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Joan White", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Alan Walker", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Warren McGrath", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Fiona Dowd", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Anna Bower", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Benjamin Parr", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Mary May", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Karen Johnston", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Fiona Rees", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Piers Buckland", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Dylan Avery", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Nicholas Duncan", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jonathan Lambert", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Anne Powell", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jan Fisher", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Ryan Newman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Sophie Welch", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Leah Short", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Maria Ince", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Colin Coleman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Evan Martin", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Alexandra Wallace", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Maria Watson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Sam Springer", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Ava Hemmings", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Richard Kerr", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Nicholas Ferguson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jan James", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Richard Brown", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Edward Harris", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Connor Cornish", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Ava Randall", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Fiona Anderson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "James Lambert", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Lisa Hudson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Emily Randall", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Stephen Wilson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Richard Robertson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Emma Ince", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Joan Duncan", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Chloe Vaughan", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Leah Avery", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Evan Hamilton", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Phil Black", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Sebastian Miller", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Caroline McLean", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Mary MacLeod", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Gavin Vance", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Grace Hemmings", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Robert Knox", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Deirdre Randall", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Diane Pullman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Penelope Jones", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jack Springer", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Anthony Johnston", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jacob Sharp", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Anna Henderson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Stephanie North", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Kevin Burgess", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Amy Burgess", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Richard McDonald", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Frank Dyer", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Bella Jones", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Austin Murray", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Kevin Howard", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Alison Parsons", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Alexander Abraham", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Adam Cameron", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Anna Carr", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Samantha Thomson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Dorothy Wallace", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Melanie Sanderson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Dorothy Pullman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Penelope Nash", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Neil Martin", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Tracey Hodges", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Grace Greene", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Emma Walsh", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Julian Alsop", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Robert Graham", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Dorothy Edmunds", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Sophie Randall", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Diana Rutherford", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Maria Ogden", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Owen Glover", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Luke McGrath", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Irene McGrath", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Colin North", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Bernadette Black", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Justin Brown", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Chloe Davies", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Penelope Peake", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Faith Blake", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Simon Thomson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Megan Stewart", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Madeleine Sanderson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Kevin Tucker", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Elizabeth Hodges", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Lauren McGrath", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Michelle Cornish", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Cameron Springer", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Cameron Avery", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Evan Poole", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Leah Black", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Ruth Roberts", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Cameron Abraham", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Dylan Brown", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Joe Vance", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Luke Young", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Abigail Paige", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Carolyn Arnold", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Warren Oliver", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Diana Powell", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Joseph Powell", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Stephen Robertson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Dorothy Hudson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Alexander May", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Victoria Kerr", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Felicity Fraser", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Kylie Chapman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Tim Ferguson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Isaac Bailey", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Sebastian Wallace", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Paul Churchill", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Anna Rutherford", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Sue Martin", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Lisa Young", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Fiona Arnold", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Anne Randall", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Amy Paterson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "David Rampling", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Michael Lyman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Fiona Peters", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Pippa Coleman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Anthony Henderson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Connor Coleman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Lillian Chapman", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jack Cornish", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Benjamin Parsons", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jacob Roberts", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Piers Lambert", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Una Ball", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Liam Martin", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jacob Hill", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Faith Fraser", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Lucas Hamilton", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Thomas Baker", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jack Alsop", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "David Walker", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Max Turner", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Frank Henderson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Virginia Poole", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Wendy Jackson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Joseph Nolan", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Gavin Mackay", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Max Hunter", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Adrian Duncan", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Rebecca Wilkins", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Carol Paige", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Bernadette Greene", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Diane Scott", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Caroline White", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jane Mackenzie", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Connor Peake", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Christian Bower", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Trevor Marshall", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Diane Underwood", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Dan Metcalfe", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Leonard Davidson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Felicity Terry", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Edward Stewart", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Ryan Terry", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Faith May", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Grace Hart", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Joanne Nolan", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Pippa Skinner", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Jonathan Davidson", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Wendy Ellison", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Lauren Dickens", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Cameron Martin", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Sam Glover", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Carol Davies", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Audrey Vaughan", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Yvonne Sharp", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Chloe Vance", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Owen Nash", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Sean Lawrence", UserName = "******"
                },
                new ApplicationUser {
                    Email = "*****@*****.**", FullName = "Keith Hudson", UserName = "******"
                }
            };

            foreach (var user in newUsers)
            {
                user.EmailConfirmed = true;
                var result = await _userManager.CreateAsync(user, "T3mpp@ss!");
            }

            var email = "*****@*****.**";

            if (await _userManager.FindByEmailAsync(email) == null)
            {
                // Seed everything
                var user = new ApplicationUser
                {
                    UserName       = email,
                    Email          = email,
                    EmailConfirmed = true,
                };
                var result = await _userManager.CreateAsync(user, "T3mpp@ss!");

                result = await _userManager.AddToRoleAsync(user, adminRole.Name);



                // Preload interests
                var interests = new[]
                {
                    new Interest {
                        Name = "Drones", Description = "Cool flying robots."
                    },
                    new Interest {
                        Name = "Cyber Security", Description = "Hack the planet."
                    },
                    new Interest {
                        Name = "Paranormal", Description = "ESP Programs."
                    },
                };

                _context.AddRange(
                    new ApplicationUserInterest {
                    ApplicationUser = user, Interest = interests[0]
                },
                    new ApplicationUserInterest {
                    ApplicationUser = user, Interest = interests[2]
                }
                    );

                _context.AddRange(interests);
            }



            _context.SaveChanges();
        }
Example #24
0
        //Seed Default User
        public static async Task SeedDefaultUserAsync(UserManager <CustomUser> userManagerSvc, RoleManager <IdentityRole> roleManager)
        {
            //create your self as a user

            var defaultUser = new CustomUser()
            {
                Email          = "*****@*****.**",
                UserName       = "******",
                FirstName      = "Lan",
                LastName       = "Le",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };

            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.Admin.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***************  ERROR  **************");
                Debug.WriteLine("Error Seeding Default Admin");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("*****************************");
                throw;
            }

            //Seed Default ProjectManager1 User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Henry",
                LastName       = "McCoy",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };
            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.ProjectManager.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Default ProjectManager1 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Default ProjectManager2 User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Peter",
                LastName       = "Quill",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };
            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.ProjectManager.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Default ProjectManager2 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Default Developer1 User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Steve",
                LastName       = "Rogers",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };
            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.Developer.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Default Developer1 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Default Developer2 User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "James",
                LastName       = "Howlett",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };
            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.Developer.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Default Developer2 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Default Developer3 User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Natasha",
                LastName       = "Romanova",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };
            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.Developer.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Default Developer3 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Default Developer4 User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Carol",
                LastName       = "Danvers",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };
            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.Developer.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Default Developer4 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Default Developer5 User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Tony",
                LastName       = "Stark",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };
            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.Developer.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Default Developer5 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Default Submitter1 User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Scott",
                LastName       = "Summers",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };
            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.Submitter.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Default Submitter1 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }


            //Seed Default Submitter2 User
            defaultUser = new CustomUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                FirstName      = "Sue",
                LastName       = "Storm",
                EmailConfirmed = true,
                CompanyId      = company1Id
            };
            try
            {
                var user = await userManagerSvc.FindByEmailAsync(defaultUser.Email);

                if (user == null)
                {
                    await userManagerSvc.CreateAsync(defaultUser, "Abc123!");

                    await userManagerSvc.AddToRoleAsync(defaultUser, Roles.Submitter.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("*************  ERROR  *************");
                Debug.WriteLine("Error Seeding Default Submitter2 User.");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***********************************");
                throw;
            }
        }
Example #25
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            var emailExists = await _userManager.FindByEmailAsync(Input.Email);

            if (emailExists != null)
            {
                ModelState.AddModelError(string.Empty, "Not valid. Please enter a valid email address.");
                return(Page());
            }
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    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 code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

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

                    var body = $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>. <br />If you did not sign up for this website, please DO NOT confirm your email, instead please notify us by replying to this email so any security breach can be investigated.";

                    string mailText = EmailHelper.BuildTemplate(_templatesPath, "IdentityTemplate.html");
                    mailText = mailText.Replace("[username]", user.UserName).Replace("[body]", body);

                    await _emailService.SendAsync(user.Email, "Confirm your email for germistry aka Krystal Ruwoldt's Portfolio and Blog", mailText, true);

                    string notifyMailText = EmailHelper.BuildTemplate(_templatesPath, "UserRegisterTemplate.html");
                    notifyMailText = notifyMailText.Replace("[username]", user.UserName).Replace("[registerType]", "locally");
                    await _emailService.SendAsync("*****@*****.**", "New Local User Registered", notifyMailText, true);

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

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

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task <IActionResult> IsUserWithEmailExist([FromBody] string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            return(Ok(user != null));
        }
Example #27
0
        public async Task <LoginResultDTO> LoginAsync(string email, string password, bool rememberMe)
        {
            string token = "";

            ApplicationUser user = await _userManager.FindByEmailAsync(email);

            if (user != null)
            {
                var result = await _signInManager.PasswordSignInAsync(email, password, rememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    string secret = _appSettings.Secret;
                    token = IdentityUtil.generateJwtToken(user, secret);

                    UserSignInResultDTO customerResult = new UserSignInResultDTO
                    {
                        firstname = user.FirstName,
                        lastname  = user.LastName,
                        email     = user.Email,
                        phone     = user.PhoneNumber,
                        token     = token
                    };

                    LoginResultDTO loginResultDTO = new LoginResultDTO
                    {
                        Status           = "success",
                        ResponseCode     = "00",
                        ResponseMessage  = "Sign in Successfully",
                        UserSignInResult = customerResult,
                        ErrorList        = null
                    };

                    return(loginResultDTO);
                }
                else
                {
                    LoginResultDTO loginResultDTO = new LoginResultDTO
                    {
                        Status           = "fail",
                        ResponseCode     = "01",
                        ResponseMessage  = "Invalid Credentials",
                        UserSignInResult = null,
                        ErrorList        = null
                    };

                    return(loginResultDTO);
                }
            }
            else
            {
                LoginResultDTO loginResultDTO = new LoginResultDTO
                {
                    Status           = "fail",
                    ResponseCode     = "01",
                    ResponseMessage  = "User does not exist",
                    UserSignInResult = null,
                    ErrorList        = null
                };

                return(loginResultDTO);
            }
        }
 public async Task <Voter> GetVoterByEmailAsync(string email)
 {
     return(await _userManager.FindByEmailAsync(email));
 }
Example #29
0
        private async Task <string> GetUserId()
        {
            var user = await _userManager.FindByEmailAsync(User.FindFirst(ClaimTypes.Email).Value);

            return(user.Id);
        }
Example #30
0
 private async Task <User> FindUserByEmail(string email)
 {
     return(await _userManager.FindByEmailAsync(email));
 }
Example #31
0
        public async Task <OmbiIdentityResult> SubmitResetPassword([FromBody] SubmitPasswordReset email)
        {
            // Check if account exists
            var user = await UserManager.FindByEmailAsync(email.Email);

            var defaultMessage = new OmbiIdentityResult
            {
                Successful = true,
                Errors     = new List <string> {
                    "If this account exists you should recieve a password reset link."
                }
            };

            if (user == null)
            {
                return(defaultMessage);
            }


            var customizationSettings = await CustomizationSettings.GetSettingsAsync();

            var appName = (string.IsNullOrEmpty(customizationSettings.ApplicationName)
                ? "Ombi"
                : customizationSettings.ApplicationName);

            var emailSettings = await EmailSettings.GetSettingsAsync();

            customizationSettings.AddToUrl("/token?token=");
            var url = customizationSettings.ApplicationUrl;

            if (user.UserType == UserType.PlexUser)
            {
                await EmailProvider.SendAdHoc(new NotificationMessage
                {
                    To      = user.Email,
                    Subject = $"{appName} Password Reset",
                    Message =
                        $"You recently made a request to reset your {appName} account. Please click the link below to complete the process.<br/><br/>" +
                        $"<a href=\"https://www.plex.tv/sign-in/password-reset/\"> Reset </a>"
                }, emailSettings);
            }
            else if (user.UserType == UserType.EmbyUser && user.IsEmbyConnect)
            {
                await EmailProvider.SendAdHoc(new NotificationMessage
                {
                    To      = user.Email,
                    Subject = $"{appName} Password Reset",
                    Message =
                        $"You recently made a request to reset your {appName} account.<br/><br/>" +
                        $"To reset your password you need to go to <a href=\"https://emby.media/community/index.php\">Emby.Media</a> and then click on your Username > Edit Profile > Email and Password"
                }, emailSettings);
            }
            else
            {
                // We have the user
                var token = await UserManager.GeneratePasswordResetTokenAsync(user);

                var encodedToken = WebUtility.UrlEncode(token);

                await EmailProvider.SendAdHoc(new NotificationMessage
                {
                    To      = user.Email,
                    Subject = $"{appName} Password Reset",
                    Message =
                        $"You recently made a request to reset your {appName} account. Please click the link below to complete the process.<br/><br/>" +
                        $"<a href=\"{url}{encodedToken}\"> Reset </a>"
                }, emailSettings);
            }

            return(defaultMessage);
        }
Example #32
0
        public async Task <IActionResult> CreateStudentForm(Student student)
        {
            if (ModelState.IsValid)
            {
                AppUser user = new AppUser
                {
                    UserName = student.FirstName,
                    Email    = student.Email
                };
                IdentityResult result
                    = await userManager.CreateAsync(user, student.Password);

                if (result.Succeeded)
                {
                    AppUser savedUser = await userManager.FindByEmailAsync(user.Email);

                    student.StudentUser = savedUser;
                    if (student.Foto != null)
                    {
                        if (student.Foto.Length > 0)
                        {
                            byte[] p1 = null;
                            using (var fs1 = student.Foto.OpenReadStream())
                                using (var ms1 = new MemoryStream())
                                {
                                    fs1.CopyTo(ms1);
                                    p1 = ms1.ToArray();
                                }
                            student.Avatar = p1;
                        }
                    }
                    context.Add(student);
                    IdentityResult identityResult =
                        await userManager.AddToRoleAsync(savedUser, "student");

                    if (!identityResult.Succeeded)
                    {
                        AddErrorsFromResult(identityResult);
                    }
                    context.SaveChanges();
                    return(PartialView("SuccessRegistration"));
                }
                else
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
                }
            }

            ViewBag.User           = "******";
            (Student, Client)users = (student, new Client());
            if (Request.IsAjaxRequest())
            {
                return(PartialView("CreateForm", users));
            }
            else
            {
                return(View("CreateCommonForm", users));
            }
        }
Example #33
0
        private async Task Seed(IUnitOfWork uow  , UserManager<ApplicationUser> usrMan, RoleManager<IdentityRole> _RoleManager)
        {

            var email = "*****@*****.**";
            var RoleName = "CustomerAdmin";
            var role = await _RoleManager.FindByNameAsync(RoleName);
            if (role == null)
            {
                role = new IdentityRole { Name = RoleName };
                await _RoleManager.CreateAsync(role);
            }

        RoleName = "superadmin";
            role = await _RoleManager.FindByNameAsync( RoleName );
            if ( role == null)
            {
                role = new IdentityRole { Name = "SuperAdmin" };
                await _RoleManager.CreateAsync(role);
            }
            
            var appUser = await usrMan.FindByEmailAsync(email);
            if (appUser != null)
            {
                var result = await usrMan.DeleteAsync(appUser);
            }
            else 
            {
                appUser = new ApplicationUser() { UserName = email, Email = email };
                var result2 = await usrMan.CreateAsync(appUser, "Shafiro2,");
                if (result2.Succeeded)
                {
                    await usrMan.AddToRoleAsync(appUser,  RoleName ); 
                    var hrmUser = new User()
                    {
                        UserID = "7310209296",
                        FirstName = "Gabriel",
                        LastName = "Tekin",
                        UserName = "******",
                        UserCode = "tekgab",
                        PhoneNumber = "0702385537"
                    };
                    if (uow.UserRepository.GetEagerLoad( w => w.UserID.Equals( hrmUser.UserID, StringComparison.OrdinalIgnoreCase )).FirstOrDefault()   == null )
                    {
                        uow.UserRepository.Insert(hrmUser);
                        uow.Save();
                    }
                    
                }
                else
                {
                    var code = result2.Errors.FirstOrDefault().Code;
                }
            }

            } // method seed 
Example #34
0
 public async Task <ActionResult <bool> > CheckEmailExistsAsync([FromQuery] string email)
 {
     return(await _userManager.FindByEmailAsync(email) != null);
 }
        public async Task EnsureSeedDataAsync()
        {
            if (await _userManager.FindByEmailAsync("*****@*****.**") == null)
            {
                // Add the user.
                var newUser = new WorldUser()
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };

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

            if (!_context.Trips.Any())
            {
                // Add new data
                var usTrip = new Trip()
                {
                    Name     = "US Trip",
                    Created  = DateTime.UtcNow,
                    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()
                {
                    Name     = "World Trip",
                    Created  = DateTime.UtcNow,
                    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);

                _context.SaveChanges();
            }
        }
Example #36
0
 private static async Task <ApplicationUser> GetAdminUser(UserManager <ApplicationUser> userManager, string email)
 {
     return(await userManager.FindByEmailAsync(email));
 }
 //This Method will return the User by using the Email
 public async Task <ApplicationUser> GetUserByEmailAsync(string email)
 {
     return(await _userManager.FindByEmailAsync(email));
 }
 public async Task<JsonData> Reset(UserViewModel model)
 {
     try
     {
         var db = new DataContext();
         var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
         userMan.UserValidator = new UserValidator<MyUser>(userMan)
         {
             AllowOnlyAlphanumericUserNames =
                 false
         };
         var user = await userMan.FindByEmailAsync(model.Email);
         if (user == null) throw new Exception("please check the email address");
         //todo: generate a unique password and email it to the user
         var newPassword = user.FullName.Substring(2, 3) + user.PasswordHash.Substring(0, 5);
         var result = await userMan.RemovePasswordAsync(user.Id);
         if (!result.Succeeded) throw new Exception(string.Join(", ", result.Errors));
         var result2 = await userMan.AddPasswordAsync(user.Id, newPassword);
         if (!result2.Succeeded) throw new Exception(string.Join(", ", result2.Errors));
         //todo: Email the new password to the user
         return DataHelpers.ReturnJsonData(null, true, "A new password has been emailed to your email address");
     }
     catch (Exception e)
     {
         return DataHelpers.ExceptionProcessor(e);
     }
 }
Example #39
0
        ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl      = returnUrl,
                ExternalLogins =
                    (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState
                .AddModelError(string.Empty, $"Error from external provider: {remoteError}");

                return(View("Login", loginViewModel));
            }

            // Get the login information about the user from the external login provider
            var info = await signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState
                .AddModelError(string.Empty, "Error loading external login information.");

                return(View("Login", loginViewModel));
            }

            // If the user already has a login (i.e if there is a record in AspNetUserLogins
            // table) then sign-in the user with this external login provider
            var signInResult = await signInManager.ExternalLoginSignInAsync(info.LoginProvider,
                                                                            info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                return(LocalRedirect(returnUrl));
            }
            // If there is no record in AspNetUserLogins table, the user may not have
            // a local account
            else
            {
                // Get the email claim value
                var email = info.Principal.FindFirstValue(ClaimTypes.Email);

                if (email != null)
                {
                    // Create a new user without password if we do not have a user already
                    var user = await userManager.FindByEmailAsync(email);

                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
                            Email    = info.Principal.FindFirstValue(ClaimTypes.Email)
                        };

                        await userManager.CreateAsync(user);
                    }

                    // Add a login (i.e insert a row for the user in AspNetUserLogins table)
                    await userManager.AddLoginAsync(user, info);

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

                    return(LocalRedirect(returnUrl));
                }

                // If we cannot find the user email we cannot continue
                ViewBag.ErrorTitle   = $"Email claim not received from: {info.LoginProvider}";
                ViewBag.ErrorMessage = "Please contact support on [email protected]";

                return(View("Error"));
            }
        }
Example #40
0
        public async Task <UserManagerResponse> LoginEmployeeAsync(LoginEmployeeViewModel model)
        {
            var user = await _userManger.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(new UserManagerResponse
                {
                    Message = "There is no user with that Email address",
                    IsSuccess = false,
                });
            }

            var result = await _userManger.CheckPasswordAsync(user, model.Password);

            if (!result)
            {
                return new UserManagerResponse
                       {
                           Message   = "Invalid password",
                           IsSuccess = false,
                       }
            }
            ;

            var userRole = _context.UserRoles.SingleOrDefault(ur => ur.UserId == user.Id);
            var role     = _context.Roles.FirstOrDefault(x => x.Id == userRole.RoleId);

            if (role.Name != "Admin" && role.Name != "Employee")
            {
                return(new UserManagerResponse
                {
                    Message = "Unauthorized",
                    IsSuccess = false,
                });
            }

            var claims = new[]
            {
                new Claim("Email", model.Email),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim("Role", role.Name)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["AuthSettings:Key"]));

            var token = new JwtSecurityToken(
                issuer: _configuration["AuthSettings:Issuer"],
                audience: _configuration["AuthSettings:Audience"],
                claims: claims,
                expires: DateTime.Now.AddDays(30),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            string tokenAsString = new JwtSecurityTokenHandler().WriteToken(token);

            return(new UserManagerResponse
            {
                Message = tokenAsString,
                IsSuccess = true,
                ExpireDate = token.ValidTo
            });
        }

        /**
         * public async Task<UserManagerResponse> ConfirmEmailAsync(string userId, string token)
         * {
         *  var user = await _userManger.FindByIdAsync(userId);
         *  if (user == null)
         *      return new UserManagerResponse
         *      {
         *          IsSuccess = false,
         *          Message = "User not found"
         *      };
         *
         *  var decodedToken = WebEncoders.Base64UrlDecode(token);
         *  string normalToken = Encoding.UTF8.GetString(decodedToken);
         *
         *  var result = await _userManger.ConfirmEmailAsync(user, normalToken);
         *
         *  if (result.Succeeded)
         *      return new UserManagerResponse
         *      {
         *          Message = "Email confirmed successfully!",
         *          IsSuccess = true,
         *      };
         *
         *  return new UserManagerResponse
         *  {
         *      IsSuccess = false,
         *      Message = "Email did not confirm",
         *      Errors = result.Errors.Select(e => e.Description)
         *  };
         * }
         **/
        /**
         * public async Task<UserManagerResponse> ForgetPasswordAsync(string email)
         * {
         *  var user = await _userManger.FindByEmailAsync(email);
         *  if (user == null)
         *      return new UserManagerResponse
         *      {
         *          IsSuccess = false,
         *          Message = "No user associated with email",
         *      };
         *
         *  var token = await _userManger.GeneratePasswordResetTokenAsync(user);
         *  var encodedToken = Encoding.UTF8.GetBytes(token);
         *  var validToken = WebEncoders.Base64UrlEncode(encodedToken);
         *
         *  string url = $"{_configuration["AppUrl"]}/ResetPassword?email={email}&token={validToken}";
         *
         *  await _mailService.SendEmailAsync(email, "Reset Password", "<h1>Follow the instructions to reset your password</h1>" +
         *      $"<p>To reset your password <a href='{url}'>Click here</a></p>");
         *
         *  return new UserManagerResponse
         *  {
         *      IsSuccess = true,
         *      Message = "Reset password URL has been sent to the email successfully!"
         *  };
         * }
         **/
        /**
         * public async Task<UserManagerResponse> ResetPasswordAsync(ResetPasswordViewModel model)
         * {
         *  var user = await _userManger.FindByEmailAsync(model.Email);
         *  if (user == null)
         *      return new UserManagerResponse
         *      {
         *          IsSuccess = false,
         *          Message = "No user associated with email",
         *      };
         *
         *  if (model.NewPassword != model.ConfirmPassword)
         *      return new UserManagerResponse
         *      {
         *          IsSuccess = false,
         *          Message = "Password doesn't match its confirmation",
         *      };
         *
         *  var decodedToken = WebEncoders.Base64UrlDecode(model.Token);
         *  string normalToken = Encoding.UTF8.GetString(decodedToken);
         *
         *  var result = await _userManger.ResetPasswordAsync(user, normalToken, model.NewPassword);
         *
         *  if (result.Succeeded)
         *      return new UserManagerResponse
         *      {
         *          Message = "Password has been reset successfully!",
         *          IsSuccess = true,
         *      };
         *
         *  return new UserManagerResponse
         *  {
         *      Message = "Something went wrong",
         *      IsSuccess = false,
         *      Errors = result.Errors.Select(e => e.Description),
         *  };
         * }
         **/
    }
Example #41
0
        public async Task <bool> SeedAsync()
        {
            _ctx.Database.EnsureCreated();

            #region Vars
            const string   userEmail = V_Constants.USER_EMAIL_DEFAULT;
            const string   userName  = V_Constants.USER_NAME_DEFAULT;
            UserModel      root;
            IdentityResult result;
            #endregion


            await AddRoles();

            #region root
            root = await _manager.FindByEmailAsync(userEmail);

            if (null == root)
            {
                root = new UserModel()
                {
                    FirstName = V_Constants.USER_FIRSTNAME_DEFAULT,
                    LastName  = V_Constants.USER_LASTNAME_DEFAULT,
                    Email     = userEmail,
                    UserName  = userName
                };
                result = await _manager.CreateAsync(root, V_Constants.DEFAULT_PASS);

                if (IdentityResult.Success == result)
                {
                    await _manager.AddToRoleAsync(root, V_Constants.USER_ROL_ROOT);
                }
            }
            #endregion

            #region Cities
            if (_ctx.City.Count() == 0)
            {
                List <City> cities = new List <City>()
                {
                    new City()
                    {
                        Name = "La Paz, Baja California Sur, México"
                    },
                    new City()
                    {
                        Name = "Los Cabos, Baja California Sur, México"
                    },
                    new City()
                    {
                        Name = "Campeche, Campeche, México"
                    },
                    new City()
                    {
                        Name = "Ciudad del Carmen, Campeche, México"
                    },
                    new City()
                    {
                        Name = "Saltillo, Coahuila de Zaragoza, México"
                    },
                    new City()
                    {
                        Name = "Monclova-Frontera, Coahuila de Zaragoza, México"
                    },
                    new City()
                    {
                        Name = "La Laguna, Coahuila de Zaragoza, México"
                    },
                    new City()
                    {
                        Name = "Piedras Negras, Coahuila de Zaragoza, México"
                    },
                    new City()
                    {
                        Name = "Tecomán, Colima, México"
                    },
                    new City()
                    {
                        Name = "Colima-Villa de Álvarez, Colima, México"
                    },
                    new City()
                    {
                        Name = "Manzanillo, Colima, México"
                    },
                    new City()
                    {
                        Name = "Tepic, Nayarit, México"
                    },
                    new City()
                    {
                        Name = "Tula, Hidalgo, México"
                    },
                    new City()
                    {
                        Name = "Acapulco, Guerrero, México"
                    },
                    new City()
                    {
                        Name = "Cuernavaca	Morelos, México"
                    },
                    new City()
                    {
                        Name = "Tehuantepec-Salina Cruz, Oaxaca, México"
                    }
                };
                await _ctx.City.AddRangeAsync(cities);

                await _ctx.SaveChangesAsync();
            }
            #endregion
            return(true);
        }