public async Task UpdateAllUserRoles(User user, IEnumerable <RoleDto> roles) { // Removing all current roles var userRoles = await UserRoleRepository.GetWhereAsync(ur => ur.UserId == user.Id); if (userRoles != null) { foreach (var uRole in userRoles) { this.UserRoleRepository.Delete(uRole); } } // Apply new roles if (roles != null && roles.Count() > 0) { foreach (var role in roles) { await this.UserRoleRepository.AddAsync(new UserRole() { UserId = user.Id, RoleId = role.Id }); } } await this.UserRoleRepository.SaveAsync(); }
public async Task <User> CreateExternalUser(string login) { var user = new User(); user.Id = Guid.NewGuid(); user.Login = login.ToLower(); user.ActivationCode = Guid.NewGuid(); user.Password = "******"; user.Type = LoginType.EXTERNAL; user.IsActive = true; var lstRole = await RoleRepository.GetWhereAsync(r => r.Name.ToLower().Equals("external")); if (!lstRole.Any()) { throw new Exception("Cannot find role external"); } await UserRoleRepository.AddAsync(new UserRole() { User = user, RoleId = lstRole.First().Id }); await this.Repository.SaveAsync(); return(user); }
public UnitOfWorkWebApi(ApplicationContext context) : base(context) { /*************Authorization************/ Claims = new ClaimRepository(context); ClientApplications = new ClientApplicationRepository(context); ClientApplicationUtils = new ClientApplicationUtilRepository(context); RoleClaims = new RoleClaimRepository(context); RoleEntityClaims = new RoleEntityClaimRepository(context); Roles = new RoleRepository(context); UserClaims = new UserClaimRepository(context); UserEntityClaims = new UserEntityClaimRepository(context); Users = new UserRepository(context); UserRoles = new UserRoleRepository(context); UserUtils = new UserUtilRepository(context); Applications = new ApplicationRepository(context); ApplicationUsers = new ApplicationUserRepository(context); /*************Authorization************/ /*************Instances************/ Matches = new MatchRepository(context); Teams = new TeamRepository(context); Players = new PlayerRepository(context); Stats = new StatRepository(context); /*********End of Instances*********/ }
private void AddRoles(User user, IEnumerable <int> PostedRoles, UserRoleModel viewModel, EducationSecurityPrincipal requestor) { var rolesToAdd = PostedRoles.Except(user.UserRoles.Select(u => u.RoleId)).ToList(); foreach (int roleId in rolesToAdd) { var role = RoleRepository.Items.SingleOrDefault(r => r.Id == roleId); if (role != null) { var schools = GetSelectedSchools(viewModel.allSchoolsSelected, role, viewModel.SelectedSchoolIds).ToList(); var providers = GetSelectedProviders(role, viewModel.SelectedProviderIds).ToList(); var newUserRole = new UserRole { RoleId = roleId, UserId = viewModel.UserId, CreatingUser = requestor.Identity.User }; user.UserRoles.Add(newUserRole); UserRoleRepository.Add(newUserRole); foreach (School school in schools) { UserRoleRepository.AddLink(newUserRole, school); } foreach (Provider provider in providers) { UserRoleRepository.AddLink(newUserRole, provider); } } } }
public List<UserRole> GetAllUserRoles(bool addChooseEntity) { List<UserRole> userRoles = new UserRoleRepository().GetAll(); if (addChooseEntity) userRoles.Insert(0, new UserRole(-1, "Odaberi")); return userRoles; }
public UnitOfWork(ApplicationDbContext context) { _context = context; Attempts = new AttemptRepository(_context); Exams = new ExamRepository(_context); Images = new ImageRepository(_context); NoteParameters = new NoteParameterRepository(_context); Notifications = new NotificationRepository(_context); Notes = new NoteRepository(_context); Opinions = new OpinionRepository(_context); Options = new OptionRepository(_context); Passages = new PassageRepository(_context); Questions = new QuestionRepository(_context); Requirements = new RequirementRepository(_context); Roles = new RoleRepository(_context); RoleClaims = new RoleClaimRepository(_context); Standards = new StandardRepository(_context); Sittings = new SittingRepository(_context); Topics = new TopicRepository(_context); Users = new UserRepository(_context); UserClaims = new UserClaimRepository(_context); UserLogins = new UserLoginRepository(_context); UserRoles = new UserRoleRepository(_context); UserTokens = new UserTokenRepository(_context); }
public bool Create(UserBO userBO) { using (var db = new dbGSCasinoContext()) { using (var transaction = db.Database.BeginTransaction()) { UserInfoRepository userInfoRepository = new UserInfoRepository(); TblUserInfo userInfo = userInfoRepository.Create(userBO, db); UserAuthRepository userAuthRepository = new UserAuthRepository(); TblUserAuth userAuth = userAuthRepository.Create(userBO, userInfo, db); UserRoleRepository userRoleRepository = new UserRoleRepository(); userRoleRepository.Create(userAuth, db); // CREATE USER WALLETS UserWalletAppService userWallet = new UserWalletAppService(); userWallet.Create(userAuth, db); transaction.Commit(); return(true); } } }
public async Task <Guid> CreateDonorPF(DonorPFCreateDto donorPFDto) { User user = new User(Guid.NewGuid(), donorPFDto.Login.ToLower(), donorPFDto.Password.ToSHA512(), LoginType.DONOR_PF, Guid.NewGuid(), true); var donorPF = this.Mapper.Map <DonorPF>(donorPFDto); donorPF.Id = Guid.NewGuid(); donorPF.UserId = user.Id; var lstRole = await RoleRepository.GetWhereAsync(r => r.Name.ToLower().Equals("donor_pf")); if (!lstRole.Any()) { throw new Exception("Cannot find role donor_pf"); } await UserRoleRepository.AddAsync(new UserRole() { User = user, RoleId = lstRole.First().Id }); await this.Repository.AddAsync(donorPF); await this.Repository.SaveAsync(); return(donorPF.Id); }
/// <summary> /// To get the user role details by id. /// </summary> /// <param name="ID"></param> /// <param name="accessToken"></param> /// <returns></returns> public UserRole GetUserRoleByID(int id, string accessToken) { UserRole userRole = null; try { dynamic session = null; if (!string.IsNullOrEmpty(accessToken)) { session = _sessionManager.GetSessionValues(accessToken); } if (!string.IsNullOrEmpty(session.DatabaseId()) || _isNonPCR) { using (var repository = new UserRoleRepository(session.DatabaseId())) { userRole = repository.GetUserRoleIDDetails(id); } } else { throw new Exception("Unable to get database connection."); } } catch { throw; } return(userRole); }
public UserResponseBO Authenticate(UserBO userBO) { using (var db = new dbGSCasinoContext()) { UserAuthRepository userAuthRepository = new UserAuthRepository(); TblUserAuth userAuth = userAuthRepository.Get(userBO, db); UserInfoRepository userInfoRepository = new UserInfoRepository(); TblUserInfo userInfo = userInfoRepository.Get(userAuth, db); UserWalletRepository userWalletRepository = new UserWalletRepository(); List <UserWalletBO> userWallet = userWalletRepository.GetBO(userAuth, db); UserRoleRepository userRoleRepository = new UserRoleRepository(); TblUserRole userRole = userRoleRepository.Get(userAuth, db); UserResponseBO userAuthResponse = new UserResponseBO(); userAuthResponse.UserInfo = userInfo; userAuthResponse.UserWallet = userWallet; userAuthResponse.UserAuth = userAuth; userAuthResponse.UserRole = userRole; return(userAuthResponse); } }
/// <summary> /// To get all the user roles. /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public IList <UserRole> GetUserRoles(string accessToken) { IList <UserRole> lstUserRoles = null; try { dynamic session = null; if (!string.IsNullOrEmpty(accessToken)) { session = _sessionManager.GetSessionValues(accessToken); } if (!string.IsNullOrEmpty(session.DatabaseId()) || _isNonPCR) { using (var repository = new UserRoleRepository(session.DatabaseId())) { lstUserRoles = repository.GetUserRoles(); } } else { throw new Exception("Unable to get database connection."); } } catch { throw; } return(lstUserRoles); }
public void RemoveSetting() { var options = new DbContextOptionsBuilder <CacidbContext>().UseInMemoryDatabase(databaseName: "CACIDB").Options; context.Database.EnsureDeleted(); using (var dbContext = new CacidbContext(options)) { dbContext.UserRole.Add(new UserRole { UserRoleId = 1 }); dbContext.SaveChanges(); } using (var dbContext = new CacidbContext(options)) { UserRoleRepository repository = new UserRoleRepository(dbContext); var caseOne = repository.Get().FirstOrDefault(m => m.UserRoleId == 1); bool result = repository.Delete(caseOne); Assert.AreEqual(true, result); List <UserRole> cases = repository.Get().ToList(); Assert.AreEqual(0, cases.Count); } }
public void UpdateSetting() { var options = new DbContextOptionsBuilder <CacidbContext>().UseInMemoryDatabase(databaseName: "CACIDB").Options; context.Database.EnsureDeleted(); using (var dbContext = new CacidbContext(options)) { dbContext.UserRole.Add(new UserRole { UserRoleId = 1 }); dbContext.SaveChanges(); } using (var dbContext = new CacidbContext(options)) { UserRoleRepository repository = new UserRoleRepository(dbContext); // test Get By AppSettingName bool result = repository.Update(new UserRole { UserRoleId = 1 }); Assert.AreEqual(true, result); Assert.AreEqual(1, dbContext.UserRole.ToList()[0].UserRoleId); } }
public WebsiteUserStore() { _userRepository = new UserRepository <TUser>(); _userLoginRepository = new UserLoginRepository(); _userClaimRepository = new UserClaimRepository <TUser>(); _userRoleRepository = new UserRoleRepository <TUser>(); }
public async Task Initialize() { ApplicationDbFactory = new ApplicationDbFactory("InMemoryDatabase"); await ApplicationDbFactory.Create().Database.EnsureDeletedAsync(); await ApplicationDbFactory.Create().Database.EnsureCreatedAsync(); ApplicationDbFactory.Create().ResetValueGenerators(); ApplicationUserRepository = new UserRepository(ApplicationDbFactory.Create(), ApplicationUserValidator); FollowerRepository = new FollowerRepository(ApplicationDbFactory.Create(), FollowerValidator); CredentialRepository = new CredentialRepository(ApplicationDbFactory.Create(), CredentialValidator); CredentialTypeRepository = new CredentialTypeRepository(ApplicationDbFactory.Create(), CredentialTypeValidator); RoleRepository = new RoleRepository(ApplicationDbFactory.Create(), RoleValidator); UserRoleRepository = new UserRoleRepository(ApplicationDbFactory.Create(), UserRoleValidator); RolePermissionRepository = new RolePermissionRepository(ApplicationDbFactory.Create(), RolePermissionValidator); PermissionRepository = new PermissionRepository(ApplicationDbFactory.Create(), PermissionValidator); HttpContextAccessor = new HttpContextAccessor(); // NOTE: Don't actually use it, when using Startup it will inject the HttpContext. (here it will always be null) UserManager = new UserManager(ApplicationUserRepository, CredentialTypeRepository, CredentialRepository, RoleRepository, UserRoleRepository, RolePermissionRepository, PermissionRepository, HttpContextAccessor, Hasher, SaltGenerator); UserService = new UserService(UserManager, ApplicationUserRepository, FollowerRepository); // A Credential type is required for a user to be able to login or register. await CredentialTypeRepository.CreateAsync(new CredentialType { Code = "Email", Name = "Email", Position = 1 }); }
public void Setup() { new DatabaseHelper().InsertTestUserRoles(); var sut = new UserRoleRepository(new ConnectionString()); _actual = sut.GetAll(); }
public bool AddUserRole(string userID, string roleIDStr) { try { var user = UserRepository.GetQueryable().FirstOrDefault(u => u.USER_ID == userID); string[] roleIdList = roleIDStr.Split(','); for (int i = 0; i < roleIdList.Length - 1; i++) { //Guid rid = new Guid(roleIdList[i]); string rid = roleIdList[i].ToString(); var role = RoleRepository.GetQueryable().FirstOrDefault(r => r.ROLE_ID == rid); var userRole = new AUTH_USER_ROLE(); // userRole.USER_ROLE_ID = Guid.NewGuid().ToString(); userRole.USER_ROLE_ID = UserRepository.GetNewID("AUTH_USER_ROLE", "USER_ROLE_ID"); userRole.AUTH_USER = user; userRole.AUTH_ROLE = role; UserRoleRepository.Add(userRole); UserRoleRepository.SaveChanges(); } } catch (Exception e) { return(false); } return(true); }
public Task AddToRoleAsync(TUser user, string roleName) { if (user == null) { throw new ArgumentNullException("user"); } if (string.IsNullOrEmpty(roleName)) { throw new ArgumentException("Argument cannot be null or empty: roleName."); } var role = RoleRepository.GetByWhere(new Dictionary <string, object> { { "Name", roleName } }); var roleId = role == null ? null : role.First().Id; if (!string.IsNullOrEmpty(roleId)) { UserRoleRepository.Insert(new IdentityUserRole { UserId = user.Id, RoleId = roleId }); } return(Task.FromResult <object>(null)); }
/// <summary> /// 用户登录验证 /// </summary> /// <returns></returns> public bool check(string username, string password, out LoginUserInfomation loginUserInfomation) { bool result = false; loginUserInfomation = new LoginUserInfomation(); UserListRepository userListRepository = new UserListRepository(); List <UserList> user = userListRepository.GetListWithCondition(new { Username = username, UserPassword = password }); if (user.Count != 0) { result = true; loginUserInfomation.user = user[0]; UserPermissionListRepository userPermissionListRepository = new UserPermissionListRepository(); if (user[0].UserPermissionID.HasValue) { UserPermissionList temp_userPermission = userPermissionListRepository.GetEntityById(user[0].UserPermissionID.Value); if (temp_userPermission != null) { loginUserInfomation.userPermission = temp_userPermission; } } UserRoleRepository userRoleRepository = new UserRoleRepository(); if (user[0].UserRoleID.HasValue) { UserRole temp_userRole = userRoleRepository.GetEntityById(user[0].UserRoleID.Value); if (temp_userRole != null) { loginUserInfomation.userRole = temp_userRole; } } } return(result); }
public UserController() { TaxiHeavenContext ctx = new TaxiHeavenContext(); _userRepository = new UserRepository(ctx); _userRoleRepository = new UserRoleRepository(ctx); }
public RoleServiceImpl(RoleRepository roleRepo, RolePermissionMapService rolePermissionMapService, UserRoleRepository userRoleRepo, Helper.TransactionManager transactionManager) { _roleRepo = roleRepo; _rolePermissionMapService = rolePermissionMapService; _userRoleRepo = userRoleRepo; _transactionManager = transactionManager; }
public ProjectController() { DbContext = new ApplicationDbContext(); ProjectRepository = new ProjectRepository(DbContext); UserRepository = new UserRepository(DbContext); UserRoleRepository = new UserRoleRepository(DbContext); }
public async Task <List <UserRole> > GetUserRoles(int userId, bool isAdmin) { var userRoleCache = new UserRoleCache(Cache); List <UserRole> cacheResult = await userRoleCache.GetUserRolesFromCache(userId, isAdmin); if (cacheResult != null) { return(cacheResult); } List <UserRole> roles; using (var uow = new UnitOfWork(Context)) { var repo = new UserRoleRepository(uow); roles = await repo.GetAllWithRelated(isAdmin).Where(c => c.UserId == userId).ToListAsync(); } if (roles != null) { await userRoleCache.AddUserRolesToCache(userId, roles, isAdmin); } return(roles); }
public async Task <Page <UserRoleGrid> > GetGrid(GridRequest gridRequest, int?userId, int?roleId) { if (!userId.HasValue && !roleId.HasValue) { throw new CallerException("UserId or RoleId is required"); } var data = new Page <UserRoleGrid>(); using (var uow = new UnitOfWork(Context)) { var repo = new UserRoleRepository(uow); var query = repo.GetAllForGrid(userId, roleId); var dataGridLogic = new DataGridLogic <UserRoleGrid>(gridRequest, query); data.Records = await dataGridLogic.GetResults(); //TODO this wont work data.PageSize = dataGridLogic.PageSize; data.PageOffset = dataGridLogic.PageOffset; data.TotalRecordCount = dataGridLogic.TotalRecordCount; data.SortExpression = dataGridLogic.SortExpression; } return(data); }
[Explicit] // This test is currently broken .. there is no cache invalidation on the set of roles that include the 'Everyone' role public void Test_User_NestedEveryone( ) // see TFS #27869 { UserRoleRepository roleRepository; Role parentRole; Role everyoneRole; UserAccount userAccount; ISet <long> result; using (DatabaseContext.GetContext(true)) { parentRole = Entity.Create <Role>( ); everyoneRole = Entity.Get <Role>(WellKnownAliases.CurrentTenant.EveryoneRole); parentRole.IncludesRoles.Add(everyoneRole); parentRole.Save( ); userAccount = Entity.Create <UserAccount>( ); userAccount.Save( ); roleRepository = new UserRoleRepository( ); result = roleRepository.GetUserRoles(userAccount.Id); Assert.That(result, Is.Not.Null); Assert.That(result, Has.Some.EqualTo(parentRole.Id), "Parent role not found"); Assert.That(result, Has.Some.EqualTo(WellKnownAliases.CurrentTenant.EveryoneRole), "Child role not found"); } }
public void Test_User_NestedRole() { UserRoleRepository roleRepository; Role parentRole; Role childRole; UserAccount userAccount; ISet <long> result; using (DatabaseContext.GetContext(true)) { parentRole = Entity.Create <Role>(); childRole = Entity.Create <Role>(); parentRole.IncludesRoles.Add(childRole); parentRole.Save(); userAccount = Entity.Create <UserAccount>(); userAccount.UserHasRole.Add(childRole); userAccount.Save(); roleRepository = new UserRoleRepository(); result = roleRepository.GetUserRoles(userAccount.Id); Assert.That(result, Is.Not.Null); Assert.That(result, Has.Count.EqualTo(UserRoleRepository.EveryoneRoles.Count + 2)); Assert.That(result, Has.Some.EqualTo(parentRole.Id), "Parent role not found"); Assert.That(result, Has.Some.EqualTo(childRole.Id), "Child role not found"); } }
public async void Add_Success() { var sqlR = new UserRoleRepository(); var e = new UserRole { Name = Guid.NewGuid().ToString(), Permissions = 123 }; var id = await sqlR.Add(new UserRoleRepository.UserRoleUi { Role = e }); var results = await sqlR.GetAll(0, 10000); foreach (var result in results.Data) { if (string.IsNullOrEmpty(result.Role.Name) || result.Role.Permissions == 0) { throw new NullException(result); } if (result.Role.Name.Equals(e.Name) && result.Role.Id == id) { Assert.True(true); } } }
public void Test_Role_NestedRole(bool useChild) { UserRoleRepository roleRepository; Role parentRole; Role childRole; ISet <long> result; using (DatabaseContext.GetContext(true)) { parentRole = Entity.Create <Role>( ); childRole = Entity.Create <Role>( ); parentRole.IncludesRoles.Add(childRole); parentRole.Save( ); roleRepository = new UserRoleRepository( ); result = roleRepository.GetUserRoles(useChild ? childRole.Id : parentRole.Id); Assert.That(result, Is.Not.Null); Assert.That(result, Has.Some.EqualTo(parentRole.Id), "Parent role not found"); if (useChild) { Assert.That(result, Has.Some.EqualTo(childRole.Id), "Child role not found"); } else { Assert.That(result, Has.None.EqualTo(childRole.Id), "Child role unexpected"); } Assert.That(result, Has.Count.EqualTo(UserRoleRepository.EveryoneRoles.Count + (useChild ? 2 : 1))); } }
public ActionResult Edit(UserRoleModel model) { var result = new JsonModel(); var opType = OperationType.Insert; UserRole role = null; if (model.Id > 0) { role = UserRoleRepository.Get(model.Id); if (role == null) { result.msg = $"找不到id为{0}的角色"; return(Json(result)); } opType = OperationType.Update; } else { role = new UserRole(); } Mapper.Map(model, role); UserRoleSvc.SaveList(role, model.MenuIds); LogRepository.Insert(TableSource.UserRole, opType, role.Id); result.code = JsonModelCode.Succ; ShowSuccMsg("保存成功!"); return(Json(result)); }
public ActionResult GetList(string keyWord) { var search = GetSearchModel(); var list = UserRoleRepository.GetList(keyWord, search); return(Json(list, JsonRequestBehavior.AllowGet)); }
public ActionResult EditUser(string id) { var context = new AppSecurityContext(); var rolRepository = new RoleRepository(context); var userRolRepository = new UserRoleRepository(context); var user = context.Users.Find(id); var model = new EditAppUserViewModel(); model.Email = user.Email; model.Id = user.Id; var roles = rolRepository.GetAll(); var assignedRoles = userRolRepository.GetAssignedUserRoles(id); if (assignedRoles.Count() > 0) { model.SelectedRoles = assignedRoles.Select(x => x.RoleId).ToArray(); } else { model.SelectedRoles = new string[0]; } model.AvailableRoles = mapper.Map <ICollection <AppRoleViewModel> >(roles); return(View(model)); }
public int Save(UserRole userRole) { UserRoleRepository ur = new UserRoleRepository(); if (userRole.ID > 0) return ur.Update(userRole); else return ur.Insert(userRole); }
public string[] GetUserRolesForUsername(string username) { List<QueryParameter> queryParameters = new List<QueryParameter>(); queryParameters.Add(new QueryParameter("username", username)); List<UserRole> userRoles = new UserRoleRepository().GetByParameter("getUserRolesForUsername", queryParameters); string roles = string.Empty; foreach (UserRole userRole in userRoles) roles += userRole.Name + ","; return roles.Substring(0, roles.Length - 1).Split(','); }
/// <summary> /// Initialize the database and repositories. Inject the database context to repositories. /// </summary> public BaseController() { var db = new BarContext(); BarRepository = new BarRepository(db); BottleRepository = new BottleRepository(db); DrinkRepository = new DrinkRepository(db); DrinkBarRepository = new DrinkBarRepository(db); EventRepository = new EventRepository(db); IngredientDrinkRepository = new IngredientDrinkRepository(db); IngredientRepository = new IngredientRepository(db); OrderDrinkRepository = new OrderDrinkRepository(db); OrderRepository = new OrderRepository(db); QuantityRepository = new QuantityRepository(db); UnitRepository = new UnitRepository(db); UserBarRepository = new UserBarRepository(db); UserRepository = new UserRepository(db); UserRoleRepository = new UserRoleRepository(db); }