public static void Main(string[] args) { var tmp = CreateHostBuilder(args).Build(); UserRoleCache.Init(); tmp.Run(); }
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 IActionResult QueryUserChemicals() { var certification = HttpContext.Request.Headers["certification"]; var success = UserRoleCache.TryGetUserRole(certification, out var userRole); if (!success) { return(NotFound("try again")); } int userid = userRole.User.UserId; _logger.LogInformation("query chemicals of user id: {1}", userid); try { var response = HttpWrapper.CallServiceByGet("/api/entity/user/chemicals", $"userid={userid}"); if (!response.IsSuccessCode) { return(NotFound("try again")); } var res = JsonSerializer.Deserialize <List <Chemical> >(response.Body); return(Ok(res)); } catch (JsonException) { return(BadRequest("internal error")); } catch (Exception) { return(NotFound("try again")); } }
private static Dictionary <string, string[]> StartUserSynchronization() { Dictionary <string, string[]> userRoles = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase); using (AdoDataConnection connection = new AdoDataConnection("systemSettings")) using (UserRoleCache userRoleCache = UserRoleCache.GetCurrentCache()) { TableOperations <UserAccount> userAccountTable = new TableOperations <UserAccount>(connection); foreach (UserAccount user in userAccountTable.QueryRecords()) { string userName = user.AccountName; string[] roles; if (userRoleCache.TryGetUserRole(userName, out roles)) { userRoles[userName] = roles; } } if (userRoles.Count > 0) { Interlocked.Exchange(ref s_latestSecurityContext, userRoles); s_synchronizeUsers.RunOnceAsync(); } } return(userRoles); }
public static string[] GetRolesForUser(string username) { if (username == null) { return(Array.Empty <string>()); } username = username.ToLowerInvariant(); if (!UserRoleCache.TryGetValue(username, out var rolesArray)) { rolesArray = Array.Empty <string>(); var roleNames = new List <string>(); var roles = SueetieDataProvider.LoadProvider().GetRoles(ApplicationName, username); if (roles != null) { foreach (var role in roles) { roleNames.Add(role); } UserRoleCache[username] = rolesArray = roleNames.ToArray(); } } return(rolesArray); }
public IActionResult QueryLabChemicals() { var certification = HttpContext.Request.Headers["certification"]; var success = UserRoleCache.TryGetUserRole(certification, out var userRole); if (!success) { return(NotFound("try again")); } int labId = userRole.User.LabId; try { var response = RpcWrapper.CallServiceByGet("/api/entity/chemicals", $"labId={labId}"); if (!response.IsSuccessCode) { return(NotFound("try again")); } var res = JsonSerializer.Deserialize <List <Chemical> >(response.Body); return(Ok(res)); } catch (JsonException) { return(BadRequest("internal error")); } catch (Exception) { return(NotFound("try again")); } }
public IActionResult QueryWorkFlows() { var certification = HttpContext.Request.Headers["certification"]; var success = UserRoleCache.TryGetUserRole(certification, out var userRole); if (!success) { return(NotFound("try again")); } int userId = userRole.User.UserId; try { var response = HttpWrapper.CallServiceByGet("/api/entity/workflows", $"id={userId}", $"type=userid"); if (!response.IsSuccessCode) { return(NotFound("try again")); } var res = JsonSerializer.Deserialize <List <WorkFlow> >(response.Body); return(Ok(res)); } catch (JsonException) { return(BadRequest("internal error")); } catch (Exception) { return(NotFound("try again")); } }
public IActionResult GetNotifyMessages() { var certification = HttpContext.Request.Headers["certification"]; var success = UserRoleCache.TryGetUserRole(certification, out var userRole); if (!success) { return(NotFound("try again")); } int userId = userRole.User.UserId; try { var response = RpcWrapper.CallServiceByGet("/api/entity/notify", $"userid={userId}"); if (!response.IsSuccessCode) { return(NotFound("try again")); } var res = JsonSerializer.Deserialize <NotifyResult>(response.Body); return(Ok(res)); } catch (JsonException) { return(BadRequest("internal error")); } catch (Exception) { return(NotFound("try again")); } }
public BaseUserRepository(IDbContextCore dbContext, IBaseUserRoleMapRepository baseUserRoleMapRepository, IBasePermissionUserRepository basePermissionUserRepository, IBasePermissionRoleRepository basePermissionRoleRepository) : base(dbContext) { _baseUserRoleMapRepository = baseUserRoleMapRepository; _basePermissionRoleRepository = basePermissionRoleRepository; _basePermissionUserRepository = basePermissionUserRepository; _userRoleCache = new UserRoleCache(baseUserRoleMapRepository); _cache = new Base_UserModelCache(this); }
public IActionResult ReadStatusChange([FromBody] NotifyUpdateParam param) { var certification = HttpContext.Request.Headers["certification"]; if (UserRoleCache.TryGetUserRole(certification, out var userRole)) { param.UserId = userRole.User.UserId; try { var response = RpcWrapper.CallServiceByPost("/api/entity/notify", JsonSerializer.Serialize(param)); return(Ok()); } catch (Exception) { return(NotFound("try again")); } } return(Unauthorized()); }
public void OnAuthorization(AuthorizationFilterContext context) { //If the Authorization header is empty or null //then return Unauthorized string header = context.HttpContext.Request.Headers["certification"]; if (string.IsNullOrEmpty(header)) { context.Result = new UnauthorizedObjectResult("headers don't include certification"); return; } else { //call the cache to check the certification, which means the user is logined if (UserRoleCache.TryGetUserRole(header, out UserRoleResult result)) { // everytime user make some move, update the expire time. UserRoleCache.UpdateUserRole(header); if (string.IsNullOrEmpty(Role)) { return; } var list = Role.Split(',').ToHashSet(); foreach (var role in result.Roles) { if (list.Contains(role.RoleName)) { // matches, let go. return; } } context.Result = new UnauthorizedObjectResult("Insufficient permissions"); return; } else { context.Result = new RedirectResult("/account/login"); return; } } }
public IActionResult RejectDeclear([FromBody] SolveFormParam param) { if (UserRoleCache.TryGetUserRole(HttpContext.Request.Headers["certification"], out UserRoleResult result)) { if (!result.Roles.Exists(r => r.LabId == param.LabId)) { return(Unauthorized()); } } try { HttpWrapper.CallServiceByPost("/api/declaration/reject", JsonSerializer.Serialize(param)); return(Ok()); } catch (Exception e) { _logger.LogError(e.Message); return(NotFound(e.Message)); } }
public IActionResult Logout([FromBody] LogoutParam param) { var certification = HttpContext.Request.Headers["certification"]; if (!UserRoleCache.TryGetUserRole(certification, out var userRole)) { return(Ok()); } var user = userRole.User; // 二次校验,防止利用奇怪的方法把别人踢下线 if (user.UserName == param.UserName && user.UserPassword == param.Password) { UserRoleCache.RemoveUserRoleFromCache(certification); return(Ok()); } else { return(BadRequest()); } }
private static Dictionary <string, string[]> StartUserSynchronization(string currentUserName) { Dictionary <string, string[]> userRoles = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase); using (AdoDataConnection connection = new AdoDataConnection("systemSettings")) using (UserRoleCache userRoleCache = UserRoleCache.GetCurrentCache()) { TableOperations <UserAccount> userAccountTable = new TableOperations <UserAccount>(connection); string[] roles; foreach (UserAccount user in userAccountTable.QueryRecords()) { string userName = user.AccountName; if (userRoleCache.TryGetUserRole(userName, out roles)) { userRoles[userName] = roles; } } // Also make sure current user is added since user may have implicit rights based on group if (!string.IsNullOrEmpty(currentUserName)) { if (!userRoles.ContainsKey(currentUserName) && userRoleCache.TryGetUserRole(currentUserName, out roles)) { userRoles[currentUserName] = roles; } } if (userRoles.Count > 0) { Interlocked.Exchange(ref s_latestSecurityContext, userRoles); s_manualSynchronization = true; s_synchronizeUsers.RunOnceAsync(); } } return(userRoles); }
public IActionResult Login([FromForm] string username, [FromForm] string password) { _logger.LogInformation("Username: {username} try login.", username); try { if (HttpContext.Request.Headers.ContainsKey("certification")) { var ifcertification = HttpContext.Request.Headers["certification"]; if (UserRoleCache.TryGetUserRole(ifcertification, out var userRole)) { if (username == userRole.User.UserName) { var ret = new LoginReturn { Success = true, User = userRole.User, Roles = userRole.Roles, Certification = ifcertification }; return(Ok(ifcertification)); } else { UserRoleCache.RemoveUserRoleFromCache(ifcertification); } } } _logger.LogInformation("Call RpcWrapper, method: get."); _logger.LogInformation("port: {port}", RpcWrapper.Port); var response = RpcWrapper.CallServiceByGet( "/api/userrole", $"username={username}"); if (!response.IsSuccessCode) { return(Ok(new LoginReturn { Success = false })); } var result = JsonSerializer.Deserialize <UserRoleResult>(response.Body); if (password == result.User.UserPassword) { string certification = Guid.NewGuid().ToString(); var ret = new LoginReturn { Success = true, User = result.User, Roles = result.Roles, Certification = certification }; //UserRoleCache.AddUserRoleToCache(certification, result); //return Ok(certification); // For easy debug ret.Certification = "123"; UserRoleCache.AddUserRoleToCache("123", result); return(Ok(ret)); } return(Ok(new LoginReturn { Success = false })); } catch (Exception e) { // not sure if this should be write here _logger.LogError(e.Message); _logger.LogError("Call database_connector failed."); return(Ok(new LoginReturn { Success = false })); } }