public ActionResult Edit(ApplicationUserViewModel user) { ApplicationDbContext db = new ApplicationDbContext(); if (ModelState.IsValid) { var editedUser = db.Users.FirstOrDefault(x => x.Id == user.Id); editedUser.DisplayName = user.DisplayName; editedUser.Avatar = user.Avatar; editedUser.FacebookProfile = user.FacebookProfile; var role = db.Roles.FirstOrDefault(x => x.Name == "Admin"); var userRole = new UserRole() { Role = role }; if (user.IsAdmin) { editedUser.Roles.Add(userRole); } else { editedUser.Roles.Clear(); } db.SaveChanges(); //Db.UsersRepository.Update(editedUser); //Db.SaveChanges(); return RedirectToAction("Index"); } return View(user); }
// authorization check logic private bool IsAuthorized(UserRole userRoles) { var logger = ObjectFactory.GetInstance<Logger>(); bool result; switch (mode) { case RoleMode.Any: result = (userRoles & roles) == userRoles; break; case RoleMode.All: result = (userRoles & roles) == roles; break; default: logger.Error("[RoleRequiredAttribute].[IsAuthorized] throwing exception ([mode] is unknown)."); throw new InvalidOperationException("Mode is unknown."); } if (!result) { logger.Debug("[RoleRequiredAttribute].[IsAuthorized] finished work with result = 'false'."); } return result; }
public AuthorizeAttribute(UserRole role) { Roles = new[] { role }; }
void LoginCommunication_LoginChanged(UserRole role) { if (role == UserRole.Admin) { TiAdmin.IsEnabled = true; TiEditAdd.IsEnabled = false; TiSearchView.IsEnabled = false; } else if(role == UserRole.Recruiter) { TiAdmin.IsEnabled = false; TiEditAdd.IsEnabled = true; TiSearchView.IsEnabled = true; TiRecruits.IsEnabled = true; } else if (role == UserRole.Manager) { TiAdmin.IsEnabled = false; TiEditAdd.IsEnabled = true; TiSearchView.IsEnabled = true; TiRecruits.IsEnabled = true; TiManager.IsEnabled = true; } else { TiAdmin.IsEnabled = false; TiEditAdd.IsEnabled = false; TiSearchView.IsEnabled = false; TiManager.IsEnabled = false; } }
public ActionResult Add(UserRole model) { var addRoleResult = _roleAdminService.AddRole(model); if (!addRoleResult.Success) TempData.ErrorMessages().Add(addRoleResult.Error); return RedirectToAction("Index"); }
public ActionResult Delete_Get(UserRole role) { if (role == null) return RedirectToAction("Index"); return View(role); }
/// <summary> /// 添加新用户。 /// </summary> /// <param name="username">用户名,此用户名不能已存在。</param> /// <param name="password">密码</param> /// <param name="ipLimit">ip绑定地址</param> /// <param name="role">用户角色</param> /// <param name="functionModularIDs">用户被赋予的权限列表(使用function_modular表的id组成一个数组。数组中的元素即被赋予的权限。)</param> /// <returns>是否插入成功。此方法采用事务处理,所以插入失败不会在数据库产生垃圾数据。</returns> public bool AddUser(String username, String password, String ipLimit, UserRole role, IList<String> functionModularIDs) { User newUser = new User(); newUser.name = username; newUser.password = password; newUser.ipLimit = ipLimit; newUser.role = role; bool result; //事务处理:插入失败,事务回滚 try { sqlMapper.BeginTransaction(); //插入user表 sqlMapper.Insert("InsertUser", newUser); //循环插入user_function表 foreach (String modularId in functionModularIDs) { IDictionary<String, String> dic = new Dictionary<String, String>(); dic.Add("username", username); dic.Add("functionid", modularId); sqlMapper.Insert("InsertUserFunctionRelation", dic); } sqlMapper.CommitTransaction(); result = true; } catch { sqlMapper.RollBackTransaction(); result = false; } return result; }
/// <summary> /// Initializes a new instance of the <see cref="WebSiteUser"/> class. /// </summary> /// <param name="loginName"> /// The login name. /// </param> /// <param name="customerId"> /// The customer id. /// </param> /// <param name="nickName">昵称</param> /// <param name="role"></param> public WebSiteUser(string loginName, int customerId, string nickName, UserRole role) { this.LoginName = loginName; this.CustomerId = customerId; this.NickName = nickName; Role = role; }
public async Task DeleteAsync(UserRole role) { if (role == null) throw new ArgumentNullException("role"); await Task.Run((() => _userRoleRepository.Delete(role.Id))); }
public bool DeleteUserRole(UserRole entity) { if (entity == null) return false; _unitOfWork.UserRoleRepository.Delete(entity); _unitOfWork.Save(); return true; }
// PUT api/UserRoles/5 public HttpResponseMessage PutUserRole(int id, UserRole userrole) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != userrole.Id) { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(userrole).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }
// PUT odata/UserRole(5) public virtual async Task<IHttpActionResult> Put([FromODataUri] int roleId, UserRole userRole) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (roleId != userRole.RoleId) { return BadRequest(); } try { await MainUnitOfWork.UpdateAsync(userRole); } catch (DbUpdateConcurrencyException) { if (!MainUnitOfWork.Exists(roleId)) { return NotFound(); } else { return Conflict(); } } return Ok(userRole); }
public IHttpActionResult Get() { var result = new UserRole(); result.Users = db.GetAllUsersWithRoles().ToList(); result.Roles = db.GetAllRolesWithUsers().ToList(); return Ok(result); }
public void DeleteUserRole(UserRole userrole) { if(userrole == null) throw new ArgumentNullException("userrole"); userrole.IsDeleted = true; _userroleRepository.Update(userrole); }
public AddRoleResult AddRole(UserRole model) { if (_roleService.GetRoleByName(model.Name) != null) return new AddRoleResult(false, string.Format("{0} already exists.", model.Name)); _roleService.SaveRole(model); return new AddRoleResult(true, null); }
public ActionResult UpdateUser([DataSourceRequest]DataSourceRequest request, UsersAdminViewModel userVM) { if (userVM != null && ModelState.IsValid) { var user = this.db.Users.All().FirstOrDefault(u => u.Id == userVM.UserId); Role selectedRole = db.Roles.All().FirstOrDefault(r => r.Id == userVM.RoleId); if (user.Roles != null) { user.Roles.Clear(); } var newRole = new UserRole { Role = selectedRole, RoleId = selectedRole.Id, User = user, UserId = user.Id }; user.Roles.Add(newRole); this.db.SaveChanges(); } var users = this.db.Users.All().Select(UsersAdminViewModel.FromUser); DataSourceResult result = users.ToDataSourceResult(request); return Json(result, JsonRequestBehavior.AllowGet); //return View("Index"); }
/// <summary> /// Run the code example. /// </summary> /// <param name="service">An initialized Dfa Reporting service object /// </param> public override void Run(DfareportingService service) { long parentUserRoleId = long.Parse(_T("INSERT_PARENT_USER_ROLE_ID_HERE")); long permission1Id = long.Parse(_T("INSERT_FIRST_PERMISSION_ID_HERE")); long permission2Id = long.Parse(_T("INSERT_SECOND_PERMISSIONS_ID_HERE")); long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); long subaccountId = long.Parse(_T("INSERT_SUBACCOUNT_ID_HERE")); String userRoleName = _T("INSERT_USER_ROLE_NAME_HERE"); // Create user role structure. UserRole userRole = new UserRole(); userRole.Name = userRoleName; userRole.SubaccountId = subaccountId; userRole.ParentUserRoleId = parentUserRoleId; // Create a permission object to represent each permission this user role // has. UserRolePermission permission1 = new UserRolePermission(); permission1.Id = permission1Id; UserRolePermission permission2 = new UserRolePermission(); permission2.Id = permission2Id; List<UserRolePermission> permissions = new List<UserRolePermission> { permission1, permission2 }; // Add the permissions to the user role. userRole.Permissions = permissions; // Create user role. UserRole result = service.UserRoles.Insert(userRole, profileId).Execute(); // Display user role ID. Console.WriteLine("User role with ID {0} was created.", result.Id); }
public static void InitData(this OAContext db) { #region InitRole var admin = new UserRole { Name = UserRoleEnum.执行站长.ToString(), Describe = UserRoleEnum.执行站长.ToString(), RoleEnum = (int)UserRoleEnum.执行站长 }; db.UserRoles.Add(admin); db.SaveChanges(); var bangong = new UserRole { FatherRole = admin, Name = UserRoleEnum.办公组组长.ToString(), Describe = UserRoleEnum.办公组组长.ToString(), RoleEnum = (int)UserRoleEnum.办公组组长 }; db.UserRoles.Add(bangong); db.SaveChanges(); var bangong2 = new UserRole { FatherRole = bangong, Name = UserRoleEnum.办公组成员.ToString(), Describe = UserRoleEnum.办公组成员.ToString(), RoleEnum = (int)UserRoleEnum.办公组成员 }; db.UserRoles.Add(bangong2); db.SaveChanges(); var jishu = new UserRole { FatherRole = admin, Name = UserRoleEnum.技术组组长.ToString(), Describe = UserRoleEnum.技术组组长.ToString(), RoleEnum = (int)UserRoleEnum.技术组组长 }; db.UserRoles.Add(jishu); db.SaveChanges(); var jishu2 = new UserRole { FatherRole = jishu, Name = UserRoleEnum.技术组成员.ToString(), Describe = UserRoleEnum.技术组成员.ToString(), RoleEnum = (int)UserRoleEnum.技术组成员 }; db.UserRoles.Add(jishu2); db.SaveChanges(); var yunying = new UserRole { FatherRole = admin, Name = UserRoleEnum.运营组组长.ToString(), Describe = UserRoleEnum.运营组组长.ToString(), RoleEnum = (int)UserRoleEnum.运营组组长 }; db.UserRoles.Add(yunying); db.SaveChanges(); var yunying2 = new UserRole { FatherRole = yunying, Name = UserRoleEnum.运营组成员.ToString(), Describe = UserRoleEnum.运营组成员.ToString(), RoleEnum = (int)UserRoleEnum.运营组成员 }; db.UserRoles.Add(yunying2); db.SaveChanges(); #endregion }
private void CheckPermission(UserRole role, Enum permissions = null) { if (currentUser == null) { throw new FaultException("Пользователь не авторизован в системе"); } if (currentUser is Administrator && role.HasFlag(UserRole.Administrator)) { var administrator = currentUser as Administrator; if (permissions != null && !administrator.Permissions.HasFlag(permissions)) { throw new FaultException("Недостаточно прав для доступа"); } return; } if (currentUser is Operator && role.HasFlag(UserRole.Operator)) { return; } throw new FaultException("Ошибка прав доступа"); }
public User(string email, string password, UserRole role=UserRole.Basic) { SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); Email = email; PasswordHash = ASCIIEncoding.ASCII.GetString(sha1.ComputeHash(Encoding.ASCII.GetBytes(password))); Role = role; }
public int Save(UserRole userRole) { UserRoleRepository ur = new UserRoleRepository(); if (userRole.ID > 0) return ur.Update(userRole); else return ur.Insert(userRole); }
public void RoleController_AddPost_ReturnsRedirectToRouteResult() { RoleController roleController = GetRoleController(); var userRole = new UserRole(); roleController.Add(userRole).Should().BeOfType<RedirectToRouteResult>(); }
public async Task CreateAsync(UserRole role) { if(role == null) throw new ArgumentNullException("role"); await Task.Run(() => _userRoleRepository.Insert(role)); }
public bool IsAuthorized(IRequestContext requestContext, IUserProvider userProvider, UserRole userRole) { if (userRole == UserRole.None) { userRole = UserRole.ReadOnly; } string userName = requestContext.UserName, password = requestContext.Password; if (userName == null || password == null) { return false; } var ip = GetIp(true); /* if (ip != requestContext.ClientId) { return false; } * */ HttpContext.Current.Trace.Write("requestContext.ClientId = " + requestContext.ClientId); HttpContext.Current.Trace.Write("ip = " + ip); var result = userProvider.Validate(userName, password); return result != null && result.Result; }
public ActionResult AddRole(UserRole role) { var client = new RestClient(ServerBaseUrl + "UserRoles/AddUserRole"); RestRequest request = new RestRequest(Method.POST); request.AddObject(role); int intt = client.Execute<int>(request).Data; return RedirectToAction("AllRoles"); }
public static IUser Update(DBCommand cmd, IUser instance, string name, string password, UserRole? role) { instance.Name = name; instance.Password = password; instance.Role = role; return cmd.Update("User", instance); }
public void RoleController_AddPost_ShouldCallAddRoleWithPassedRole() { RoleController roleController = GetRoleController(); var userRole = new UserRole {Name = "test"}; roleController.Add(userRole); A.CallTo(() => roleService.AddRole(userRole)).MustHaveHappened(); }
// ADD YOUR COMPONENTS HERE public MainPage(IKernel ninjectKernel, UserRole userRole /*ENTER NEEDED BUSINESS COMPONENTS HERE*/) { _ninjectKernel = ninjectKernel; _userRole = userRole; InitializeComponent(); this.WindowTitle = windowTitle; }
public bool IsRole(UserRole role) { if (Role == UserRole.Illegal || role == UserRole.Illegal) { return Role == role; } return Role >= role; }
public User(string firstName, string lastName, string password, UserRole role, string username) { FirstName = firstName; LastName = lastName; Password = password; Role = role; Username = username; }
public User(string uname, string passwd, UserRole role) { Username = uname; Password = passwd; Role = role; }
public int Update(UserRole userRole) { _context.Entry(userRole).State = EntityState.Modified; return(_context.SaveChanges()); }
public UpdateInternalUserRole(string userId, UserRole role) { UserId = userId; Role = role; }
public TestUserContext(Guid userId, string emailAddress, string userName, string jobTitle, UserRole roles) : this(new UserAccount() { Id = userId, Name = userName, JobTitle = jobTitle, EmailAddress = emailAddress, Roles = roles }) { }
public IsInRole(UserRole accountRole) { AccountRole = accountRole; }
private void BuildTestData() { var tuple = NeedsConfiguredCurrentUser(); CurrentUser = tuple.Item1; orgmember1 = tuple.Item2; org1 = tuple.Item3; var roleSA = AddEntity <AppDbContext, Role>(new Role { RoleName = RoleName.SuperAdmin }); var roleOA = AddEntity <AppDbContext, Role>(new Role { RoleName = RoleName.OrganizationAdmin }); var roleAB = AddEntity <AppDbContext, Role>(new Role { RoleName = RoleName.AppBuilder }); user1 = AddEntity <AppDbContext, User>(new User { ExternalId = "test-auth0-id1", Email = "*****@*****.**", Name = "Test Testenson1", GivenName = "Test1", FamilyName = "Testenson1", Locale = "en-US", EmailNotification = true }); user2 = AddEntity <AppDbContext, User>(new User { ExternalId = "test-auth0-id2", Email = "*****@*****.**", Name = "Test Testenson2", GivenName = "Test1", FamilyName = "Testenson2", Locale = "en-US", EmailNotification = false }); org2 = AddEntity <AppDbContext, Organization>(new Organization { OwnerId = CurrentUser.Id, Name = "Kalaam Media" }); orgmember2 = AddEntity <AppDbContext, OrganizationMembership>(new OrganizationMembership { UserId = user1.Id, OrganizationId = org1.Id }); orgmember3 = AddEntity <AppDbContext, OrganizationMembership>(new OrganizationMembership { UserId = user1.Id, OrganizationId = org2.Id }); ur1 = AddEntity <AppDbContext, UserRole>(new UserRole { UserId = CurrentUser.Id, OrganizationId = org1.Id, RoleId = roleSA.Id }); ur2 = AddEntity <AppDbContext, UserRole>(new UserRole { UserId = user1.Id, OrganizationId = org1.Id, RoleId = roleOA.Id }); ur3 = AddEntity <AppDbContext, UserRole>(new UserRole { UserId = CurrentUser.Id, OrganizationId = org2.Id, RoleId = roleSA.Id }); ur4 = AddEntity <AppDbContext, UserRole>(new UserRole { UserId = user2.Id, OrganizationId = org2.Id, RoleId = roleOA.Id }); var notificationParm = new { orgName = "SIL International", url = "http://gtis.guru.com:8443", token = "replace" }; var serializedParm = JsonConvert.SerializeObject(notificationParm); notification1 = AddEntity <AppDbContext, Notification>(new Notification { MessageId = "buildengineConnected", MessageSubstitutionsJson = serializedParm, Message = "Build Engine for organization SIL International status change: connected", UserId = user1.Id, SendEmail = true }); }
public void OnSaveStrategy(UserRole role) { _controller.SendRequestUpdateRole(role); }
public RoleRequirement(UserRole role) { Role = role; }
private void BuildTestData(bool available = true) { CurrentUser = NeedsCurrentUser(); roleOA = AddEntity <AppDbContext, Role>(new Role { RoleName = RoleName.OrganizationAdmin }); roleSA = AddEntity <AppDbContext, Role>(new Role { RoleName = RoleName.SuperAdmin }); user1 = AddEntity <AppDbContext, User>(new User { ExternalId = "test-auth0-id1", Email = "*****@*****.**", Name = "Test Testenson1", GivenName = "Test1", FamilyName = "Testenson1" }); user2 = AddEntity <AppDbContext, User>(new User { ExternalId = "test-auth0-id2", Email = "*****@*****.**", Name = "Test Testenson2", GivenName = "Test2", FamilyName = "Testenson2" }); user3 = AddEntity <AppDbContext, User>(new User { ExternalId = "test-auth0-id3", Email = "*****@*****.**", Name = "Test Testenson3", GivenName = "Test3", FamilyName = "Testenson3" }); Environment.SetEnvironmentVariable("DEFAULT_BUILDENGINE_URL", "https://buildengine.testorg2"); Environment.SetEnvironmentVariable("DEFAULT_BUILDENGINE_API_ACCESS_TOKEN", "ReplaceAll"); org1 = AddEntity <AppDbContext, Organization>(new Organization { Name = "TestOrg1", WebsiteUrl = "https://testorg1.org", BuildEngineUrl = "https://buildengine.testorg1", BuildEngineApiAccessToken = "replace", UseDefaultBuildEngine = false }); org2 = AddEntity <AppDbContext, Organization>(new Organization { Name = "TestOrg2", WebsiteUrl = "https://testorg2.org", UseDefaultBuildEngine = true }); CurrentUserMembership = AddEntity <AppDbContext, OrganizationMembership>(new OrganizationMembership { UserId = CurrentUser.Id, OrganizationId = org1.Id }); organizationMembership1 = AddEntity <AppDbContext, OrganizationMembership>(new OrganizationMembership { UserId = user1.Id, OrganizationId = org1.Id }); organizationMembership2 = AddEntity <AppDbContext, OrganizationMembership>(new OrganizationMembership { UserId = user2.Id, OrganizationId = org1.Id }); organizationMembership3 = AddEntity <AppDbContext, OrganizationMembership>(new OrganizationMembership { UserId = user2.Id, OrganizationId = org2.Id }); organizationMembership4 = AddEntity <AppDbContext, OrganizationMembership>(new OrganizationMembership { UserId = user1.Id, OrganizationId = org2.Id }); group1 = AddEntity <AppDbContext, Group>(new Group { Name = "TestGroup1", Abbreviation = "TG1", OwnerId = org1.Id }); group2 = AddEntity <AppDbContext, Group>(new Group { Name = "TestGroup2", Abbreviation = "TG2", OwnerId = org2.Id }); groupMembership1 = AddEntity <AppDbContext, GroupMembership>(new GroupMembership { UserId = user1.Id, GroupId = group1.Id }); groupMembership2 = AddEntity <AppDbContext, GroupMembership>(new GroupMembership { UserId = user2.Id, GroupId = group1.Id }); groupMembership3 = AddEntity <AppDbContext, GroupMembership>(new GroupMembership { UserId = user2.Id, GroupId = group2.Id }); groupMembership4 = AddEntity <AppDbContext, GroupMembership>(new GroupMembership { UserId = user1.Id, GroupId = group2.Id }); type1 = AddEntity <AppDbContext, ApplicationType>(new ApplicationType { Name = "scriptureappbuilder", Description = "Scripture App Builder" }); project1 = AddEntity <AppDbContext, Project>(new Project { Name = "Test Project1", TypeId = type1.Id, Description = "Test Description", OwnerId = user1.Id, GroupId = group1.Id, OrganizationId = org1.Id, Language = "eng-US", IsPublic = true, WorkflowProjectUrl = "ssh://[email protected]/v1/repos/scriptureappbuilder-DEM-LSDEV-eng-US-English-Greek", WorkflowAppProjectUrl = "https://dev.scriptoria.io/projects/1" }); project2 = AddEntity <AppDbContext, Project>(new Project { Name = "Test Project2", TypeId = type1.Id, Description = "Test Description 2", OwnerId = user1.Id, GroupId = group2.Id, OrganizationId = org2.Id, Language = "eng-US", IsPublic = true, WorkflowProjectUrl = "ssh://[email protected]/v1/repos/scriptureappbuilder-DEM-LSDEV-eng-US-English-Greek", WorkflowAppProjectUrl = "https://dev.scriptoria.io/projects/2" }); systemStatus1 = AddEntity <AppDbContext, SystemStatus>(new SystemStatus { BuildEngineUrl = "https://buildengine.testorg1", BuildEngineApiAccessToken = "replace", SystemAvailable = available }); systemStatus2 = AddEntity <AppDbContext, SystemStatus>(new SystemStatus { BuildEngineUrl = "https://buildengine.testorg2", BuildEngineApiAccessToken = "ReplaceAll", SystemAvailable = available }); store1 = AddEntity <AppDbContext, Store>(new Store { Name = "wycliffeusa", Description = "Wycliffe USA Google Play Store" }); workflow1 = AddEntity <AppDbContext, WorkflowDefinition>(new WorkflowDefinition { Name = "TestWorkFlow", Enabled = true, Description = "This is a test workflow", WorkflowScheme = "Don't know what this is" }); productDefinition1 = AddEntity <AppDbContext, ProductDefinition>(new ProductDefinition { Name = "TestProd1", TypeId = type1.Id, Description = "This is a test product", WorkflowId = workflow1.Id }); product1 = AddEntity <AppDbContext, Product>(new Product { ProjectId = project1.Id, ProductDefinitionId = productDefinition1.Id, StoreId = store1.Id, WorkflowJobId = 1 }); product2 = AddEntity <AppDbContext, Product>(new Product { ProjectId = project1.Id, ProductDefinitionId = productDefinition1.Id, StoreId = store1.Id, WorkflowJobId = 2, WorkflowBuildId = 2 }); product3 = AddEntity <AppDbContext, Product>(new Product { ProjectId = project2.Id, ProductDefinitionId = productDefinition1.Id, StoreId = store1.Id, WorkflowJobId = 2, WorkflowBuildId = 2 }); ur1 = AddEntity <AppDbContext, UserRole>(new UserRole { UserId = user2.Id, RoleId = roleOA.Id, OrganizationId = org1.Id }); ur2 = AddEntity <AppDbContext, UserRole>(new UserRole { UserId = user3.Id, RoleId = roleSA.Id, OrganizationId = org1.Id }); ur3 = AddEntity <AppDbContext, UserRole>(new UserRole { UserId = user2.Id, RoleId = roleOA.Id, OrganizationId = org2.Id }); }
static void Main(string[] args) { Seed(); while (true) { if (_currentUser == null) { int loginChoice = _uiService.LogInMenu(); if (loginChoice == 1) { int roleChoice = _uiService.RoleMenu(); UserRole role = (UserRole)roleChoice; Console.Clear(); Console.WriteLine("Enter username:"******"Enter password:"******"Enter first name:"); newUser.FirstName = Console.ReadLine(); Console.WriteLine("Enter last name:"); newUser.LastName = Console.ReadLine(); Console.WriteLine("Enter username:"******"Enter password:"******"Train": int trainChoice = 1; if (_currentUser.Role == UserRole.Premium) { trainChoice = _uiService.TrainMenu(); } if (trainChoice == 1) { int trainingItem = _uiService.TrainMenuItems(_videoTrainings.GetTrainings()); VideoTraining training = _videoTrainings.GetTrainings()[trainingItem - 1]; Console.WriteLine(training.Title); Console.WriteLine($"Link: {training.Link}"); Console.WriteLine($"Raiting: {training.Rating}"); Console.WriteLine($"Time: {training.Time} minutes"); Console.ReadLine(); } if (trainChoice == 2) { int trainingItem = _uiService.TrainMenuItems(_liveTrainings.GetTrainings()); LiveTraining training = _liveTrainings.GetTrainings()[trainingItem - 1]; Console.WriteLine(training.Title); Console.WriteLine($"THE TRAINING STARTS AT: {training.NextSession}"); Console.WriteLine($"Raiting: {training.Rating}"); Console.WriteLine($"Time: {training.Time} minutes"); Console.ReadLine(); } break; case "Upgrade to Premium": break; case "Reschedule training": break; case "Account": break; case "Log Out": _currentUser = null; break; default: break; } } }
public static IUserContext Create(string emailAddress, string userName, string jobTitle, UserRole roles) { return(new TestUserContext(Guid.NewGuid(), emailAddress, userName, jobTitle, roles)); }
public void SaveRole(UserRole role) { _session.Transact(session => session.SaveOrUpdate(role)); }
//Check out static pre defined user dictionary to compare username - password pair. public static bool LogUserIn(string userName, string password, out UserRole role) { //prevent multi write on same object lock (PreUserDefinitions) { UserDefinition definiton = null; PreUserDefinitions.TryGetValue(userName, out definiton); if (definiton != null) { if (definiton.Password == password) { string sessionId = System.Web.HttpContext.Current.Session.SessionID; if (SessionUserPair.ContainsKey(sessionId)) { if (SessionUserPair[sessionId] != userName) { //user might be logged in with different account on the tabs of same browser //dont forget that we assigned PokeIn.Comet.CometSettings.MultiWindowsForSameSession = true; under SampleController.cs //so, it's possible to a session may contains many client ids inside //if the username is same for clientids its not a problem but if not string [] clientIds = null; try { //get full client id list under the same session List <string> clientIDS = PokeIn.Comet.CometWorker.GetClientIdsBySessionId(sessionId); //convert list to array because we need consistent list. the foreach loop below may change the state of List clientIds = clientIDS.ToArray(); } catch { } if (clientIds != null) { foreach (string clientId in clientIds) { BaseUserClass baseUser; PokeIn.Comet.CometWorker.GetClientObject(clientId, "User", out baseUser); if (baseUser == null) { PokeIn.Comet.CometWorker.GetClientObject(clientId, "Admin", out baseUser); } if (baseUser != null) { baseUser.Kicked = true; } PokeIn.Comet.CometWorker.RemoveClient(clientId); } } } SessionUserPair.Remove(sessionId); } SessionUserPair.Add(sessionId, userName); PreUserDefinitions[userName].SessionId = sessionId; role = PreUserDefinitions[userName].Role; return(true); } } } role = UserRole.None; return(false); }
protected override void Seed(MusicPortalDbContext context) { Genre ambientGenre = new Genre() { Name = "Ambient" }; Genre hiphopGenre = new Genre() { Name = "Hip-Hop" }; Genre instrumentalGenre = new Genre() { Name = "Instrumental" }; Genre soundtrackGenre = new Genre() { Name = "Soundtrack" }; Genre pianoGenre = new Genre() { Name = "Piano" }; context.Genres.AddRange(new List <Genre>() { ambientGenre, hiphopGenre, instrumentalGenre, soundtrackGenre, pianoGenre, new Genre() { Name = "Alternative" }, new Genre() { Name = "Blues" }, new Genre() { Name = "Background" }, new Genre() { Name = "Chanson" }, new Genre() { Name = "Classical" }, new Genre() { Name = "Club" }, new Genre() { Name = "Country" }, new Genre() { Name = "Dance" }, new Genre() { Name = "Disco" }, new Genre() { Name = "Drum & Bass" }, new Genre() { Name = "Electro" }, new Genre() { Name = "Folk" }, new Genre() { Name = "Funk" }, new Genre() { Name = "Hardcore" }, new Genre() { Name = "House" }, new Genre() { Name = "Industrial" }, new Genre() { Name = "Jazz" }, new Genre() { Name = "Metal" }, new Genre() { Name = "Minimal" }, new Genre() { Name = "Pop-Rock" }, new Genre() { Name = "Punk" }, new Genre() { Name = "Rap" }, new Genre() { Name = "Reggae" }, new Genre() { Name = "Retro" }, new Genre() { Name = "R&B" }, new Genre() { Name = "Rock" }, new Genre() { Name = "Soul" }, new Genre() { Name = "Techno" }, new Genre() { Name = "Trance" } }); UserRole authorized = new UserRole() { Name = "Admin" }; UserRole admin = new UserRole() { Name = "Authorized" }; context.UserRoles.AddRange(new List <UserRole>() { authorized, admin, new UserRole() { Name = "Authenticated" } }); var salt = CryptoService.GetRandomBytes(AppConstants.PASSOWORD_SALT_LENGTH).ToHexString(); context.Users.Add(new User() { Login = "******", Password = CryptoService.ComputeMD5Hash(Encoding.Unicode.GetBytes((salt + "admin"))).ToHexString(), Salt = salt, Roles = new List <UserRole>() { authorized, admin } }); context.Songs.Add(new Song() { Name = "Lo-fi chill cover OST", FileName = "ba814cc1-5de9-494c-b46e-c171e5fec6ab.mp3", Genres = new List <Genre>() { ambientGenre, hiphopGenre, soundtrackGenre } }); context.Songs.Add(new Song() { Name = "After Dark piano cover", FileName = "ceas4cc1-5de9-494c-b46e-c171e5feceas.mp3", Genres = new List <Genre>() { instrumentalGenre, pianoGenre } }); context.SaveChanges(); base.Seed(context); }
public async Task <int> DeleteUserRole(UserRole UserRole) { Context.UserRoles.Remove(UserRole); return(await SaveAll()); }
protected void Page_Load(object sender, EventArgs e) { Role = UserRole.IsoUser; LoadDepartment(1); }
internal static Task SetRolePermissions(IEnumerable <ChannelContext> channels, DiscordServerContext server, ChangedPermissions permissions, UserRole role) { return(_discordClient.RolesService.SetRolePermissions(channels, server, permissions, role)); }
public AuthAttribute(UserRole allowedRole) { allowedRole = AllowedRoles; }
public async Task <AuthResponse> Register(User user, PersonalInformation profile, Company company, string password) { using (var _context = _dbcontext()) { var is_user = await _context.Users.FirstOrDefaultAsync(x => x.Email == user.Email); if (is_user != null) { return(new AuthResponse("User Already Exist")); } byte[] passwordHash, passwordSalt; CreatePasswordHash(password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; using (var transaction = _context.Database.BeginTransaction()) { try { _context.Companies.Add(company); await _context.SaveChangesAsync(); List <Permission> permission = new List <Permission>(); string[] doc_type = { "User", "Role", "Unit", "Department", "Branch" }; for (int i = 0; i < doc_type.Length; i++) { permission.Add( new Permission { DocumentType = doc_type[i], DocumentAccessLevel = 0, Create = true, Read = true, Update = true, Delete = true, Upload = true, Download = true, Amend = true, Cancel = true, Approval = true, SetPermission = true, CompanyId = company.CompanyId, DateCreated = DateTime.Now } ); } //_context.Permissions.AddRange(permission); //int records = await _context.SaveChangesAsync(); var role = new Role { RoleName = "Owner", Description = "Full Access", CompanyId = company.CompanyId, DateCreated = DateTime.Now }; //List<RolePermission> rolepermission = new List<RolePermission>(); foreach (Permission perm in permission) { var roleperm = new RolePermission { Roles = role, Permissions = perm, CompanyId = company.CompanyId, DateCreated = DateTime.Now }; _context.RolePermissions.Add(roleperm); } ; await _context.SaveChangesAsync(); user.CompanyId = company.CompanyId; _context.Users.Add(user); await _context.SaveChangesAsync(); //_context.Roles.Add(role); //await _context.SaveChangesAsync(); var UserRole = new UserRole { Users = user, Roles = role, CompanyId = company.CompanyId, DateCreated = DateTime.Now }; _context.UserRoles.Add(UserRole); await _context.SaveChangesAsync(); profile.UserId = user.UserId; _context.PersonalInformation.Add(profile); await _context.SaveChangesAsync(); transaction.Commit(); return(new AuthResponse(user)); } catch (Exception ex) { transaction.Rollback(); return(new AuthResponse(ex.Message)); } } } }
// GET api/values public object Get(string apiAuthToken) { ConfigurationDTO configurationDTO = new ConfigurationDTO(); List <User> userMatches = IUserService.GetDataByPropertyName(nameof(Utility.User.ApiAuthToken), apiAuthToken, true, 0, 0, false); User user = new Utility.User(); if (userMatches.Count > 0) { user = userMatches.FirstOrDefault(); if (user != null) { if (user.Status == 0) { configurationDTO.isSuccess = false; configurationDTO.responseMsg = "User not active"; configurationDTO.user = null; configurationDTO.branch = null; return(configurationDTO); } else { UserRole userRole = IUserRoleService.GetSingle(user.UserRoleId); if (user.BranchId == 0 && userRole.Name == "Super Admin") { configurationDTO.isSuccess = true; configurationDTO.responseMsg = "SA"; configurationDTO.user = user; configurationDTO.branch = null; return(configurationDTO); } else if (user.BranchId == 0 && userRole.Name == "HQ Admin") { configurationDTO.isSuccess = true; configurationDTO.responseMsg = "HQ Admin"; configurationDTO.user = user; configurationDTO.branch = null; return(configurationDTO); } else if (user.BranchId == 0 && userRole.Name == "Regional Admin") { configurationDTO.isSuccess = true; configurationDTO.responseMsg = "Regional Admin"; configurationDTO.user = user; configurationDTO.branch = null; return(configurationDTO); } else { Branch branch = IBranchService.GetSingle(user.BranchId); if (branch.Status != 0) { List <Department> departments = new List <Department>(); if (branch.IsAll == 1) { departments = IDepartmentService.GetData(0, 0, false); } else { List <BranchDepartment> branchDepartments = IBranchDepartmentService.GetDataByFilter(" branch_id = '" + branch.Id + "' and status = '1'", 0, 0, false); departments = IDepartmentService.GetDataByFilter(" ID not in (" + String.Join(",", branchDepartments.Select(x => x.DepartmentId).ToArray()) + ") and status='1'", 0, 0, false); //departments.ForEach(x => //{ // //x.Status = branchDepartments.Where(y => y.DepartmentId == x.Id).FirstOrDefault().Status; // x.Status = 1; //}); } List <DepartmentUser> userDepartments = IDepartmentUserService.GetDataByFilter(" user_id = '" + user.Id + "' and status='1'", 0, 0, false); if (user.IsAll == 0) { departments = departments.Where(x => !(userDepartments.Select(y => y.DepartmentId).ToList().Contains(x.Id))).ToList(); } configurationDTO.isSuccess = true; configurationDTO.responseMsg = "Branch"; configurationDTO.user = user; configurationDTO.branch = branch; configurationDTO.departments = departments; user.LastSyncDate = DateTime.Now; IUserService.UpdateData(user); return(configurationDTO); } else { configurationDTO.isSuccess = false; configurationDTO.responseMsg = "Branch not active"; configurationDTO.user = null; configurationDTO.branch = null; return(configurationDTO); } } } } else { configurationDTO.isSuccess = false; configurationDTO.responseMsg = "User doesn't exist"; configurationDTO.user = null; configurationDTO.branch = null; return(configurationDTO); } } else { configurationDTO.isSuccess = false; configurationDTO.responseMsg = "User doesn't exist"; configurationDTO.user = null; configurationDTO.branch = null; return(configurationDTO); } }
/// <summary> /// /// </summary> /// <remarks>Updates the roles for a user</remarks> /// <param name="id">id of User to update</param> /// <param name="items"></param> /// <response code="200">OK</response> /// <response code="404">User not found</response> public virtual IActionResult UsersIdRolesPutAsync(int id, UserRoleViewModel[] items) { bool exists = _context.Users.Any(x => x.Id == id); if (exists && items != null) { User user = _context.Users .Include(x => x.District) .Include(x => x.GroupMemberships) .ThenInclude(y => y.Group) .Include(x => x.UserRoles) .ThenInclude(y => y.Role) .ThenInclude(z => z.RolePermissions) .ThenInclude(z => z.Permission) .First(x => x.Id == id); if (user.UserRoles == null) { user.UserRoles = new List <UserRole>(); } else { // existing data, clear it. foreach (var userRole in user.UserRoles) { if (_context.UserRoles.Any(x => x.Id == userRole.Id)) { UserRole delete = _context.UserRoles.First(x => x.Id == userRole.Id); _context.Remove(delete); } } user.UserRoles.Clear(); } foreach (var item in items) { // check the role id bool role_exists = _context.Roles.Any(x => x.Id == item.RoleId); if (role_exists) { // create a new UserRole based on the view model. UserRole userRole = new UserRole(); Role role = _context.Roles.First(x => x.Id == item.RoleId); userRole.Role = role; userRole.EffectiveDate = item.EffectiveDate; userRole.ExpiryDate = item.ExpiryDate; _context.Add(userRole); if (!user.UserRoles.Contains(userRole)) { user.UserRoles.Add(userRole); } } } _context.Update(user); _context.SaveChanges(); return(new StatusCodeResult(201)); } else { return(new StatusCodeResult(400)); } }
public static bool IsAuthorisedAtLevel(this IUserIdentity user, UserRole requiredRole) { return((int)user.Role >= (int)requiredRole); }
public User CreateUser(CreateUserWrapper user) { if (user == null || user.password_hash == "") { return(null); } try { User user_obj = _userRepository.GetAll().Where(p => p.email == user.email).FirstOrDefault(); UserPassword user_password = null; UserRole user_role = null; if (user_obj == null) { //creating objects user_obj = new User(); user_password = new UserPassword(); user_role = new UserRole(); //add information user_obj.email = user.email; user_obj.date_registration = DateTime.Now; //add user object to context user_obj = _userRepository.Add(user_obj); //commit _unitOfWork.Commit(); //add information to password object user_password.user_id = user_obj.id; user_password.passwrod_hash = user.password_hash; //add password object to context _userPasswordRepository.Add(user_password); //commit _unitOfWork.Commit(); //add role user_role.user_id = user_obj.id; // 1 - admin, 2 -moderator, 3 - user user_role.role_id = 3; user_role = _userRoleRepository.Add(user_role); //commit _unitOfWork.Commit(); return(user_obj); } else { return(null); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } }
bool HasPermission(UserRole role, UserPermission permission) { return((role.Permissions & permission) == permission); }
private void ShowHeroInfo() { if (_heroSlotSelected == null) { return; } UserRole userRole = _heroSlotSelected.userRole; if (userRole == null) { return; } uiHero.quality.mainTexture = Helper.LoadTextureElement((int)userRole.Base.ElemId); uiHero.icon.mainTexture = Helper.LoadTextureForHero(userRole.Base.RoleId); uiHero.starManager.SetStart(userRole.Base.Grade); uiHero.lblName.text = userRole.Name; uiHero.lblLevel.text = GameManager.localization.GetText("Global_Lvl") + userRole.Base.Level; uiHero.exp.value = (float)userRole.Base.Exp / (float)RoleConfig.LEVELS_EXP[userRole.Base.Level]; uiHero.energy.value = (float)userRole.Base.Energy / (float)RoleConfig.ENERGY_MAX; uiHero.expValue.text = userRole.Base.Exp + "/" + RoleConfig.LEVELS_EXP[userRole.Base.Level]; uiHero.energyValue.text = userRole.Base.Energy + "/" + RoleConfig.ENERGY_MAX; uiHero.inBattle.value = userRole.Base.Status == RoleStatus.Active; uiHero.skillDef.transform.Find("Texture").GetComponent <UITexture>().mainTexture = Helper.LoadTextureForSkill(userRole.RoleSkills[0].SkillId); uiHero.skill1.transform.Find("Texture").GetComponent <UITexture>().mainTexture = Helper.LoadTextureForSkill(userRole.RoleSkills[1].SkillId); uiHero.skill2.transform.Find("Texture").GetComponent <UITexture>().mainTexture = Helper.LoadTextureForSkill(userRole.RoleSkills[2].SkillId); uiHero.biography.text = ""; uiHero.element.spriteName = Helper.GetSpriteNameOfElement(userRole.Base.ElemId); uiHero.roleClass.spriteName = Helper.GetSpriteNameOfRoleClass(userRole.Base.Class); UserItem ring = userRole.RoleItems.FirstOrDefault(p => p.RoleUId == userRole.Id && p.GameItem.Kind == (int)ItemKind.Ring); UserItem armor = userRole.RoleItems.FirstOrDefault(p => p.RoleUId == userRole.Id && p.GameItem.Kind == (int)ItemKind.Armor); UserItem support = userRole.RoleItems.FirstOrDefault(p => p.RoleUId == userRole.Id && p.GameItem.Kind == (int)ItemKind.Support); UserItem medal = userRole.RoleItems.FirstOrDefault(p => p.RoleUId == userRole.Id && p.GameItem.Kind == (int)ItemKind.Medal); ShowEquipItem(ring, uiHero.ring); ShowEquipItem(armor, uiHero.armor); ShowEquipItem(support, uiHero.support); ShowEquipItem(medal, uiHero.medal); CloseSkillWindow(); if (GameManager.GameUser.HireRoles.Count > 0) { UserRoleHire hireRole = GameManager.GameUser.HireRoles.FirstOrDefault(p => p.Id == userRole.Id); if (hireRole != null) { uiHireHero.txtGold.value = hireRole.HireGold.ToString(); uiHireHero.txtSilver.value = hireRole.HireSilver.ToString(); if (hireRole.HireMode != 0) { uiHireHero.togAcceptToHire.value = true; } else { uiHireHero.togAcceptToHire.value = false; } } else { uiHireHero.txtGold.value = "0"; uiHireHero.txtSilver.value = "0"; uiHireHero.togAcceptToHire.value = false; } } }
public void Add(UserRole userRole) { _context.UserRoles.Add(userRole); _context.SaveChanges(); }
public UserRole DeleteUserRole(UserRole userRole) { _context.UserRoles.Remove(userRole); _context.SaveChanges(); return(userRole); }
/// <summary> /// 查询当前单位最大有效的菜单数据 /// </summary> /// <param name="website">网站</param> public object QueryCompanyValidMenus(Website website) { UserRole userrole = GetUserRoles(this.CurrentCompany); return(ConstructMenuViews(PermissionService.QueryPermissionOfCompany(this.CurrentCompany.CompanyId, userrole, website))); }
private void UploadUserRole(UserRole userRole) { var resource = LoadResource(_repository.UserRoles, userRole.Identifier).UpdateWith(userRole); Upsert(_repository.UserRoles, resource); }
/// <summary> /// Initializes a new instance of the <see cref="ChoicePrincipal" /> class. /// </summary> /// <param name="identity">The identity.</param> /// <param name="role">The role.</param> public Principal(IIdentity identity, UserRole role) { Identity = identity; _role = role; }