コード例 #1
0
        protected override void Seed(ApplicationDbContext context)
        {
            using (var roleStore = new RoleStore <AppRole, Guid, AppUserRole>(context))
                using (var roleManager = new RoleManager <AppRole, Guid>(roleStore))
                    using (var userManager = new AppUserManager(new AppUserStore(context)))
                    {
                        if (userManager.Users.Count() == 0)
                        {
                            var             email = System.Configuration.ConfigurationManager.AppSettings["DefaultUser:Email"];
                            ApplicationUser user;
                            if (userManager.FindByEmail(email) == null)
                            {
                                user = new ApplicationUser
                                {
                                    UserName       = email,
                                    Email          = email,
                                    FirstName      = System.Configuration.ConfigurationManager.AppSettings["DefaultUser:FirstName"],
                                    LastName       = System.Configuration.ConfigurationManager.AppSettings["DefaultUser:LastName"],
                                    EmailConfirmed = true
                                };
                                userManager.Create(user, System.Configuration.ConfigurationManager.AppSettings["DefaultUser:Password"]);
                            }

                            user = userManager.FindByEmail(email);
                            foreach (var role in Enum.GetNames(typeof(Roles)))
                            {
                                if (!roleManager.RoleExists(role.ToLower()))
                                {
                                    roleManager.Create(new AppRole()
                                    {
                                        Name = role, Id = Guid.NewGuid()
                                    });
                                }

                                if (!userManager.IsInRole(user.Id, role))
                                {
                                    userManager.AddToRole(user.Id, role);
                                }
                            }
                        }

                        if (context.Settings.SingleOrDefault() == null)
                        {
                            var settings = new Settings();

                            context.Entry(settings).State = EntityState.Added;

                            context.SaveChanges();
                        }
                    }
        }
コード例 #2
0
        public void UpdateUser(UserDTO user)
        {
            var userManager = new AppUserManager(new AppUserStore(new AppDbContext()));
            var updatedUser = Mapping.Mapper.Map <AppUser>(user);

            using (var context = new AppDbContext())
            {
                var oldUser = userManager.FindByEmail(user.Email);
                if (string.IsNullOrEmpty(updatedUser.PasswordHash))
                {
                    updatedUser.PasswordHash = oldUser.PasswordHash;
                }
                if (string.IsNullOrEmpty(updatedUser.Code))
                {
                    updatedUser.Code = oldUser.Code;
                }
                if (string.IsNullOrEmpty(updatedUser.SecurityStamp))
                {
                    updatedUser.SecurityStamp = oldUser.SecurityStamp;
                }



                context.Entry(updatedUser).State = EntityState.Modified;

                context.SaveChanges();
            }
        }
コード例 #3
0
        public ActionResult Login(LoginViewModel loginVM, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = AppUserManager.FindByEmail(loginVM.Email);
                if (user != null)
                {
                    var signInStatus = SignInManager.PasswordSignIn(loginVM.Email, loginVM.Password, loginVM.RememberMe, false);
                    switch (signInStatus)
                    {
                    case SignInStatus.Success:
                        return(RedirectToLocal(returnUrl));

                    case SignInStatus.LockedOut:
                        return(View("Lockout"));

                    case SignInStatus.RequiresVerification:
                        return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = loginVM.RememberMe }));

                    case SignInStatus.Failure:
                    default:
                        ModelState.AddModelError("", "Invalid login attempt.");
                        return(View(loginVM));
                    }
                }
            }
            //login has failed, if we reach here.
            ModelState.AddModelError("", "Invalid username or password");
            return(View(loginVM));
        }
コード例 #4
0
        public void CreateActivity(Activity activity, AppUser currentUser)
        {
            AppUserManager userMgr = new AppUserManager(new UserStore <AppUser>(context));
            AppUser        user    = userMgr.FindByEmail(currentUser.Email);

            activity.ActivityCreator = user;
            activity.ActivityId      = new System.Guid();
            context.Activities.Add(activity);
            context.SaveChanges();
        }
コード例 #5
0
        public ActionResult UpdateUser(UpdateViewModel model)
        {
            AppUserManager         userManager = HttpContext.GetOwinContext().GetUserManager <AppUserManager>();
            IAuthenticationManager authManager = HttpContext.GetOwinContext().Authentication;

            if (ModelState.IsValid)
            {
                bool validation = repository.isValidUser(model.Email, secureService.Encryptor(model.oldPassword));
                if (validation)
                {
                    if (!model.Email.ToLower().Contains("admin"))
                    {
                        ClaimsPrincipal identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
                        userManager.RemoveFromRole(userManager.FindByEmail(model.Email).Id, identity.Claims.Where(c => c.Type == ClaimTypes.Role).Select(r => r.Value).SingleOrDefault());
                        userManager.AddToRole(userManager.FindByEmail(model.Email).Id, model.Role);
                        Request.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                        SetClaimsIdentity(model.Username, model.Email, model.Role);
                    }
                    repository.updateUser(model.Email, model.Username, secureService.Encryptor(model.newPassword));
                    if (model.Email.ToLower().Contains("admin"))
                    {
                        ViewBag.Role = "Admin";
                        SetClaimsIdentity(model.Username, model.Email, "Admin");
                    }
                    else
                    {
                        SetClaimsIdentity(model.Username, model.Email, repository.getUserRoleName(model.Email));
                    }
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Wrong data");
                }
            }
            ViewBag.Roles = repository.getRoleNames();
            ViewBag.Email = repository.getEmailByUsername(User.Identity.Name);
            return(View(model));
        }
コード例 #6
0
 public void Commit(Activity activity, AppUser currentUser)
 {
     if (activity.ActivityId != null)
     {
         AppUserManager userMgr = new AppUserManager(new UserStore <AppUser>(context));
         AppUser        user    = userMgr.FindByEmail(currentUser.Email);
         Activity       dbEntry = context.Activities.Find(activity.ActivityId);
         if (dbEntry != null)
         {
             dbEntry.IsCommited        = activity.IsCommited;
             dbEntry.CommitDescription = activity.CommitDescription;
             dbEntry.CommitCreator     = user;
         }
     }
     context.SaveChanges();
 }
コード例 #7
0
        // TODO: Apply throttling
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordReq forgotPasswordDto)
        {
            var user = AppUserManager.FindByEmail(forgotPasswordDto.Email);

            if (user == null || !(AppUserManager.IsEmailConfirmed(user.Id)))
            {
                // Don't reveal that the user does not exist or is not confirmed
                return(BadRequest());
            }

            var message = await SendForgotPasswordEmail(user);

            var response = new BaseResponseDto();

            response.Message = message;
            return(Ok(response));
        }
コード例 #8
0
        public ActionResult Register(RegisterViewModel model)
        {
            AppUserManager         userManager = HttpContext.GetOwinContext().GetUserManager <AppUserManager>();
            IAuthenticationManager authManager = HttpContext.GetOwinContext().Authentication;

            if (ModelState.IsValid)
            {
                bool validation = repository.checkUserByEmail(model.Email);
                if (!validation)
                {
                    AppUser user = new AppUser()
                    {
                        UserName     = model.Email.Split('@')[0],
                        Email        = model.Email,
                        PasswordHash = secureService.Encryptor(model.Password),
                    };
                    repository.addUser(user);
                    validation = repository.isValidUser(model.Email, secureService.Encryptor(model.Password));
                    if (model.Role != "Admin")
                    {
                        userManager.AddToRole(userManager.FindByEmail(model.Email).Id, model.Role);
                    }
                    if (validation)
                    {
                        if (model.Email.ToLower().Contains("admin"))
                        {
                            SetClaimsIdentity(model.Email.Split('@')[0], model.Email, "Admin");
                        }
                        else
                        {
                            SetClaimsIdentity(model.Email.Split('@')[0], model.Email, model.Role);
                        }
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "User with the same Email already exists");
                }
            }
            ViewBag.Roles = repository.getRoleNames();
            return(View(model));
        }
コード例 #9
0
        // TODO: Apply throttling
        public IHttpActionResult ResetPassword(ResetPasswordReq resetPasswordDto)
        {
            var user = AppUserManager.FindByEmail(resetPasswordDto.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(BadRequest());
            }
            var token          = HttpUtility.UrlDecode(resetPasswordDto.PasswordResetToken);
            var identityResult = AppUserManager.ResetPassword(user.Id, token, resetPasswordDto.NewPassword);

            if (identityResult.Succeeded)
            {
                var response = new BaseResponseDto();
                response.Message = Responses.ResetPasswordResponseMessage;
                return(Ok(response));
            }

            return(BadRequestWithIdentityErrors(identityResult));
        }
コード例 #10
0
        public ClaimsIdentity Login(string email, string password)
        {
            var userManager = new AppUserManager(new AppUserStore(new AppDbContext()));

            try
            {
                var wantedUser = userManager.FindByEmail(email);

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

                var user = userManager.Find(wantedUser.UserName, password);

                return(user == null ? null : userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie));
            }
            catch
            {
                return(null);
            }
        }
        public static void Seed(AppDbContext dbContext)
        {
            var companyPeekClopenburg = new Company
            {
                Name = "Peek & Clopenburg"
            };

            var companyZara = new Company
            {
                Name = "Zara"
            };

            dbContext.Companies.AddOrUpdate(x => x.Name, companyPeekClopenburg, companyZara);
            dbContext.SaveChanges();

//            var user = new User
//            {
//                Email = DbConstants.DefaultAdministratorUser.Email,
//                UserName = DbConstants.DefaultAdministratorUser.Email,
//                LastName = DbConstants.DefaultAdministratorUser.LastName,
//                FirstName = DbConstants.DefaultAdministratorUser.FirstName,
//                PhoneNumber = DbConstants.DefaultAdministratorUser.PhoneNo,
//                AccessFailedCount = 0,
//                EmailConfirmed = true,
//                IsDisabled = false,
//                LockoutEnabled = true,
//                TwoFactorEnabled = false,
//                PhoneNumberConfirmed = true,
//            };

            var dummyUsers = new[]
            {
                new User
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    LastName             = "Zainescu",
                    FirstName            = "Alexandru",
                    AccessFailedCount    = 0,
                    EmailConfirmed       = true,
                    IsDisabled           = false,
                    LockoutEnabled       = true,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = true,
                    CompanyId            = companyPeekClopenburg.Id
                },
                new User
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    LastName             = "Dinu",
                    FirstName            = "Vlad",
                    AccessFailedCount    = 0,
                    EmailConfirmed       = true,
                    IsDisabled           = false,
                    LockoutEnabled       = true,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = true,
                    CompanyId            = companyPeekClopenburg.Id
                },
                new User
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    LastName             = "Balazsfi",
                    FirstName            = "Alexandru",
                    AccessFailedCount    = 0,
                    EmailConfirmed       = true,
                    IsDisabled           = false,
                    LockoutEnabled       = true,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = true,
                    CompanyId            = companyPeekClopenburg.Id
                },
                new User
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    LastName             = "Purdila",
                    FirstName            = "Alexandru",
                    AccessFailedCount    = 0,
                    EmailConfirmed       = true,
                    IsDisabled           = false,
                    LockoutEnabled       = true,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = true,
                    CompanyId            = companyZara.Id
                },
                new User
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    LastName             = "Ivanciu",
                    FirstName            = "Mihai",
                    AccessFailedCount    = 0,
                    EmailConfirmed       = true,
                    IsDisabled           = false,
                    LockoutEnabled       = true,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = true,
                    CompanyId            = companyZara.Id
                },
                new User
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    LastName             = "Zdurlan",
                    FirstName            = "Alin",
                    AccessFailedCount    = 0,
                    EmailConfirmed       = true,
                    IsDisabled           = false,
                    LockoutEnabled       = true,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = true,
                    CompanyId            = companyZara.Id
                },
            };

            using (var roleManager = new AppRoleManager(new AppRoleStore(dbContext)
            {
                DisposeContext = false
            }))
            {
                foreach (var roleName in DbConstants.Roles.All.Select(x => x.Name))
                {
                    if (roleManager.RoleExists(roleName) == false)
                    {
                        roleManager.Create(new Role {
                            Name = roleName
                        });
                    }
                }
            }
            dbContext.SaveChanges();

            var userManagerArgs = new AppUserManagerArgs
            {
                UserLockoutEnabledByDefault              = Settings.Default.UserLockoutEnabledByDefault,
                PasswordRequireDigit                     = Settings.Default.PasswordRequireDigit,
                PasswordRequireLowercase                 = Settings.Default.PasswordRequireLowercase,
                PasswordRequireNonLetterOrDigit          = Settings.Default.PasswordRequireNonLetterOrDigit,
                PasswordRequireUppercase                 = Settings.Default.PasswordRequireUppercase,
                PasswordRequiredLength                   = Settings.Default.PasswordRequiredLength,
                UserAccountLockoutMinutes                = Settings.Default.UserAccountLockoutMinutes,
                UserAllowOnlyAlphanumericUserNames       = Settings.Default.UserAllowOnlyAlphanumericUserNames,
                UserMaxFailedAccessAttemptsBeforeLockout = Settings.Default.UserMaxFailedAccessAttemptsBeforeLockout,
                UserRequireUniqueEmail                   = Settings.Default.UserRequireUniqueEmail
            };

            using (var userManager = new AppUserManager(new AppUserStore(dbContext)
            {
                DisposeContext = false
            }, userManagerArgs))
            {
//                if (userManager.FindByEmail(user.Email) == null)
//                {
//                    userManager.Create(user, DbConstants.DefaultAdministratorUser.Password);
//                    userManager.AddToRole(user.Id, DbConstants.Roles.Administrator.Name);
//                }

                foreach (var dummyUser in dummyUsers)
                {
                    if (userManager.FindByEmail(dummyUser.Email) == null)
                    {
                        userManager.Create(dummyUser, DbConstants.DefaultAdministratorUser.Password);
                        userManager.AddToRole(dummyUser.Id, DbConstants.Roles.Client.Name);
                    }
                }
            }
            dbContext.SaveChanges();

            var userIds = dummyUsers.Select(x => x.Id).ToArray();
            var random  = new Random();

            var messages = new List <Message>();

            for (var index = 0; index < 25; index++)
            {
                var randomInteger = random.Next(0, 100);
                var companyId     = randomInteger % 2 == 0 ? companyPeekClopenburg.Id : companyZara.Id;
                var sentByUserId  = userIds[random.Next(0, userIds.Length)];
                var sentAt        = DateTime.UtcNow.AddSeconds(-1 * random.Next(0, 432000));

                var body = Faker.Lorem.Paragraph();
                if (body.Length > DbConstants.StringLength4096)
                {
                    body = body.Substring(0, DbConstants.StringLength4096 - 4) + " ...";
                }

                var subject = Faker.Lorem.Sentence();
                if (subject.Length > DbConstants.StringLength)
                {
                    subject = subject.Substring(0, DbConstants.StringLength - 4) + " ...";
                }

                messages.Add(new Message
                {
                    Body         = body,
                    Subject      = subject,
                    IsRead       = false,
                    CompanyId    = companyId,
                    SentByUserId = sentByUserId,
                    SentAt       = sentAt
                });
            }
            dbContext.Messages.AddRange(messages);
            dbContext.SaveChanges();
        }
コード例 #12
0
        protected override void Seed(AppDbContext context)
        {
            Settings currentSettings = context.Settings.FirstOrDefault();

            if (currentSettings == null)
            {
                Settings settings = new Settings()
                {
                    Currency               = "USD",
                    ShopName               = "My Demo Shop",
                    ContactEmailAddress    = "*****@*****.**",
                    NotificationReplyEmail = "*****@*****.**",
                    SMTPEnableSSL          = false
                };

                context.Settings.Add(settings);
            }

            AppUserManager userManager = new AppUserManager(new UserStore <AppUser>(context), null);
            AppRoleManager roleManager = new AppRoleManager(new RoleStore <AppRole>(context));

            string roleName = "Administrators";
            string userName = "******";
            string password = "******";
            string email    = "*****@*****.**";

            if (!roleManager.RoleExists(roleName))
            {
                roleManager.Create(new AppRole(roleName));
            }

            if (!roleManager.RoleExists("Staff"))
            {
                roleManager.Create(new AppRole("Staff"));
            }

            AppUser user = userManager.FindByEmail(email);

            if (user == null)
            {
                AppUser newUser = new AppUser
                {
                    Name           = userName,
                    Surname        = userName,
                    UserName       = email,
                    Email          = email,
                    Created        = DateTime.UtcNow,
                    EmailConfirmed = true
                };

                newUser.Carts = new Collection <Cart>
                {
                    new Cart(newUser)
                };

                IdentityResult result = userManager.Create(newUser, password);
                user = userManager.Find(email, password);
            }

            if (!userManager.IsInRole(user.Id, roleName))
            {
                userManager.AddToRole(user.Id, roleName);
            }
            context.SaveChanges();
        }
コード例 #13
0
        public IHttpActionResult PutUserInfo(UserInfoViewModel item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var currentUser = AppUserManager.FindById(User.Identity.GetUserId());

            if (currentUser == null)
            {
                return(NotFound());
            }

            if (currentUser.Email != item.Email)
            {
                var existingEmail = AppUserManager.FindByEmail(item.Email);
                if (existingEmail != null)
                {
                    return(BadRequest("Email is already in use"));
                }
                currentUser.UserName = item.Email;
                currentUser.Email    = item.Email;
            }

            currentUser.FirstName       = item.FirstName;
            currentUser.LastName        = item.LastName;
            currentUser.Phone           = item.Phone;
            currentUser.Company         = item.Company;
            currentUser.Position        = item.Position;
            currentUser.LinkedInProfile = item.LinkedInProfile;
            currentUser.WorkExperience  = item.WorkExperience;
            currentUser.ABN             = item.ABN;
            currentUser.Address         = item.Address;
            currentUser.Timezone        = item.Timezone;
            currentUser.CVLink          = item.CVLink;

            AppUserManager.Update(currentUser);

            if (!String.IsNullOrEmpty(item.Password))
            {
                using (var db = AppDb.Database.BeginTransaction())
                {
                    try
                    {
                        var result1 = AppUserManager.RemovePassword(currentUser.Id);
                        if (!result1.Succeeded)
                        {
                            return(GetErrorResult(result1));
                        }
                        var result2 = AppUserManager.AddPassword(currentUser.Id, item.Password);
                        if (!result2.Succeeded)
                        {
                            return(GetErrorResult(result2));
                        }
                        db.Commit();
                    }
                    catch (Exception)
                    {
                        db.Rollback();
                    }
                }
            }
            return(StatusCode(HttpStatusCode.NoContent));
        }