public async Task <IHttpActionResult> AddNew([FromBody] RbacRegisterUser user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } RbacUser dbUser = new RbacUser(user.UserName); if (dbUser != null) { return(BadRequest(string.Format("User '{0}' already exists!", user.UserName))); } RbacRole role = new RbacRole(user.RoleId); if (role == null) { return(BadRequest(string.Format("Role id '{0}' not found!", user.RoleId))); } RbacUser newUser = Rbac.CreateUser(user.UserName, user.FullName, user.Email, user.Password, role); if ((newUser != null) && (newUser.UserId > 0)) { return(Ok()); } return(BadRequest("Cannot create user!")); }
/// <summary> /// 初始化开发者 /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> public static async Task InitializeDefaultDeveloperResource(IServiceProvider serviceProvider) { var context = serviceProvider.GetRequiredService <AppDbContext>(); // 删除数据库 await context.Database.EnsureDeletedAsync(); // 确认数据库已经创建 await context.Database.EnsureCreatedAsync(); // 加入菜单 await context.Menus.AddRangeAsync(allMenus); var adminRole = new RbacRole { Id = 1, Code = "admin", NormalizedName = "admin", Name = "admin", Menus = allMenus, Permissions = new List <Permission> { } }; var userRoles = new RbacRole { Id = 2, Code = "user", NormalizedName = "user", Name = "user", Menus = allMenus.Where(m => m.Id < 900).ToList() }; await context.Permissions.AddRangeAsync(allPermissions); userRoles.Permissions = allPermissions; adminRole.Permissions = allPermissions; if (!await context.Roles.AnyAsync()) { await context.Roles.AddAsync(adminRole); await context.Roles.AddAsync(userRoles); await context.SaveChangesAsync(); } // 创建开发者公司 //await context.companys.AddAsync(new Company { id = 1, name = "开发者公司", status = CompanyStatus.Approve, code = "developer", description = "负责开发,运维不同公司的业务系统", menuIds = string.Join(",", allMenus.Select(m => m.id)) }); //await context.rbacRoles.AddAsync(new RbacRole { id = 1, name = "开发者", companyId = 1, menuIds = string.Join(",", allMenus.Select(m => m.id)) }); //await context.rbacMenus.AddRangeAsync(allMenus); // 创建丁丁公司 //await context.companys.AddAsync(new Company { id = 2, name = "钉钉公司", status = CompanyStatus.Approve, code = "dingding", description = "钉钉群扫描", menuIds = string.Join(",", dingdingMenus.Select(m => m.id)) }); //await context.rbacRoles.AddAsync(new RbacRole { id = 200, name = "钉钉管理员", companyId = 2, menuIds = string.Join(",", dingdingMenus.Select(m => m.id)) }); if (!await context.Users.AnyAsync()) { var userStore = serviceProvider.GetRequiredService <UserManager <RbacUser> >(); // 初始化开发者 var result = await userStore.CreateAsync(new RbacUser { Email = "13419597065", UserName = "******", nickname = "刺月无影", roleId = 1, companyId = 1 }, "Shadow2016.."); var admin = await userStore.FindByNameAsync("13419597065"); await userStore.AddToRoleAsync(admin, "admin"); var result2 = await userStore.CreateAsync(new RbacUser { Email = "user", UserName = "******", nickname = "用户", roleId = 1, companyId = 1 }, "Shadow2016.."); var user = await userStore.FindByNameAsync("user"); await userStore.AddToRoleAsync(user, "user"); } await context.SaveChangesAsync(); }
public async Task <IHttpActionResult> Register([FromBody] RbacRegisterUser user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (user.RbacId == 0) { return(BadRequest("Rbac id cannot be zero!")); } Rbac rbac = new Rbac(user.RbacId, ""); if (rbac == null) { return(BadRequest(string.Format("Rbac instance with rbac id '{0}' not found!", user.RbacId))); } RbacRole role = new RbacRole(user.RoleId); if (role == null) { return(BadRequest(string.Format("Role id '{0}' not found!", user.RoleId))); } RbacUser newUser = rbac.CreateUser(user.UserName, user.FullName, user.Email, user.Password, role); if ((newUser != null) && (newUser.UserId > 0)) { return(Ok()); } return(BadRequest("Cannot create user!")); }
public void GetSample(Rbac rbac) { string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rbac.Name + "_sample_role.xml"); RbacRole.GetSample(rbac).Export(fileName); WriteColor(ConsoleColor.Green, fileName + " exported." + Environment.NewLine); }
public void CheckAccess_WithOperation_ReturnFalse_Test() { var role = new RbacRole("testRole", new IRbacOperation[] { new RbacOperation("op1"), new RbacOperation("op2") }); Assert.IsFalse(role.CheckAccess("Fake")); }
public void CreateNew(Rbac rbac, Options options) { string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, options.FileName); RbacRole role = rbac.ImportRole(fileName); Console.WriteLine(); WriteColor(ConsoleColor.Green, "Role from " + fileName + " imported into " + rbac.Name + ". The role id is:" + role.RoleId + "." + Environment.NewLine); }
public RbacRoleWeb Get(string name) { RbacRole role = Rbac.GetRole(name); if (role != null) { role.ParseMetaData(); return(new RbacRoleWeb(role)); } return(null); }
public RbacRoleWeb Get(int id) { RbacRole role = Rbac.GetRole(id); if (role != null) { role.ParseMetaData(); return(new RbacRoleWeb(role)); } return(null); }
public void CheckAccess_WithTasks_ReturnFalse_Test() { var role = new RbacRole("testRole", Enumerable.Empty <IRbacOperation>(), new IRbacTask[] { new RbacTask("t1", new RbacOperation("op2"), new BizRule(_ => !string.IsNullOrEmpty(_["id"]))) }); Assert.IsFalse(role.CheckAccess("t3", new Dictionary <string, string>() { { "id", "test" } })); }
public void CheckAccess_WithRoles3_ReturnTrue_Test() { var role = new RbacRole("testRole", Enumerable.Empty <IRbacOperation>(), Enumerable.Empty <IRbacTask>(), new IRbacRole[] { new RbacRole("r1"), new RbacRole("r2", new IRbacOperation[] { new RbacOperation("op1"), new RbacOperation("op2") }) }); Assert.IsTrue(role.CheckAccess("op1")); }
public void CheckAccess_WithRoles4_ReturnTrue_Test() { var role = new RbacRole("testRole", Enumerable.Empty <IRbacOperation>(), Enumerable.Empty <IRbacTask>(), new IRbacRole[] { new RbacRole("r1"), new RbacRole("r2", Enumerable.Empty <IRbacOperation>(), new IRbacTask[] { new RbacTask("t1", new RbacOperation("op2"), new BizRule(_ => _["id"] == "id1")) }) }); Assert.IsTrue(role.CheckAccess("t1", new Dictionary <string, string>() { { "id", "id1" } })); }
private void InsertRoles(Rbac rbac) { string path = Path.Combine(_rootDir, "Books"); string entitlements = File.ReadAllText(Path.Combine(_rootDir, "Books", "entitlement.xml")); string[] roleFiles = Directory.GetFiles(path, "role_*.xml"); foreach (string roleFile in roleFiles) { string strRle = File.ReadAllText(roleFile); string strDescription = File.ReadAllText(Path.Combine(Path.GetDirectoryName(roleFile), Path.GetFileNameWithoutExtension(roleFile) + ".txt")); RbacRole role = rbac.CreateRole(Path.GetFileNameWithoutExtension(roleFile) , strDescription, strRle, entitlements); roles.Add(role); } }
public async Task <IHttpActionResult> Update([FromBody] RbacRegisterUser user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } RbacRole role = new RbacRole(user.RoleId); if (role == null) { return(BadRequest(string.Format("Role id '{0}' not found!", user.RoleId))); } Rbac.Save(user); return(Ok()); }
public async Task Revoke(CommandRequest request) { string roleName = (request.Arguments[2] ?? "").Trim(); string recievingUsername = (request.Arguments[3] ?? "").Trim(); if (roleName.Length == 0) { await request.WriteLine("Error: No role name specified!"); return; } if (recievingUsername.Length == 0) { await request.WriteLine("Error: No username specified!"); return; } User user = server.AccountManager.GetByName(recievingUsername); RbacRole roleToGrant = server.AccountManager.ResolveRole(roleName); if (user == null) { await request.WriteLine($"Error: No user with the the name {recievingUsername} could be found."); return; } if (roleToGrant == null) { await request.WriteLine($"Error: No role with the the name {roleName} could be found."); return; } if (!user.HasRole(roleToGrant)) { await request.WriteLine($"Error: {recievingUsername} doesn't have the role {roleToGrant.Name}."); return; } user.Roles.Remove(roleToGrant); await server.SaveUserData(); await request.WriteLine($"Ok: Role {roleToGrant.Name} removed from {user.Username} successfully."); }
public async Task Grant(CommandRequest request) { string roleName = (request.Arguments[2] ?? "").Trim(); string targetUsername = (request.Arguments[3] ?? "").Trim(); if (roleName.Length == 0) { await request.WriteLine("Error: No role name specified!"); return; } if (targetUsername.Length == 0) { await request.WriteLine("Error: No username specified!"); return; } User user = server.AccountManager.GetByName(targetUsername); RbacRole roleToGrant = server.AccountManager.ResolveRole(roleName); if (user == null) { await request.WriteLine($"Error: No user with the the name {targetUsername} could be found."); return; } if (roleToGrant == null) { await request.WriteLine($"Error: No role with the the name {roleName} could be found."); return; } if (user.HasRole(roleToGrant)) { await request.WriteLine($"Error: {targetUsername} already has the role {roleToGrant.Name}."); return; } user.Roles.Add(roleToGrant); await server.SaveUserData(); await request.WriteLine($"Ok: Role {roleToGrant.Name} added to {user.Username} successfully."); }
public void Setup() { Rbac rbac = new Rbac(); rbac = rbac.CreateNew("books", "books description", @"Data Source=LPT-03084856325\SQLEXPRESS;Initial Catalog=books;Integrated Security=True", File.ReadAllText(Path.Combine(_rootDir, "Books", "entitlement.xml"))); InsertRoles(rbac); GenericParserAdapter parser = new GenericParserAdapter(Path.Combine(_rootDir, "Books", "BooksUsers.csv")); parser.FirstRowHasHeader = true; DataTable table = parser.GetDataTable(); if (table.Rows.Count > 0) { foreach (DataRow dataRow in table.Rows) { RbacRole role = roles.Where(r => r.Name == dataRow["Role"].ToString()).SingleOrDefault(); if (role == null) { throw new Exception(dataRow["Role"].ToString() + " is not defined!"); } RbacUser user = Rbac.CreateUser(dataRow[0].ToString(), dataRow[1].ToString(), dataRow[2].ToString(), "password", role); if (role.Name == "role_city_mgr") { user.AddParameter("{CityNames}", "('New York','Charlotte')"); } else if (role.Name == "role_state_mgr") { user.AddParameter("{ShortNames}", "('NY','NC')"); } else if (role.Name == "role_country_mgr") { user.AddParameter("{CountryCodes}", "('IN','US')"); } } } }
private void cbRoles_SelectedIndexChanged(object sender, EventArgs e) { if (cbRoles.SelectedItem != null) { RbacRole dbRole = Rbac.GetRole(((RbacRole)cbRoles.SelectedItem).Name); RbacRoleWeb role = new RbacRoleWeb(dbRole); tabPage4.Text = role.Name; txtRole.Text = role.MetaDataRbac; txtEntitlements.Text = role.MetaDataEntitlements; role.MetaDataRbac = string.Empty; role.MetaDataEntitlements = string.Empty; propRole.SelectedObject = role; } else { tabPage4.Tag = null; tabPage4.Text = "Role"; } ParseInline(); }
private void InsertRoles(Rbac rbac) { string path = Path.Combine(_rootDir, "Books"); string[] roleFiles = Directory.GetFiles(path, "role_*.xml"); roleFiles = roleFiles.Where(rf => rf.Contains("_entitlement") == false).ToArray(); foreach (string roleFile in roleFiles) { string strRle = File.ReadAllText(roleFile); string onlyRoleFileName = Path.GetFileNameWithoutExtension(roleFile); string strDescription = File.ReadAllText(Path.Combine(Path.GetDirectoryName(roleFile), onlyRoleFileName + ".txt")); string strEntitlement = File.ReadAllText(Path.Combine(Path.GetDirectoryName(roleFile), onlyRoleFileName + "_entitlement.xml")); RbacRole role = rbac.CreateRole(Path.GetFileNameWithoutExtension(roleFile) , strDescription, strRle, strEntitlement); roles.Add(role); Console.Write("."); } }
public void Setup(Options options) { if (string.IsNullOrEmpty(options.ConnectionString)) { WriteErrorLine("Connection string is required. Please use -x <connection string>"); return; } Rbac rbac = new Rbac(); rbac = rbac.CreateNew("books", "books description", options.ConnectionString, File.ReadAllText(Path.Combine(_rootDir, "Books", "entitlement.xml"))); Console.Write("."); InsertRoles(rbac); GenericParserAdapter parser = new GenericParserAdapter(Path.Combine(_rootDir, "Books", "BooksUsers.csv")); parser.FirstRowHasHeader = true; DataTable table = parser.GetDataTable(); if (table.Rows.Count > 0) { foreach (DataRow dataRow in table.Rows) { RbacRole role = roles.Where(r => r.Name == dataRow["Role"].ToString()).SingleOrDefault(); if (role == null) { throw new Exception(dataRow["Role"].ToString() + " is not defined!"); } RbacUser user = Rbac.CreateUser(dataRow[0].ToString(), dataRow[1].ToString(), dataRow[2].ToString(), "password", role); if (role.Name == "role_city_mgr") { user.AddParameter("{CityNames}", "('New York','Charlotte')"); } else if (role.Name == "role_state_mgr") { user.AddParameter("{ShortNames}", "('NY','NC')"); } else if (role.Name == "role_country_mgr") { user.AddParameter("{CountryCodes}", "('IN','US')"); } if (role.Name == "role_guest_user") { user.AddParameter("{CityNames}", "('New York')"); } Console.Write("."); } } Console.WriteLine(); var rbacs = Rbac.GetRbacs(); if (rbacs != null) { WriteColor(ConsoleColor.Green, rbacs.Count + " rbac instance(s) created." + Environment.NewLine); } else { WriteErrorLine("rbac creation failed!"); } var vroles = Rbac.GetRoles(); if (vroles != null) { WriteColor(ConsoleColor.Green, vroles.Count + " role(s) created." + Environment.NewLine); } else { WriteErrorLine("role(s) creation failed!"); } var users = Rbac.GetUsers(); if (users != null) { WriteColor(ConsoleColor.Green, users.Count + " user(s) created." + Environment.NewLine); } else { WriteErrorLine("user(s) creation failed!"); } }
public string Get(int userId, string reqType) { DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>(); try { if (reqType == "loggedInUser") { RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser"); MasterDbContext masterDbContext = new MasterDbContext(connString); string userImgName = (from x in masterDbContext.Employees where x.EmployeeId == currentUser.EmployeeId select x.ImageName).FirstOrDefault(); EmployeeModel employee = (from x in masterDbContext.Employees where x.EmployeeId == currentUser.EmployeeId select x).FirstOrDefault(); string imgLocation = string.IsNullOrEmpty(userImgName) ? "" : fileUploadLocation + "UserProfile\\" + userImgName; //start: to get default route for current user. List <RbacRole> usrAllRoles = RBAC.GetUserAllRoles(currentUser.UserId); RbacRole defRole = usrAllRoles != null && usrAllRoles.Count > 0 ? usrAllRoles.OrderBy(r => r.RolePriority).FirstOrDefault() : null; int? defRouteId = defRole != null ? defRole.DefaultRouteId : 0; string defaultRoutePath = null; if (defRouteId.HasValue) { List <DanpheRoute> allRoutes = RBAC.GetAllRoutes(); DanpheRoute defRoute = allRoutes.Where(r => r.RouteId == defRouteId.Value).FirstOrDefault(); if (defRoute != null) { defaultRoutePath = defRoute.UrlFullPath; } } //end: to get default route for current user. //Ajay 07 Aug 2019 //getting LandingPageRouteId var landingPageRouteId = (new RbacDbContext(connString)).Users .Where(a => a.UserId == currentUser.UserId) .Select(a => a.LandingPageRouteId).FirstOrDefault(); responseData.Results = new { UserId = currentUser.UserId, UserName = currentUser.UserName, EmployeeId = currentUser.EmployeeId, Profile = new { ImageLocation = imgLocation }, NeedsPasswordUpdate = currentUser.NeedsPasswordUpdate, DefaultPagePath = defaultRoutePath, Employee = employee, LandingPageRouteId = landingPageRouteId }; responseData.Status = "OK"; } else if (reqType != null && reqType.ToLower() == "routelist") { RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser"); if (currentUser != null) { var currentUserId = currentUser.UserId; List <DanpheRoute> routeList = new List <DanpheRoute>(); //we need to get routes with defaultshow=false and no need of hierarchy. routeList = RBAC.GetRoutesForUser(currentUser.UserId, getHiearrchy: false); responseData.Results = routeList; responseData.Status = "OK"; //set session of Valid routeList for loggedin user HttpContext.Session.Set <List <DanpheRoute> >("validRouteList", routeList); } else { responseData.Status = "Failed"; responseData.ErrorMessage = "User is Not valid"; } } else if (reqType != null && reqType == "validallrouteList") { RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser"); if (currentUser != null) { var currentUserId = currentUser.UserId; List <DanpheRoute> routeList = new List <DanpheRoute>(); routeList = RBAC.GetRoutesForUser(currentUser.UserId, getHiearrchy: true); var filteredRoutes = routeList.Where(r => r.DefaultShow != false && r.IsActive == true).ToList(); filteredRoutes.ForEach(r => { if (r.ChildRoutes != null) { r.ChildRoutesDefaultShowCount = r.ChildRoutes.Where(c => c.DefaultShow == true).Count(); } else { r.ChildRoutesDefaultShowCount = 0; } }); responseData.Results = filteredRoutes; responseData.Status = "OK"; HttpContext.Session.Set <List <DanpheRoute> >("validallrouteList", filteredRoutes); } else { responseData.Status = "Failed"; responseData.ErrorMessage = "User is Not valid"; } } else if (reqType != null && reqType == "userPermissionList") { RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser"); List <RbacPermission> userPermissions = new List <RbacPermission>(); if (currentUser != null) { int currentUserId = currentUser.UserId; //get permissions of user userPermissions = RBAC.GetUserAllPermissions(currentUserId); //set session of valid user permission HttpContext.Session.Set <List <RbacPermission> >("userAllPermissions", userPermissions); responseData.Status = "OK"; } else { responseData.Status = "Failed"; responseData.ErrorMessage = "Invalid User."; } responseData.Results = userPermissions; } else if (reqType == "activeBillingCounter") { string activeCounterId = HttpContext.Session.Get <string>("activeBillingCounter"); int actCounterId; int.TryParse(activeCounterId, out actCounterId); responseData.Results = actCounterId; responseData.Status = "OK"; } else if (reqType == "activePharmacyCounter") { string activeCounterId = HttpContext.Session.Get <string>("activePharmacyCounter"); int actCounterId; int.TryParse(activeCounterId, out actCounterId); string activeCounterName = HttpContext.Session.Get <string>("activePharmacyCounterName"); PHRMCounter counter = new PHRMCounter(); counter.CounterId = actCounterId; counter.CounterName = activeCounterName; responseData.Results = counter; responseData.Status = "OK"; } } catch (Exception ex) { responseData.Status = "Failed"; responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString(); } var routelist = DanpheJSONConvert.SerializeObject(responseData, true); return(DanpheJSONConvert.SerializeObject(responseData, true)); }
public void CheckAccess_ReturnFalse_Test() { var role = new RbacRole("testRole"); Assert.IsFalse(role.CheckAccess("Fake")); }
public void TestBatch() { GenericParserAdapter genParser = new GenericParserAdapter(Path.Combine(_rootDir, "Books", "tests.csv")); genParser.FirstRowHasHeader = true; DataTable table = genParser.GetDataTable(); if (table.Columns["ParsedQueryStage1"] == null) { table.Columns.Add("ParsedQueryStage1"); table.Columns.Add("ParsedQuery"); table.Columns.Add("Records"); table.Columns.Add("Errors"); table.Columns.Add("TestResult"); } bool cleaned = false; foreach (DataRow row in table.Rows) { //if (row["Id"].ToString() == "11") // Debugger.Break(); Rbac rbac = new Rbac(row["User"].ToString()); RbacRole role = Rbac.GetRole(row["Role"].ToString()); if (!cleaned) { CleanDataFromDb(rbac.ConnectionString); cleaned = true; } SqlQueryParser parser = new SqlQueryParser(rbac); try { parser.Parse(row["Query"].ToString()); } catch (Exception ex) { row["Errors"] = ex.Message; if (row["Expected"].ToString().Equals(row["Errors"].ToString())) { row["TestResult"] = "Passed"; } else { row["TestResult"] = "Failed"; } continue; } row["ParsedQueryStage1"] = parser.ParsedQueryStage1; row["ParsedQuery"] = parser.ParsedQuery; row["Errors"] += parser.AllErrors; if (string.IsNullOrEmpty(parser.AllErrors)) { RbacSqlQueryEngine engine = new RbacSqlQueryEngine(parser, true); engine.Execute(); if (engine.IsErrored) { row["Records"] = "Errored"; } else if ((parser.QueryType == RbacQueryTypes.Select) && (engine.Table == null)) { row["Records"] = "Errored"; } else if ((parser.QueryType == RbacQueryTypes.Select) && (engine.Table != null)) { row["Records"] = engine.Table.Rows.Count + " record(s)"; } if (!string.IsNullOrEmpty(parser.AllErrors)) { row["Errors"] += parser.AllErrors + Environment.NewLine; } if (!string.IsNullOrEmpty(engine.AllErrors)) { row["Errors"] += engine.AllErrors + Environment.NewLine; } } if (row["Expected"].ToString().Equals(row["Errors"].ToString())) { row["TestResult"] = "Passed"; } else { row["TestResult"] = "Failed"; } CleanDataFromDb(rbac.ConnectionString); } string outFile = Path.Combine(_rootDir, "Books", "tests_result.csv"); table.ToCsv(outFile); WriteColor(ConsoleColor.Green, outFile + " is generated!"); Console.WriteLine(); ToCsvMarkdownFormat(table, Path.Combine(_rootDir, "Books", "tests_result.md")); }
public void CheckAccess_ReturnTrue_Test() { var role = new RbacRole("testRole"); Assert.IsTrue(role.CheckAccess("testRole")); }