public Workflow(TDataContext dbContext, TEntity entity, ApiIdentity identity, Func <WorkflowActivityContext> getEntryActivity) { this.DataContext = dbContext; this.Entity = entity; this.Identity = identity; //Determine current activity and load it in. if (entity.WorkFlowActivityID == null) { _isNew = true; //New, we don't have one, load the entry point. var dbActivityContext = getEntryActivity(); entity.WorkFlowActivityID = dbActivityContext.Activity.ID; entity.WorkflowID = dbActivityContext.WorkflowID; dbContext.SaveChanges(); this.ID = dbActivityContext.WorkflowID; } else { this.ID = entity.WorkflowID.Value; } WorkflowConfigurations.TryGetValue(this.ID, out CurrentWorkflowConfiguration); if (!CurrentWorkflowConfiguration.Activities.ContainsKey(entity.WorkFlowActivityID.Value)) { throw new ArgumentOutOfRangeException("The Workflow activity referenced by the entity could not be found."); } }
public void CreateDummyUsers() { var ident = new ApiIdentity(new Guid("2CBF97E0-FF50-496A-8F77-A57DA62DAC05"), "SystemAdministrator", "System Administrator"); HttpContext.Current.User = new GenericPrincipal(ident, new string[] { }); var orgID = new Guid("7C5B0001-7635-4AC4-8961-A2F9013FFC50"); var secGroupID = new Guid("7F180001-5B09-4EF5-8872-A2F9013FFC69"); using (var db = new DataContext()) { for (int i = 0; i < 1000; i++) { var newUser = new User { FirstName = "Dummy", LastName = "User", UserName = $"DummyUser{i}", Email = $"DummyUser{i}@test.com", PasswordHash = "SomeBadPassword123!$".ComputeHash(), Active = true, FailedLoginCount = 0, OrganizationID = orgID, }; db.Users.Add(newUser); db.SecurityGroupUsers.Add(new SecurityGroupUser { SecurityGroupID = secGroupID, UserID = newUser.ID }); db.SaveChanges(); } } }
static Dictionary <string, MethodInfo> index(Index <MethodInfo> methods) { var index = new Dictionary <string, MethodInfo>(); core.iter(methods, m => index.TryAdd(ApiIdentity.identify(m).IdentityText, m)); return(index); }
public override async Task <bool> CanDelete(DataContext db, ApiIdentity identity, params Guid[] keys) { return(await(from p in db.Filter(db.Projects, identity, PermissionIdentifiers.Project.ManageSecurity) join sg in db.SecurityGroups on p.ID equals sg.OwnerID where keys.Contains(sg.ID) select p.ID).AnyAsync() || await(from o in db.Filter(db.Organizations, identity, PermissionIdentifiers.Organization.ManageSecurity) join sg in db.SecurityGroups on o.ID equals sg.OwnerID where keys.Contains(sg.ID) select o.ID).AnyAsync() ); }
public static BllLoginUser ToBllLoginUser(this ApiIdentity item) { return(new BllLoginUser { Username = item.Username, Password = item.Password, }); }
public static IKickPrincipal GetPrincipal(string username, string password) { System.Diagnostics.Trace.WriteLine("GetPrincipal " + username + " : " + password); string securityToken = UserBR.AuthenticateUser(username, password); IIdentity identity = new ApiIdentity(username); return(new AuthenticatedKickPrincipal(identity, UserCache.GetUser(securityToken))); }
protected virtual TRequest CreateRequest <TRequest, TModel>(TModel data, ApiIdentity user = null) where TModel : SaveModelBase, new() where TRequest : RequestBase <TModel>, new() { return(new TRequest { Data = data, User = user ?? new ApiIdentity() }); }
public async Task <ResponseMessage <UserRole> > CanAssignRole(string role) { if (string.IsNullOrWhiteSpace(role)) { throw new ArgumentException($"'{nameof(role)}' cannot be null or whitespace.", nameof(role)); } if (!ApiIdentity.IsAuthenticated()) { return new ResponseMessage <UserRole> { Success = false, Message = "User not Authenticated" } } ; var authRoles = await GetRoles(ApiIdentity.GetUserName()).ConfigureAwait(false); if (authRoles.IsNullOrEmptyCollection()) { return new ResponseMessage <UserRole> { Success = false, Message = "Can not perform action, User has no Role." } } ; if (!Enum.TryParse(role, true, out RoleEnumType req)) { return new ResponseMessage <UserRole> { Success = false, Message = $"Can not perform action, {role} is not supported" } } ; HashSet <RoleEnumType> authEnums = new(); foreach (var item in authRoles) { if (Enum.TryParse(item.RoleName, true, out RoleEnumType cur) && cur != RoleEnumType.Unknown) { authEnums.Add(cur); } } var maxAuth = authEnums.HasAnyInCollection() ? authEnums.Max() : 0; if (maxAuth < req) { return new ResponseMessage <UserRole> { Success = false, Message = "Can not perform action, User has low privilages." } } ; return(new ResponseMessage <UserRole> { Success = true, Message = "Ok" }); }
public override async Task <bool> CanInsert(DataContext db, ApiIdentity identity, params User[] objs) { var organizationIDs = objs.Select(u => u.OrganizationID ?? Guid.Empty).ToArray(); var aclOrgs = db.OrganizationAcls.FilterAcl(identity, PermissionIdentifiers.Organization.CreateUsers).Where(a => organizationIDs.Contains(a.OrganizationID)); var aclGlobal = db.GlobalAcls.FilterAcl(identity, PermissionIdentifiers.Organization.CreateUsers); return((await aclOrgs.AnyAsync() && await aclOrgs.AllAsync(a => a.Allowed)) || (await aclGlobal.AnyAsync() && await aclGlobal.AllAsync(a => a.Allowed))); }
public IceClient(string apiKey, string apiSecret, bool ssl = true, string host = "api.icocryptex.io", ushort port = 443) { Identity = new ApiIdentity(apiKey, apiSecret); ApiUtility = new ApiUtil(host, port, ssl, this); Public = new PublicIceApi(this); Account = new AccountIceApi(this); Deposit = new DepositIceApi(this); Withdraw = new WithdrawIceApi(this); Order = new OrderIceApi(this); }
public UsersQueryTests() { HttpContext.Current = new HttpContext( new HttpRequest("", "https://tempuri.org", ""), new HttpResponse(new StringWriter()) ); //Set the current user _identity = new ApiIdentity(new Guid("2CBF97E0-FF50-496A-8F77-A57DA62DAC05"), "SystemAdministrator", "System Administrator"); HttpContext.Current.User = new GenericPrincipal(_identity, new string[] { }); }
public static BllIdentity ToBllIdentity(this ApiIdentity item) { return(new BllIdentity { Username = item.Username, Password = item.Password, Email = item.Email, FirstName = item.Username, LastName = item.Username, Gender = item.Gender }); }
public IHttpActionResult GetIdentity() { try { var identity = ApiIdentity.GetIdentity(Request); return(Ok(identity)); } catch (Exception ex) { return(BadRequest(ex.Message + " : " + ex.StackTrace)); } }
public ApiLoginResponse Register(ApiIdentity input) { int userId = _userService.Create(input.ToBllIdentity()); string token = _userService.LogIn(input.ToBllLoginUser()); return(new ApiLoginResponse { Succeeded = true, Username = input.Username, Token = token }); }
/// <summary> /// Adds a log item to TaskChangedLogs indicating the task was modified. /// </summary> /// <param name="identity">The identity to associate with the log item.</param> /// <param name="db">The datacontext.</param> /// <param name="optionalDescription">An optional description to use instead of the description generated by the ActionLogConfiguration.</param> /// <returns></returns> public async Task LogAsModifiedAsync(ApiIdentity identity, DataContext db, string optionalDescription = null) { var logger = new ActionLogConfiguration(); var logItem = await logger.CreateLogItemAsync(this, EntityState.Modified, identity, db); if (!string.IsNullOrWhiteSpace(optionalDescription)) { logItem.Description = optionalDescription; } this.TaskChangedLogs.Add(logItem); }
/// <summary> /// Initalizes a new instance of the <see cref="ChunkedMultipartFormDMCProvider"/> class /// </summary> /// <param name="rootDir">The Root Directory the file chunk is to be written to</param> /// <param name="request">The Request Context sent by the Upload Control</param> /// <param name="context">The DbContext</param> /// <param name="identity">The Api Identity of the User</param> public ChunkedMultipartFormDMCProvider(string rootDir, HttpRequest request, DataContext context, ApiIdentity identity) : base(rootDir) { DocumentMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject <dmc.Criteria.DocumentMetadata>(request.Params["metadata"]); if (DocumentMetadata.ID == Guid.Empty) { DocumentMetadata.ID = Utilities.DatabaseEx.NewGuid(); } _dataContext = context; _identity = identity; }
public override async Task <bool> CanInsert(DataContext db, ApiIdentity identity, params Project[] objs) { if (objs.Any(p => p.GroupID == null)) { return(false); } var groupIDs = objs.Select(p => p.GroupID.Value).ToArray(); var aclGroups = db.GroupAcls.FilterAcl(identity, PermissionIdentifiers.Group.CreateProjects).Where(g => groupIDs.Contains(g.GroupID)); var aclGlobal = db.GlobalAcls.FilterAcl(identity, PermissionIdentifiers.Group.CreateProjects); return((aclGlobal.Any() && aclGlobal.All(a => a.Allowed)) || (aclGroups.Any() && aclGroups.All(a => a.Allowed))); }
public VmTicketRepository( IAzureVmManagementService azureVmManagementService, IRepository <VmTicket> repository, AppVersionContext context, IVmSdkService vmSdkService, IConfiguration configuration, IApiIdentity apiIdentity) : base(context, apiIdentity) { _azureVmManagementService = azureVmManagementService; _repository = repository; _context = context; _vmSdkService = vmSdkService; _configuration = configuration; _userId = ApiIdentity.GetUserName(); VmRebootDelay = configuration.GetValue <int>("VmRebootDelay"); }
public ControllerTest() { //Set the current context HttpContext.Current = new HttpContext( new HttpRequest("", "https://tempuri.org", ""), new HttpResponse(new StringWriter()) ); //Set the current user var ident = new ApiIdentity(new Guid("96DC0001-94F1-47CC-BFE6-A22201424AD0"), "SystemAdministrator", "System Administrator"); HttpContext.Current.User = new GenericPrincipal(ident, new string[] { }); controller = new C(); controller.Request = new System.Net.Http.HttpRequestMessage(); controller.RequestContext = new System.Web.Http.Controllers.HttpRequestContext(); }
public async Task <CommunicationDetails> AddMessageToCommunication(string submitedSubscription, string supportTicketId, string subject, string body) { if (string.IsNullOrWhiteSpace(submitedSubscription)) { throw new ArgumentException($"'{nameof(submitedSubscription)}' cannot be null or whitespace.", nameof(submitedSubscription)); } if (string.IsNullOrWhiteSpace(supportTicketId)) { throw new ArgumentException($"'{nameof(supportTicketId)}' cannot be null or whitespace.", nameof(supportTicketId)); } if (string.IsNullOrWhiteSpace(subject)) { throw new ArgumentException($"'{nameof(subject)}' cannot be null or whitespace.", nameof(subject)); } if (string.IsNullOrWhiteSpace(body)) { throw new ArgumentException($"'{nameof(body)}' cannot be null or whitespace.", nameof(body)); } try { var apiToken = await base.ApiIdentity.GetAccessTokenForUserAsync(Scope); var cr = new Microsoft.Rest.TokenCredentials(apiToken); var msClient = new MicrosoftSupportClient(cr, HttpClientBase, true); msClient.SubscriptionId = submitedSubscription; var email = await ApiIdentity.GetCurrentUserEmail(); string name = null; name = StringHelper.RandomStringDate(20); var crNew = await msClient.Communications.CreateAsync(supportTicketId, name, new CommunicationDetails { Body = body, Sender = email, Subject = subject, }); return(crNew); } catch (Exception ex) { throw; } }
public AdoProjectAccessRepository( IConfiguration configuration, IRepository <AdoProjectAccess> repository, AdoContext context, //IAdoProjectHistoryRepository adoProjectHistoryRepository, IMapper mapper, ILogger <AdoProjectAccessRepository> logger, IMessageBus messageBus, IApiIdentity apiIdentity) : base(context, apiIdentity) { _repository = repository; _context = context; //_adoProjectHistoryRepository = adoProjectHistoryRepository; _mapper = mapper; _logger = logger; _messageBus = messageBus; _userId = ApiIdentity.GetUserName(); _serviceBusConfig = configuration.GetSection(nameof(ServiceBusConfig)).Get <ServiceBusConfig>(); }
public static bool CanViewIndividualResults(this DataContext db, ApiIdentity apiIdentity, Guid currentUserID, Guid requestID) { var organizationsAcls = db.OrganizationAcls.FilterAcl(apiIdentity, PermissionIdentifiers.Request.ViewIndividualResults, PermissionIdentifiers.DataMartInProject.SeeRequests); var projectsAcls = db.ProjectAcls.FilterAcl(apiIdentity, PermissionIdentifiers.Request.ViewIndividualResults); var usersAcls = db.UserAcls.FilterAcl(apiIdentity, PermissionIdentifiers.Request.ViewIndividualResults); var projectOrganizationsAcls = db.ProjectOrganizationAcls.FilterAcl(apiIdentity, PermissionIdentifiers.Request.ViewIndividualResults); var projectDataMartAcls = db.ProjectDataMartAcls.FilterAcl(apiIdentity, PermissionIdentifiers.DataMartInProject.SeeRequests); var dataMartAcls = db.DataMartAcls.FilterAcl(apiIdentity, PermissionIdentifiers.DataMartInProject.SeeRequests); var canViewIndividualResults = (from r in db.Requests let organization = organizationsAcls.Where(o => o.OrganizationID == r.OrganizationID) let project = projectsAcls.Where(p => p.ProjectID == r.ProjectID) let user = usersAcls.Where(u => u.UserID == currentUserID) let projectOrganization = projectOrganizationsAcls.Where(p => p.ProjectID == r.ProjectID && p.OrganizationID == r.OrganizationID) let projectDataMart = projectDataMartAcls.Where(a => a.ProjectID == r.ProjectID && r.DataMarts.Any(dm => dm.DataMartID == a.DataMartID)) let dataMart = dataMartAcls.Where(a => r.DataMarts.Any(dm => dm.DataMartID == a.DataMartID)) where r.ID == requestID && (organization.Any() || project.Any() || user.Any() || projectOrganization.Any() || projectDataMart.Any() || dataMart.Any()) && organization.All(a => a.Allowed) && project.All(a => a.Allowed) && user.All(a => a.Allowed) && projectOrganization.All(a => a.Allowed) && projectDataMart.All(a => a.Allowed) && dataMart.All(a => a.Allowed) select r).Any(); return(canViewIndividualResults); }
public async Task <ApiLoginResponse> Register(ApiIdentity input) { var user = new IdentityUser { UserName = input.Username, Email = input.Email }; IdentityResult result = await _userManager.CreateAsync(user, input.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); } else { throw new HttpStatusCodeException((int)HttpStatusCode.InternalServerError, result.Errors.First().Description); } return(new ApiLoginResponse { Succeeded = true, Username = input.Username }); }
public override IQueryable <RequestObserver> SecureList(DataContext db, IQueryable <RequestObserver> query, ApiIdentity identity, params PermissionDefinition[] permissions) { return(query); }
public override Task <bool> CanUpdate(DataContext db, ApiIdentity identity, params Guid[] keys) { return(Task.Run(() => true)); }
public override Task <bool> CanInsert(DataContext db, ApiIdentity identity, params RequestObserver[] requests) { return(Task.Run(() => true)); }
/// <summary> /// Initalizes a new instance of the <see cref="ChunkedMultipartFormDMCSProvider"/> class /// </summary> /// <param name="rootDir">The Root Directory the file chunk is to be written to</param> /// <param name="request">The Request Context sent by the Upload Control</param> /// <param name="context">The DbContext</param> /// <param name="identity">The Api Identity of the User</param> public ChunkedMultipartFormDMCSProvider(string rootDir, HttpRequest request, DataContext context, ApiIdentity identity) : base(rootDir) { this.DocumentMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject <DMCSResponseDocument>(request.Params["metadata"]); this.db = context; this.identity = identity; }
public override Task <bool> CanUpdate(DataContext db, ApiIdentity identity, params Guid[] keys) { return(HasPermissions(db, identity, keys, PermissionIdentifiers.DataMart.ManageSecurity)); }
public override Task <bool> CanInsert(DataContext db, ApiIdentity identity, params AclDataMart[] objs) { return(HasPermissions(db, identity, PermissionIdentifiers.DataMart.ManageSecurity)); }
public override IQueryable <AclDataMart> SecureList(DataContext db, IQueryable <AclDataMart> query, ApiIdentity identity, params PermissionDefinition[] permissions) { if (permissions == null || permissions.Length == 0) { permissions = new PermissionDefinition[] { PermissionIdentifiers.DataMart.ManageSecurity } } ; return(from q in query join dm in db.Filter(db.DataMarts, identity, permissions) on q.DataMartID equals dm.ID select q); }