예제 #1
0
        private bool IsValidUser(UserLogOnViewModel model)
        {
            model.GeoLocation = GeoLocationInfo.GetGeolocationInfo();

            //проверяем, есть ли емейл в базе
            var user = _identityDbContext.ApplicationUsers.Include("ApplicationUserPasswordHistories")
                       .SingleOrDefault(p => p.Email == model.Email);

            if (user == null)
            {
                throw new Exception($"Пользователя с email {model.Email} нет в базе");
            }

            //проверяем, подходит ли пароль емейлу
            var userPassword = user.ApplicationUserPasswordHistories.SingleOrDefault(p => p.Password == model.Password);

            if (userPassword == null)
            {
                user.FailedSignInCount += 1;
                _identityDbContext.SaveChanges();
                throw new Exception("Неверный пароль");
            }
            if (userPassword != null && userPassword.InvalidatedDate != null)
            {
                user.FailedSignInCount += 1;
                _identityDbContext.SaveChanges();
                throw new Exception("Аккаунт пользователя заблокирован");
            }

            //добавляем строку нового входа в таблице ApplicationUserSignInHistories в БД
            ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory()
            {
                Id = Guid.NewGuid(),
                ApplicationUserId = user.Id,
                SignInTime        = DateTime.Now,
                MachineIp         = model.GeoLocation.ip,
                IpToGeoCountry    = model.GeoLocation.country_name,
                IpToGeoCity       = model.GeoLocation.city,
                IpToGeoLatitude   = model.GeoLocation.latitude,
                IpToGeoLongitude  = model.GeoLocation.longitude
            };

            _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory);
            _identityDbContext.SaveChanges();

            return(true);
        }
        public void OpenOrganization(RegisterOrganizationViewModel model)
        {
            var geoLocationInfo = GeoLocationInfo.GetGeolocationInfo();

            if (model == null)
            {
                throw new Exception($"{typeof(RegisterOrganizationViewModel).Name} is null");
            }

            var checkOrganization = _applicationDbContext.Organizations
                                    .SingleOrDefault(p => p.IdentificationNumber == model.IdentificationNumber || p.FullName == model.FullName);

            if (checkOrganization != null)
            {
                throw new Exception("Такая организация уже сущуствует в базе");
            }

            var checkOrganizationType = _applicationDbContext.OrganizationTypes
                                        .SingleOrDefault(p => p.Name == model.OrganizationType);

            if (checkOrganizationType == null)
            {
                OrganizationType orgType = new OrganizationType()
                {
                    Id   = Guid.NewGuid(),
                    Name = model.OrganizationType
                };
                _applicationDbContext.OrganizationTypes.Add(orgType);
                _applicationDbContext.SaveChanges();
                checkOrganizationType = orgType;
            }


            Organization organization = new Organization()
            {
                Id                   = Guid.NewGuid(),
                FullName             = model.FullName,
                IdentificationNumber = model.IdentificationNumber,
                RegistrationDate     = DateTime.Now,
                OrganizationTypeId   = checkOrganizationType.Id
            };

            _applicationDbContext.Organizations.Add(organization);
            _applicationDbContext.SaveChanges();

            var checkEmployeeEmail = _applicationDbContext.Employees.Any(p => p.Email == model.CeoEmail);

            if (!checkEmployeeEmail)
            {
                var ceoPosition = _applicationDbContext.EmployeePositions.SingleOrDefault(p => p.Name == "CEO");
                if (ceoPosition == null)
                {
                    EmployeePosition pos = new EmployeePosition()
                    {
                        Id   = Guid.NewGuid(),
                        Name = "CEO"
                    };
                    _applicationDbContext.EmployeePositions.Add(pos);
                    _applicationDbContext.SaveChanges();
                    ceoPosition = pos;
                }

                Employee employee = new Employee()
                {
                    Id                 = Guid.NewGuid(),
                    FirstName          = model.CeoFirstName,
                    LastName           = model.CeoLastName,
                    DoB                = model.CeoDoB,
                    Email              = model.CeoEmail,
                    EmployeePositionId = new Guid(ceoPosition.Id.ToString()),
                    OrganizationId     = organization.Id
                };
                _applicationDbContext.Employees.Add(employee);
                _applicationDbContext.SaveChanges();

                ApplicationUser user = new ApplicationUser()
                {
                    Id                   = Guid.NewGuid(),
                    Email                = model.CeoEmail,
                    IsActive             = true,
                    FailedSignInCount    = 0,
                    CreatedDate          = DateTime.Now,
                    AssosiatedEmployeeId = employee.Id
                };
                _identityDbContext.ApplicationUsers.Add(user);
                _identityDbContext.SaveChanges();

                ApplicationUserPasswordHistory userPasswordHistory = new ApplicationUserPasswordHistory()
                {
                    Id                = Guid.NewGuid(),
                    SetupDate         = DateTime.Now,
                    Password          = model.Password,
                    ApplicationUserId = user.Id
                };
                _identityDbContext.ApplicationUserPasswordHistories.Add(userPasswordHistory);
                _identityDbContext.SaveChanges();

                ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory()
                {
                    Id                = Guid.NewGuid(),
                    SignInTime        = DateTime.Now,
                    MachineIp         = geoLocationInfo.ip,
                    IpToGeoCountry    = geoLocationInfo.country_name,
                    IpToGeoCity       = geoLocationInfo.city,
                    IpToGeoLatitude   = geoLocationInfo.latitude,
                    IpToGeoLongitude  = geoLocationInfo.longitude,
                    ApplicationUserId = user.Id
                };
                _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory);
                _identityDbContext.SaveChanges();
            }
        }
        public void ValidateUserInLogIn(UserLogOnVm model)
        {
            var userExists = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Email == model.Email);

            if (userExists == null)
            {
                throw new Exception("Пользователь с таким мэйлом отсутствует в системе");
            }

            var passwordCheck = _identityDbContext.ApplicationUserPasswordHistories
                                .Where(p => p.Password == model.Password && p.ApplicationUserId == userExists.Id)
                                .OrderByDescending(p => p.SetupDate).Take(1);

            if (passwordCheck == null)
            {
                userExists.FailedSignInCount++;
                _identityDbContext.SaveChanges();
                throw new Exception("У данного пользователя другой пароль");
            }

            var FailedSignInCount = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Email == model.Email).FailedSignInCount;

            if (FailedSignInCount > 5)
            {
                userExists.IsActive = false;
                throw new Exception("Вы ввели неправильный пароль более 5 раз");
            }
            var invalidatedDateCheck = _identityDbContext.ApplicationUserPasswordHistories
                                       .Where(p => p.ApplicationUser.Email == model.Email && p.Password == model.Password)
                                       .OrderByDescending(p => p.SetupDate).Take(1);

            if (invalidatedDateCheck.FirstOrDefault().InvalidatedDate <= DateTime.Now)
            {
                userExists.IsActive = false;
                _identityDbContext.SaveChanges();
                throw new Exception("Истекла валидная дата для данного пароля");
            }


            var validUser = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Id == userExists.Id && (p.IsActive == true));

            if (validUser == null)
            {
                throw new Exception("Данный пользователь заблокирован");
            }

            validUser.FailedSignInCount = 0;
            _identityDbContext.SaveChanges();

            GeoLocationInfo geoInfo = GeoLocationInfo.GetGeolocationInfo();

            ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory()
            {
                ApplicationUserId = validUser.Id,
                IpToGeoCity       = geoInfo.city,
                IpToGeoLatitude   = geoInfo.latitude,
                IpToGeoCountry    = geoInfo.country_name,
                IpToGeoLongitude  = geoInfo.longitude,
                MachineIp         = geoInfo.ip,
                SignInTime        = DateTime.Now
            };

            _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory);
            _identityDbContext.SaveChanges();
        }
        public void OpenOrganization(OpenOrganizationRequestVm model)
        {
            if (model == null)
            {
                throw new ArgumentNullException($"{typeof(OpenOrganizationRequestVm).Name} is null");
            }

            var checkOrganization = /*(from o in _aplicationDbContext.Organizations
                                     * where o.IdentificationNumber == model.IdentificationNumber ||
                                     * o.FullName == model.FullName
                                     * select o).ToList(); */
                                    _aplicationDbContext.Organizations
                                    .SingleOrDefault(p => p.IdentificationNumber == model.IdentificationNumber ||
                                                     p.FullName == model.FullName);

            if (checkOrganization != null)
            {
                throw new Exception("Такая организация уже существует в базе");
            }

            var checkOrganizationType = _aplicationDbContext.OrganizationTypes
                                        .SingleOrDefault(p => p.Name == model.OrganizationType);

            if (checkOrganizationType == null)
            {
                throw new Exception("Организационно-правовая форма организации не корректна");
            }


            var Position = _aplicationDbContext.EmployeePositions.SingleOrDefault(p => p.PositionName == "Director");

            if (Position == null)
            {
                throw new Exception("Данной должности не имеется в списке должностей");
            }

            var UserExists = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Email == model.DirectorEmail);

            if (UserExists != null)
            {
                throw new Exception("Пользователь с данным мэйлом уже существует");
            }

            Organization organization = new Organization()
            {
                FullName             = model.FullName,
                IdentificationNumber = model.IdentificationNumber,
                RegistrationDate     = DateTime.Now,
                OrganizationTypeId   = checkOrganizationType.Id,
                OrganizationEmail    = model.OrganizationEmail,
                PhoneNumber          = model.PhoneNumber,
                LinkToWebsite        = model.LinkToWebsite,
                Address = model.Address,
            };

            _aplicationDbContext.Organizations.Add(organization);
            _aplicationDbContext.SaveChanges();

            Employee employee = new Employee()
            {
                FirstName          = model.DirectorFirstName,
                LastName           = model.DirectorLastName,
                DoB                = model.DirectorDoB,
                Email              = model.DirectorEmail,
                EmployeePositionId = Position.Id,
                OrganizationId     = organization.Id
            };

            _aplicationDbContext.Employees.Add(employee);
            _aplicationDbContext.SaveChanges();

            ApplicationUser user = new ApplicationUser()
            {
                Email                = model.DirectorEmail,
                IsActive             = true,
                FailedSignInCount    = 0,
                CreatedDate          = DateTime.Now,
                AssosiatedEmployeeId = employee.Id
            };

            _identityDbContext.ApplicationUsers.Add(user);
            _identityDbContext.SaveChanges();

            ApplicationUserPasswordHistory userPasswordHistory = new ApplicationUserPasswordHistory()
            {
                SetupDate         = DateTime.Now,
                InvalidatedDate   = DateTime.Now.AddMonths(3),
                Password          = model.Password,
                ApplicationUserId = user.Id
            };

            _identityDbContext.ApplicationUserPasswordHistories.Add(userPasswordHistory);
            _identityDbContext.SaveChanges();

            var geoLocationInfo = GeoLocationInfo.GetGeolocationInfo();

            ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory()
            {
                SignInTime        = DateTime.Now,
                MachineIp         = geoLocationInfo.ip,
                IpToGeoCountry    = geoLocationInfo.country_name,
                IpToGeoCity       = geoLocationInfo.city,
                IpToGeoLatitude   = geoLocationInfo.latitude,
                IpToGeoLongitude  = geoLocationInfo.longitude,
                ApplicationUserId = user.Id
            };

            _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory);
            _identityDbContext.SaveChanges();
        }