public UserOperationsController(IdentityRepository identityRepository, ILogger <UserOperationsController> logger, IHostingEnvironment environment) { _identityRepository = identityRepository; _environment = environment; _logger = logger; }
public PrescriptionTests() { SeedData(); IConfiguration config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var mockMapper = new MapperConfiguration(cfg => cfg.AddProfile(new MappingProfile())); var mapper = mockMapper.CreateMapper(); var userManager = MockUserManager.GetMockUserManager(_fakeIdentityUsers).Object; var signInManager = MockSigninManager.GetSignInManager <IdentityUser>(userManager).Object; IdentityRepositoryFake = new IdentityRepository(userManager, signInManager, config); var fakeGenericRepo = MockGenericRepository.GetUserInformationMock(_fakeEntities); var fakeGenericRepoUserInformationMock = MockGenericRepository.GetUserInformationMock(_fakeUsersInformation); MockUserExtension.ExtendMock(fakeGenericRepoUserInformationMock, _fakeUsersInformation); var userInformationMock = MockGenericRepository.GetUserInformationMock(_patients); var constulatationsMock = MockGenericRepository.GetUserInformationMock(_constulatations); MockGenericExtension.ExtendMock(fakeGenericRepo, _fakeEntities); FakeController = new PrescriptionsController(IdentityRepositoryFake, fakeGenericRepo.Object, fakeGenericRepoUserInformationMock.Object, userInformationMock.Object, constulatationsMock.Object, mapper); IdentityHelper.SetUser(_fakeIdentityUsers[0], FakeController); }
protected void CreateRolesAndUsersForTask() { var roles = new [] { "Employees", "USA", "Managers", "Ukraine", "Developers", "Main Office" }; roles.ForEach(role => IdentityRepository.AddRole(role)); IdentityRepository.AddChildrenRoles("Employees", new List <string> { "USA", "Managers", "Ukraine", "Developers" }); IdentityRepository.AddChildrenRoles("Ukraine", new List <string> { "Main Office" }); IdentityRepository.AddChildrenRoles("Developers", new List <string> { "Main Office" }); CreateUserForTask("O. Cole", "*****@*****.**"); CreateUserForTask("J. Shane", "*****@*****.**"); CreateUserForTask("V. Petrov", "*****@*****.**"); CreateUserForTask("M. Popov", "*****@*****.**"); IdentityRepository.AddUserInRoles("O. Cole", new [] { "USA" }); IdentityRepository.AddUserInRoles("J. Shane", new[] { "USA", "Managers" }); IdentityRepository.AddUserInRoles("V. Petrov", new[] { "Main Office" }); IdentityRepository.AddUserInRoles("M. Popov", new[] { "Main Office" }); }
/// <summary> /// Updates the status of an existing identity (whther it is disabled or not). /// </summary> /// <param name="id">ID of the identity to update.</param> /// <param name="disabled">Whether the identity is to be disabled.</param> /// <returns>Returns the updated identity.</returns> /// <exception cref="EntityNotFoundException">Thrown if the identity could not be found.</exception> public async Task <Identity> UpdateIdentityStatus(Guid id, bool disabled) { Identity identity = await GetIdentity(id); identity.Disabled = disabled; return(await IdentityRepository.UpdateIdentity(identity)); }
/// <summary> /// 获取token /// </summary> /// <returns></returns> public virtual TokenEntity GetToken() { var ticket = GetTokenTicket(); if (string.IsNullOrEmpty(ticket)) { return(null); } if (IdentityRepository.Get <IdentityEntity>(ticket) == null) { RemoveToken(); RemoveTokenTimeOut(); return(null); } if (HttpContext.Current == null) { return(null); } HttpCookie cookie = HttpContext.Current.Request.Cookies[TicketKey]; if (cookie != null) { var token = new TokenEntity { TimeOut = GetTokenTimeOut(), Ticket = cookie.Value }; return(token); } return(null); }
private static async System.Threading.Tasks.Task CreateAdminAccount(UserManager <AspNetUser> userManager, RoleManager <AspNetRole> roleManager) { string username = "******"; string email = "*****@*****.**"; string password = "******"; if (await userManager.FindByNameAsync(username) == null) { AspNetUser user = new AspNetUser { UserName = username, FullName = username, Email = email }; IdentityResult result = await userManager.CreateAsync(user, password); if (result.Succeeded) { IdentityRepository indentityRepo = new IdentityRepository(context, userManager); AspNetUser aspNetUser = await userManager.FindByNameAsync(username); AspNetGroup aspNetGroup = indentityRepo.GetAspNetGroup("Administrator"); AspNetUserGroup aspNetUserGroup = new AspNetUserGroup(); aspNetUserGroup.GroupId = aspNetGroup.GroupId; aspNetUserGroup.UserId = aspNetUser.Id; aspNetUserGroup.Active = true; indentityRepo.AddUserToGroup(aspNetUserGroup); } } }
public ReadOnlyRepositoryTests(ITestOutputHelper output) : base(output) { _identityRepository = new IdentityRepository(_configuration); _dailyRepository = new DailyLogEventRepository(_configuration); _employeeRepository = new EmployeeRepository(_configuration); RemoveDataAsync().GetAwaiter().GetResult(); }
public async Task DeleteUserRoleAsync() { 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.ShouldBeEquivalentTo(newUserDto); //Generate random new role var roleDto = IdentityDtoMock.GenerateRandomRole(Guid.NewGuid()); await identityService.CreateRoleAsync(roleDto); //Get new role var role = await context.Roles.Where(x => x.Name == roleDto.Name).SingleOrDefaultAsync(); roleDto.Id = role.Id; var newRoleDto = await identityService.GetRoleAsync(roleDto); //Assert new role roleDto.ShouldBeEquivalentTo(newRoleDto); var userRoleDto = IdentityDtoMock.GenerateRandomUserRole(roleDto.Id.Value, userDto.Id.Value); await identityService.CreateUserRoleAsync(userRoleDto); //Get new role var userRole = await context.UserRoles.Where(x => x.RoleId == roleDto.Id && x.UserId == userDto.Id).SingleOrDefaultAsync(); userRole.Should().NotBeNull(); await identityService.DeleteUserRoleAsync(userRoleDto); //Get deleted role var userRoleDeleted = await context.UserRoles.Where(x => x.RoleId == roleDto.Id && x.UserId == userDto.Id).SingleOrDefaultAsync(); userRoleDeleted.Should().BeNull(); } }
public virtual void SetIdentityRepository(IdentityRepository identityRepository) { lock (this) { this.identityRepository = identityRepository; } }
// Roles in ASP.Identity public void CreateRolesandUsers() { // Context moet opgehaald worden uit de repository! // ApplicationDbContext repo = (ApplicationDbContext)(((IdentityRepository)Store).Context); _gebruikerMgr = new GebruikerManager(); IdentityRepository repo = new IdentityRepository(); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(repo.GetContext())); // Bij initialisatie van het systeem wordt Admin aangemaakt if (!roleManager.RoleExists("SuperAdmin")) { // Aanmaken van de Admin role roleManager.Create(new IdentityRole { Name = "SuperAdmin" }); // // Administrator aanmaken var user = new ApplicationUser { UserName = "******", Email = "*****@*****.**", VoorNaam = "Qwerty", AchterNaam = "SuperAdmin" }; string userPWD = "Password"; var chkUser = this.Create(user, userPWD); // Administrator de rol van Admin toewijzen if (chkUser.Succeeded) { var result1 = this.AddToRole(user.Id, "SuperAdmin"); } DateTime joindate = DateTime.Now; _gebruikerMgr.AddGebruiker(user.UserName, user.Id, "Admin", "Qwerty", user.Email, joindate, "SuperAdmin"); } // Manager role aanmaken if (!roleManager.RoleExists("Admin")) { roleManager.Create(new IdentityRole { Name = "Admin" }); } // Emloyee role aanmaken if (!roleManager.RoleExists("User")) { roleManager.Create(new IdentityRole { Name = "User" }); } }
public async Task AddRoleAsync() { 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 role var roleDto = IdentityDtoMock.GenerateRandomRole(Guid.NewGuid()); await identityService.CreateRoleAsync(roleDto); //Get new role var role = await context.Roles.Where(x => x.Name == roleDto.Name).SingleOrDefaultAsync(); roleDto.Id = role.Id; var newRoleDto = await identityService.GetRoleAsync(roleDto); //Assert new role roleDto.ShouldBeEquivalentTo(newRoleDto); } }
public TotalUsersModel GetAllUsers() { var users = IdentityRepository.GetAllUsers().Select(u => new TotalUserListElement(u.Id, u.AccountName, u.Email, u.Description, u.Note)).ToList(); return(new TotalUsersModel(users)); }
public AdditionalExaminationResultsTests() { SeedData(); IConfiguration config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var mockMapper = new MapperConfiguration(cfg => cfg.AddProfile(new MappingProfile())); var mock = mockMapper.CreateMapper(); var userManager = MockUserManager.GetMockUserManager(_fakeIdentityUsers).Object; var signInManager = MockSigninManager.GetSignInManager <IdentityUser>(userManager).Object; IdentityRepositoryFake = new IdentityRepository(userManager, signInManager, config); var fakeGenericRepo = MockGenericRepository.GetUserInformationMock(_fakeEntities); var constulationRepo = MockGenericRepository.GetUserInformationMock(_consultations); var patientRepo = MockGenericRepository.GetUserInformationMock(_fakeUsersPatient); var typeRepo = MockGenericRepository.GetUserInformationMock(_types); MockGenericExtension.ExtendMock(fakeGenericRepo, _fakeEntities); FakeController = new AdditionalExaminationResultsController(IdentityRepositoryFake, fakeGenericRepo.Object, constulationRepo.Object, patientRepo.Object, typeRepo.Object, mock); IdentityHelper.SetUser(_fakeIdentityUsers[0], FakeController); }
public IActionResult GetPersonForAgency(long id, [Required, NotNull] string agencySystemName) { var agency = IdentityRepository.GetAgency(agencySystemName); if (agency == null) { ModelState.AddModelError(nameof(agencySystemName), $"{agencySystemName} was not found"); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Debug.Assert(agency != null, nameof(agency) + " != null"); var personIdentity = new PersonIdentity(id); if (!IdentityRepository .GetPeopleWithIdentifiers(new[] { personIdentity }, agency.RootIdentifierNames(), UserProvider) .TryGetValue(personIdentity, out var identifiers)) { return(NotFound(id)); } var personIdForAgency = IdentityRepository.GetPersonAgencyId(personIdentity, agency.Id); return(Ok(new AgencyPersonDto(personIdForAgency, IdentifierDtoMarshaller.MarshallToDtos(identifiers)))); }
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId = string.Empty; string clientSecret = string.Empty; Client client = null; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } if (context.ClientId == null) { //Remove the comments from the below line context.SetError, and invalidate context //if you want to force sending clientId/secrects once obtain access tokens. context.Validated(); //context.SetError("invalid_clientId", "ClientId should be sent."); return(Task.FromResult <object>(null)); } using (IdentityRepository _repo = new IdentityRepository()) { client = _repo.FindClient(context.ClientId); } if (client == null) { context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId)); return(Task.FromResult <object>(null)); } if (client.ApplicationType == Scheduler.Identity.Data.Enums.ApplicationTypes.NativeConfidential) { if (string.IsNullOrWhiteSpace(clientSecret)) { context.SetError("invalid_clientId", "Client secret should be sent."); return(Task.FromResult <object>(null)); } else { if (client.Secret != Helper.GetHash(clientSecret)) { context.SetError("invalid_clientId", "Client secret is invalid."); return(Task.FromResult <object>(null)); } } } if (!client.Active) { context.SetError("invalid_clientId", "Client is inactive."); return(Task.FromResult <object>(null)); } context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin); context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString()); context.Validated(); return(Task.FromResult <object>(null)); }
public async Task AddUserAsync() { 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); } }
protected void InitIdentity() { IdentityRepository.Initialize(); IdentityRepository.CreateDefaultRoles(); IdentityRepository.CreateDefaultAdministrator(); IdentityRepository.CreateDefaultUser(); }
/// <summary> /// Конструктор /// </summary> public CustomUserManager(IUserStore <T> store, IOptions <IdentityOptions> options, IPasswordHasher <T> passwordHasher, IEnumerable <IUserValidator <T> > userValidators, IEnumerable <IPasswordValidator <T> > passwordValidators, ILookupNormalizer lookupNormalizer, IdentityErrorDescriber describer, IServiceProvider serviceProvider, ILogger <UserManager <T> > logger) : base(store, options, passwordHasher, userValidators, passwordValidators, lookupNormalizer, describer, serviceProvider, logger) { _repo = new IdentityRepository(); Logger = logger; }
public BaseResponse UpdateRole(UpdateRoleRequest request) { var roleName = string.IsNullOrWhiteSpace(request.RoleName) ? string.Empty : request.RoleName; var baseRoles = (request.BaseRoles ?? Enumerable.Empty <string>()).ToArray(); IdentityRepository.UpdateRoleInRoles(roleName, baseRoles); return(BaseResponse.Ok()); }
private PersonIdentity FindMatchingPerson(IEnumerable <MatchSpecification> match) { var conversionContext = new MatchSpecificationConversionContext(IdentifierDtoMarshaller); PersonIdentity FindPerson(MatchSpecification spec) => IdentityRepository.FindPersonBy(spec.ToPersonSpecification(conversionContext)); return(match.Select(FindPerson).FirstOrDefault()); }
/// <summary> /// 得到登陆信息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="ticket"></param> /// <returns></returns> public virtual T Get <T>(string ticket) where T : IdentityEntity { ticket = Winner.Creator.Get <ISecurity>().Decrypt3Des(ticket, DesKey); if (string.IsNullOrEmpty(ticket)) { return(default(T)); } return(IdentityRepository.Get <T>(ticket)); }
//public PredictionServiceTests() //{ // var predictionRepository = new Mock<IPredictionRepository>(); // predictionRepository.Setup(x => x.CheckTypeResult(It.IsAny<string>())).ReturnsAsync((string result) => // { // if (Convert.ToInt32(result.Substring(0, 1)) > Convert.ToInt32(result.Substring(2, 1))) return TypeResult.WinTeam1; // else if (Convert.ToInt32(result.Substring(0, 1)) < Convert.ToInt32(result.Substring(2, 1))) return TypeResult.WinTeam2; // else if (Convert.ToInt32(result.Substring(0, 1)) == Convert.ToInt32(result.Substring(2, 1))) return TypeResult.Draw; // else return TypeResult.NNB; // }); // predictionRepository.Setup(x => x.CompareResultsAsync(It.IsAny<Game>(), It.IsAny<Prediction>())).ReturnsAsync((Game z, Prediction y) => // { // if (y.PredictedResult == z.Result) // return 3; // else if (y.PredictedTypeResult == z.typeResult) // return 1; // else // return 0; // }); // _predictionService = new PredictionService(predictionRepository.Object); //} public async Task CreateDb() { var options = new DbContextOptionsBuilder <StrikeNetDbContext>() .UseInMemoryDatabase(databaseName: "StrikeNetTestDb") .EnableSensitiveDataLogging() .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) .Options; var dbContext = new StrikeNetDbContext(options); if (await dbContext.Predictions.CountAsync() <= 0) { Prediction p1 = new Prediction() { Id = 1, GameId = 1, UserId = User1, PredictedResult = "3-0", PredictedTypeResult = TypeResult.WinTeam1 }; Prediction p2 = new Prediction() { Id = 2, GameId = 3, UserId = User2, PredictedResult = "2-0", PredictedTypeResult = TypeResult.WinTeam1 }; Prediction p3 = new Prediction() { Id = 3, GameId = 3, UserId = User3, PredictedResult = "0-1", PredictedTypeResult = TypeResult.WinTeam2 }; Prediction p4 = new Prediction() { Id = 4, GameId = 4, UserId = User4, PredictedResult = "1-1", PredictedTypeResult = TypeResult.Draw }; dbContext.Predictions.Add(p1); dbContext.Predictions.Add(p2); dbContext.Predictions.Add(p3); dbContext.Predictions.Add(p4); await dbContext.SaveChangesAsync(); } var identityRepository = new IdentityRepository(_userManager, _roleManager, _signInManager); var predictionRepository = new PredictionRepository(identityRepository, dbContext); _predictionService2 = new PredictionService(predictionRepository); }
/// <summary> /// Gets an identity by its unique user-chosen identifier. /// </summary> /// <param name="identifier">The identifier of the identity to retrieve.</param> /// <returns>Returns the identity, if found.</returns> /// <exception cref="EntityNotFoundException">Thrown if the identity could not be found.</exception> public async Task <Identity> GetIdentity(string identifier) { Identity identity = await IdentityRepository.GetIdentity(identifier); if (identity == null) { throw new EntityNotFoundException("Identity", identifier); } return(identity); }
public IdentityController(IdentityRepository identityRepository, IHostingEnvironment environment, ILogger <IdentityController> logger, IPasswordHasher <AspNetUser> hasher) { _identityRepository = identityRepository; _enviroment = environment; _logger = logger; _hasher = hasher; }
public UserServices() { _userRepository = new IdentityRepository <ApplicationUser>(); lichSuServices = new LichSuServices(); _imageServices = new ImageServices(); _nhanvienRepository = new IRepository <NhanViens>(); _userRoleRepository = new IdentityRepository <IdentityUserRole>(); _khachhangRepository = new IRepository <KhachHang>(); //UserManager = new ApplicationUserManager(); }
public IdentityServerUsersService( AdminRepository adminRepo, IdentityRepository idRepo, IServiceProvider serviceProvider) : base(serviceProvider) { _adminRepo = adminRepo; _idRepo = idRepo; _userManager = (UserManager <EmbeddedIdentityServerUser>)serviceProvider.GetService(typeof(UserManager <EmbeddedIdentityServerUser>)); }
public IActionResult PutPerson([FromBody, Required] PersonSpecification specification) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } var authority = IdentityRepository.GetAuthority(specification.Authority); if (authority == null) { ModelState.AddModelError( nameof(specification.Authority), $"Authority '{specification.Authority}' does not exist"); } ValidateIdentifierTypes(specification.Identifiers, nameof(specification.Identifiers)); ValidateSpecifications(specification.MatchSpecifications, nameof(specification.MatchSpecifications)); if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } //identifierChecker.EnsureHasNoInvalidDuplicates(specification.Identifiers); var identifiers = IdentifierDtoMarshaller.ConvertToIdentifiers(specification.Identifiers); var person = FindMatchingPerson(specification.MatchSpecifications); if (person == null) { if (specification.UpdateMode == UpdateMode.UpdateOnly) { return(NotFound()); } person = IdentityRepository.CreatePerson(identifiers, authority); return(CreatedAtAction("GetPerson", new { id = person.Id }, new PersonCreatedResult { PersonId = person })); } if (specification.UpdateMode == UpdateMode.CreateOnly) { return(BadRequest(new { Message = $"Person already exists" })); } IdentityRepository.UpdatePerson(person, identifiers, authority); return(new SeeOtherOjectActionResult( "GetPerson", routeValues: new { id = person.Id }, result: new PersonCreatedResult { PersonId = person })); }
private void CreateUserForTask(string userName, string email) { var account = new AccountModel { IsActivate = true, AccountName = userName, Email = email, }; IdentityRepository.CreateUser(account, "!@#$%^&*()"); }
/// <summary> /// Gets all identities, optionally filtered by name. /// </summary> /// <param name="filter">A string to filter identities names with.</param> /// <param name="showDisabled">Whether to return disabled identities. Defaults to false.</param> /// <returns>Returns identities.</returns> public async Task <IEnumerable <Identity> > GetIdentities(string filter, bool showDisabled = false) { if (filter == null) { return(await IdentityRepository.GetIdentities(showDisabled)); } else { return(await IdentityRepository.SearchIdentitiesByIdentifier(filter, showDisabled)); } }
public DetailsUserModel GetUpdateModel(string userName) { var rolesForPage = new List <BaseRoleElement>(); var roles = IdentityRepository.GetAllRoles(); var account = IdentityRepository.GetUser(userName); var userRoles = IdentityRepository.GetRolesForUser(userName); userRoles.ForEach(ur => rolesForPage.Add(new BaseRoleElement(ur, true))); roles.Except(userRoles).ForEach(role => rolesForPage.Add(new BaseRoleElement(role))); return(new DetailsUserModel(account.AccountName, account.Description, account.Email, account.Note, true, rolesForPage)); }
/// <summary> /// 移除 /// </summary> /// <param name="ticket"></param> /// <returns></returns> public virtual bool Remove(string ticket) { try { var rev = IdentityRepository.Remove(ticket); return(rev); } catch (Exception) { return(false); } }
public JSch() { identityRepository = new LocalIdentityRepository(this); try { string osname = (string)(Runtime.GetProperties()["os.name"]); if (osname != null && osname.Equals("Mac OS X")) { config.Put("hmac-sha1", "com.jcraft.jsch.jcraft.HMACSHA1"); config.Put("hmac-md5", "com.jcraft.jsch.jcraft.HMACMD5"); config.Put("hmac-md5-96", "com.jcraft.jsch.jcraft.HMACMD596"); config.Put("hmac-sha1-96", "com.jcraft.jsch.jcraft.HMACSHA196"); } } catch (Exception) { } }