Ejemplo n.º 1
0
        public async Task <bool> ChangePasswordAsync(string guid, string password)
        {
            int otpExirationHrs = Convert.ToInt32(AppUtil.GetAppSettings(AspectEnums.ConfigKeys.OTPExirationHrs));
            var startTime       = DateTime.Now.Subtract(new TimeSpan(otpExirationHrs, 0, 0));
            var endTime         = DateTime.Now;

            var objOtp = await _dbContext.OtpMaster.FirstOrDefaultAsync(k => k.CreatedDate >= startTime && k.CreatedDate <= endTime && k.Guid == guid);

            if (objOtp == null)
            {
                return(false);
            }

            var user = await _userRepository.GetByIdAsync(objOtp.UserId);

            await _userRepository.UpdateAsync(user);

            //Delete all previous OTPs
            foreach (var o in await _dbContext.OtpMaster.Where(k => k.UserId == user.Id).ToListAsync())
            {
                _dbContext.OtpMaster.Remove(o);
            }

            return(await _dbContext.SaveChangesAsync() > 0);
        }
Ejemplo n.º 2
0
        public async Task DeletePersistedGrantAsync()
        {
            using (var context = new AdminDbContext(_dbContextOptions, _storeOptions, _operationalStore))
            {
                IPersistedGrantRepository persistedGrantRepository = new PersistedGrantRepository(context);

                var localizerMock = new Mock <IPersistedGrantServiceResources>();
                var localizer     = localizerMock.Object;

                var persistedGrantService = new PersistedGrantService(persistedGrantRepository, localizer);

                //Generate persisted grant
                var persistedGrantKey = Guid.NewGuid().ToString();
                var persistedGrant    = PersistedGrantMock.GenerateRandomPersistedGrant(persistedGrantKey);

                //Try add new persisted grant
                await context.PersistedGrants.AddAsync(persistedGrant);

                await context.SaveChangesAsync();

                //Try delete persisted grant
                await persistedGrantService.DeletePersistedGrantAsync(persistedGrantKey);

                var grant = await persistedGrantRepository.GetPersitedGrantAsync(persistedGrantKey);

                //Assert
                grant.Should().BeNull();
            }
        }
Ejemplo n.º 3
0
        public async Task DeletePersistedGrantsAsync()
        {
            using (var context = new AdminDbContext(_dbContextOptions, _storeOptions, _operationalStore))
            {
                var persistedGrantRepository = new PersistedGrantRepository(context);

                var subjectId = 1;

                for (var i = 0; i < 4; i++)
                {
                    //Generate persisted grant
                    var persistedGrantKey = Guid.NewGuid().ToString();
                    var persistedGrant    = PersistedGrantMock.GenerateRandomPersistedGrant(persistedGrantKey, subjectId);

                    //Try add new persisted grant
                    await context.PersistedGrants.AddAsync(persistedGrant);
                }

                await context.SaveChangesAsync();

                //Try delete persisted grant
                await persistedGrantRepository.DeletePersistedGrantsAsync(subjectId);

                var grant = await persistedGrantRepository.GetPersitedGrantsByUser(subjectId.ToString());

                //Assert
                grant.TotalCount.Should().Be(0);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 添加模块
        /// </summary>
        public async Task Add(ModuleAddRequest info)
        {
            if (info.PId == null)
            {
                if (info.Type == (int)ModuleTypeEnum.Menu)
                {
                    throw new ApiException("顶级目录类型不能为菜单!");
                }
            }
            using (_db)
            {
                Module model = _mapper.Map <Module>(info);
                await _db.AddEntityAsync(model);

                await _db.SaveChangesAsync();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 添加字典
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task Add(DictionaryAddRequest info)
        {
            using (_db)
            {
                Domain.Dictionary model = _mapper.Map <Domain.Dictionary>(info);
                if (info.PId != null)
                {
                    Domain.Dictionary pModel = await _db.Dictionary.FindByIdAsync(info.PId.ToInt());

                    model.Category = pModel.Category;
                    model.Name     = pModel.Name;
                }
                await _db.AddEntityAsync(model);

                await _db.SaveChangesAsync();
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 角色信息修改
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task Save(RoleModifyRequest info)
        {
            using (_db)
            {
                if (info.Id != 0)
                {
                    await _db.ExecSqlNoQuery("delete Role_User where RoleId=@RoleId", new SqlParameter("RoleId", info.Id));

                    await _db.ExecSqlNoQuery("delete Privilege where MasterValue=@MasterValue", new SqlParameter("MasterValue", info.Id));

                    Role role = await _db.Role.FindByIdAsync(info.Id);

                    _mapper.Map(info.Role, role);
                    //BeforeModify(role);
                }
                else
                {
                    Role role = _mapper.Map <Role>(info.Role);
                    await _db.AddAsync(role);

                    await _db.SaveChangesAsync();

                    info.Id = role.Id;
                }
                foreach (int id in info.ModuleIds)
                {
                    Privilege privilege = new Privilege(MasterEnum.Role, info.Id, AccessEnum.Module, id);
                    await _db.AddAsync(privilege);
                }
                foreach (int id in info.OperateIds)
                {
                    Privilege privilege = new Privilege(MasterEnum.Role, info.Id, AccessEnum.Operate, id);
                    await _db.AddAsync(privilege);
                }
                foreach (int id in info.UserIds)
                {
                    Role_User model = new Role_User();
                    model.UserId = id;
                    model.RoleId = info.Id;
                    await _db.AddAsync(model);
                }
                await _db.SaveChangesAsync();
            }
        }
        private async Task <Client> GenerateClient(AdminDbContext dbContext)
        {
            var client = ClientMock.GenerateRandomClient(id: 0);

            await dbContext.Clients.AddAsync(client);

            await dbContext.SaveChangesAsync();

            return(client);
        }
        public static async Task <Response> DeleteUserAsync(long id)
        {
            var response = new Response();
            var context  = new AdminDbContext();
            var user     = await context.Users.FindAsync(id);

            context.Users.Remove(user);
            await context.SaveChangesAsync();

            return(response);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Generate default clients, identity and api resources
        /// </summary>
        private static async Task EnsureSeedIdentityServerData(AdminDbContext context)
        {
            if (!context.Clients.Any())
            {
                foreach (var client in Clients.GetAdminClient().ToList())
                {
                    var r = await context.Clients.AddAsync(client.ToEntity());
                }

#if DEBUG
                foreach (var item in MyClients.GetMyClients())
                {
                    var r = await context.Clients.AddAsync(item.ToEntity());
                }
#endif

                await context.SaveChangesAsync();
            }

            if (!context.IdentityResources.Any())
            {
                var identityResources = ClientResources.GetIdentityResources().ToList();

                foreach (var resource in identityResources)
                {
                    await context.IdentityResources.AddAsync(resource.ToEntity());
                }

                await context.SaveChangesAsync();
            }

            if (!context.ApiResources.Any())
            {
                foreach (var resource in ClientResources.GetApiResources().ToList())
                {
                    await context.ApiResources.AddAsync(resource.ToEntity());
                }

                await context.SaveChangesAsync();
            }
        }
Ejemplo n.º 10
0
        public async Task DeleteUserProviderAsync()
        {
            using (var context = new AdminDbContext(_dbContextOptions, _storeOptions, _operationalStore))
            {
                var testUserManager = GetTestUserManager(context);
                var testRoleManager = GetTestRoleManager(context);

                IIdentityRepository identityRepository = new IdentityRepository(context, testUserManager, testRoleManager);

                var localizerIdentityResource = new IdentityServiceResources();

                IIdentityService identityService = new IdentityService(identityRepository, localizerIdentityResource);

                //Generate random new user
                var userDto = IdentityDtoMock.GenerateRandomUser(Guid.NewGuid());

                await identityService.CreateUserAsync(userDto);

                //Get new user
                var user = await context.Users.Where(x => x.UserName == userDto.UserName).SingleOrDefaultAsync();

                userDto.Id = user.Id;

                var newUserDto = await identityService.GetUserAsync(userDto);

                //Assert new user
                userDto.Should().BeEquivalentTo(newUserDto);

                var userProvider = IdentityMock.GenerateRandomUserProviders(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
                                                                            newUserDto.Id);

                //Add new user login
                await context.UserLogins.AddAsync(userProvider);

                await context.SaveChangesAsync();

                //Get added user provider
                var addedUserProvider = await context.UserLogins.Where(x => x.ProviderKey == userProvider.ProviderKey && x.LoginProvider == userProvider.LoginProvider).SingleOrDefaultAsync();

                addedUserProvider.Should().NotBeNull();

                var userProviderDto = IdentityDtoMock.GenerateRandomUserProviders(userProvider.ProviderKey, userProvider.LoginProvider,
                                                                                  userProvider.UserId);

                await identityService.DeleteUserProvidersAsync(userProviderDto);

                //Get deleted user provider
                var deletedUserProvider = await context.UserLogins.Where(x => x.ProviderKey == userProvider.ProviderKey && x.LoginProvider == userProvider.LoginProvider).SingleOrDefaultAsync();

                deletedUserProvider.Should().BeNull();
            }
        }
Ejemplo n.º 11
0
        public async Task SeedDb()
        {
            var list = _context.AdminUsers;

            if (!list.Any())
            {
                var admin1 = new AdminUser {
                    Username = "******", Password = "******"
                };
                //await _context.AdminUsers.AddAsync(admin1);
                await _context.SaveChangesAsync();
            }
        }
Ejemplo n.º 12
0
        public async Task <bool> SaveOtpAsync(OtpMaster otp)
        {
            bool isSuccess = false;

            // In case from Generating OTP from Automatic redirect to Change Password because of not complex password multiple OTPs can be generated
            // Use this validation to restrict user to generate multiple OTPs
            if (await ValidateUser(otp.UserId, AspectEnums.UserValidationType.LastAttemptDuration))
            {
                _dbContext.Entry(otp).State = EntityState.Added;
                isSuccess = await _dbContext.SaveChangesAsync() > 0;
            }
            return(isSuccess);
        }
        public static async Task <Utils.Messages.Response> DeleteEntityAsync(long id)
        {
            var response = new Response();
            var context  = new AdminDbContext();
            var entity   = context.Entities.Find(id);

            if (entity != null)
            {
                context.Entities.Remove(entity);
                await context.SaveChangesAsync();
            }
            return(response);
        }
        public static async Task <Utils.Messages.Response> DeleteRelationTypeAsync(long id)
        {
            var response     = new Response();
            var context      = new AdminDbContext();
            var relationType = context.RelationTypes.Find(id);

            if (relationType != null)
            {
                context.RelationTypes.Remove(relationType);
                await context.SaveChangesAsync();
            }
            return(response);
        }
Ejemplo n.º 15
0
        private static async Task EnsureSeedEmployeeData(AdminDbContext context)
        {
#if DEBUG
            if (!context.Employees.Any())
            {
                context.Employees.AddRange(
                    new EntityFramework.Entities.Employee {
                    GH_工号 = "e11057", SFZH_身份证号 = "420923198408153413", XM_姓名 = "江俊"
                }
                    );
                await context.SaveChangesAsync();
            }
#endif
        }
        public static async Task <Utils.Messages.Response> EditRelationAsync(RelationAddEditModel relationModel)
        {
            var response = new Response();
            var context  = new AdminDbContext();

            ValidateRelation(relationModel, response);
            if (!response.Success)
            {
                return(response);
            }
            var relation = context.Relations.Find(relationModel.Id);

            relation.TypeId = relationModel.TypeId;
            await context.SaveChangesAsync();

            return(response);
        }
        public static async Task <Utils.Messages.Response> EditRelationTypeAsync(RelationTypeAddEditModel relationTypeModel)
        {
            var response = new Response();
            var context  = new AdminDbContext();

            if (context.RelationTypes.Any(u => u.Code.Equals(relationTypeModel.Code) && !u.Id.Equals(relationTypeModel.Id)))
            {
                response.AddMessage(false, "This code is already registered on another entity", ResponseMessageType.Warning);
            }
            else
            {
                var relationType = context.RelationTypes.Find(relationTypeModel.Id);
                relationType.Code = relationTypeModel.Code;
                relationType.Name = relationTypeModel.Name;
                await context.SaveChangesAsync();
            }
            return(response);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 添加登录日志
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task Add(LogLoginRequest info)
        {
            string ua     = _context.HttpContext.Request.Headers["User-Agent"];
            var    client = UAParser.Parser.GetDefault().Parse(ua);

            info.UserAgent = ua;
            info.Browser   = client.UA.ToString();
            info.Os        = client.OS.ToString();
            info.IP        = IPUtils.GetIP(_context?.HttpContext?.Request);
            var model = _mapper.Map <LogLogin>(info);

            using (_db)
            {
                await _db.AddAsync(model);

                await _db.SaveChangesAsync();
            }
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> Edit(int id, [Bind("erabiltzeId,PaswordOld,Pasword1,Pasword2")] pasahitzaAldatu aldatu)
        {
            Usuario user = AdminDbContext.user;


            try
            {
                user.password = aldatu.Pasword2;
                _context.Update(user);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
            }
            return(RedirectToAction(nameof(Index)));

            //return View(aldatu);
        }
        public static async Task <Utils.Messages.Response> EditEntityAsync(EntityAddEditModel entityModel)
        {
            var response = new Response();
            var context  = new AdminDbContext();

            ValidateEntity(entityModel, response);
            if (!response.Success)
            {
                return(response);
            }
            var entity = context.Entities.Find(entityModel.Id);

            entity.TypeId = entityModel.TypeId;
            entity.Name   = entityModel.Name;
            await context.SaveChangesAsync();

            return(response);
        }
        public static async Task <Utils.Messages.Response> AddEntiTypeAsync(EntityTypeAddEditModel entityTypeModel)
        {
            var response = new Response();
            var context  = new AdminDbContext();

            if (context.EntityTypes.Any(u => u.Code.Equals(entityTypeModel.Code)))
            {
                response.AddMessage(false, "This code is already registered", ResponseMessageType.Warning);
            }
            else
            {
                var entityType = new EntityType();
                entityType.Code = entityTypeModel.Code;
                entityType.Name = entityTypeModel.Name;
                context.EntityTypes.Add(entityType);
                await context.SaveChangesAsync();
            }
            return(response);
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> Edit([FromForm] UpdateAdminModel user)
        {
            var edited = await _context.Users.FindAsync(user.Id).ConfigureAwait(false);

            edited.UserName              = user.UserName;
            edited.Email                 = user.Email;
            edited.PhoneNumber           = user.PhoneNumber;
            edited.Banned                = user.Banned;
            _context.Entry(edited).State = EntityState.Modified;
            if (user.Banned)
            {
                var userClaims = await _context.UserClaims.Where(claim => claim.UserId == user.Id).ToListAsync().ConfigureAwait(false);

                _context.UserClaims.RemoveRange(userClaims);
            }
            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(Redirect(nameof(Index)));
        }
        public static async Task <Response> CreateUserAsync(RegisterModel registerModel)
        {
            var response = new Response();
            var context  = new AdminDbContext();

            if (context.Users.Any(u => u.Email.Equals(registerModel.Email)))
            {
                response.AddMessage(false, "This email is already registered", ResponseMessageType.Warning);
            }
            else
            {
                var user = new User();
                user.Email        = registerModel.Email;
                user.Password     = GenerateHashWithSalt(registerModel.Password, registerModel.Email);
                user.PasswordSalt = Path.GetRandomFileName();
                user.RegisterDate = DateTime.Now;
                user.Active       = true;
                context.Users.Add(user);
                await context.SaveChangesAsync();
            }
            return(response);
        }
        public async Task GetPersitedGrantAsync()
        {
            using (var context = new AdminDbContext(_dbContextOptions, _storeOptions, _operationalStore))
            {
                var persistedGrantRepository = new PersistedGrantRepository(context);

                //Generate persisted grant
                var persistedGrantKey = Guid.NewGuid().ToString();
                var persistedGrant    = PersistedGrantMock.GenerateRandomPersistedGrant(persistedGrantKey);

                //Try add new persisted grant
                await context.PersistedGrants.AddAsync(persistedGrant);

                await context.SaveChangesAsync();

                //Try get persisted grant
                var persistedGrantAdded = await persistedGrantRepository.GetPersitedGrantAsync(persistedGrantKey);

                //Assert
                persistedGrant.ShouldBeEquivalentTo(persistedGrantAdded, opt => opt.Excluding(x => x.Key));
            }
        }
        public async Task DeletePersistedGrantAsync()
        {
            using (var context = new AdminDbContext(_dbContextOptions, _storeOptions, _operationalStore))
            {
                var persistedGrantRepository = new PersistedGrantRepository(context);

                //Generate persisted grant
                var persistedGrantKey = Guid.NewGuid().ToString();
                var persistedGrant    = PersistedGrantMock.GenerateRandomPersistedGrant(persistedGrantKey, Guid.Empty);

                //Try add new persisted grant
                await context.PersistedGrants.AddAsync(persistedGrant);

                await context.SaveChangesAsync();

                //Try delete persisted grant
                await persistedGrantRepository.DeletePersistedGrantAsync(persistedGrantKey);

                var grant = await persistedGrantRepository.GetPersitedGrantAsync(persistedGrantKey);

                //Assert
                grant.Should().BeNull();
            }
        }
Ejemplo n.º 26
0
 private async Task <int> AutoSaveChangesAsync()
 {
     return(AutoSaveChanges ? await _dbContext.SaveChangesAsync() : (int)SavedStatus.WillBeSavedExplicitly);
 }