public virtual OutgoingWebResponse VerifyAccess(HttpRequestBase httpRequestInfo, out AccessToken accessToken) { Requires.NotNull(httpRequestInfo, "httpRequestInfo"); AccessProtectedResourceRequest request = null; try { if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(httpRequestInfo, out request)) { accessToken = this.AccessTokenAnalyzer.DeserializeAccessToken(request, request.AccessToken); ErrorUtilities.VerifyHost(accessToken != null, "IAccessTokenAnalyzer.DeserializeAccessToken returned a null reslut."); if (string.IsNullOrEmpty(accessToken.User) && string.IsNullOrEmpty(accessToken.ClientIdentifier)) { Logger.OAuth.Error("Access token rejected because both the username and client id properties were null or empty."); ErrorUtilities.ThrowProtocol(OAuth2Strings.InvalidAccessToken); } return null; } else { var response = new UnauthorizedResponse(new ProtocolException(OAuth2Strings.MissingAccessToken)); accessToken = null; return this.Channel.PrepareResponse(response); } } catch (ProtocolException ex) { var response = request != null ? new UnauthorizedResponse(request, ex) : new UnauthorizedResponse(ex); accessToken = null; return this.Channel.PrepareResponse(response); } }
public static async Task <IHttpResponse> FindByIdAsync( [QueryParameter(CheckFileName = true)] Guid processStageTypeId, EastFive.Api.Security security, ContentResponse onFound, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { return(await await ProcessStageTypes.FindAllAsync(security, types => types.First( async(stage, next) => { if (stage.processStageTypeId == processStageTypeId) { return onFound(stage); } return await next(); }, () => onNotFound().ToTask()), () => onUnauthorized().ToTask())); //return Connectors.FindByIdAsync(id, // security.performingAsActorId, security.claims, // (synchronization, destinationIntegrationId) => onFound(GetResource(synchronization, destinationIntegrationId, url)), // () => onNotFound(), // () => onUnauthorized()); }
public static Task <IHttpResponse> CreateAsync( [Property(Name = Resources.ProcessStageType.IdPropertyName)] Guid processStageTypeId, [Property(Name = Resources.ProcessStageType.OwnerPropertyName)] Guid ownerId, [Property(Name = Resources.ProcessStageType.GroupPropertyName)] Guid processStageGroupId, [Property(Name = Resources.ProcessStageType.TitlePropertyName)] string title, [Property(Name = Resources.ProcessStageType.ResourceTypePropertyName)] Type resourceType, [Property(Name = Resources.ProcessStageType.ResourceKeysPropertyName)] string[] resourceKeys, [Property(Name = Resources.ProcessStageType.ResourceTypesPropertyName)] Type[] resourceTypes, EastFive.Api.Security security, IHttpRequest request, IProvideUrl url, CreatedResponse onCreated, CreatedBodyResponse <ProcessStageType> onCreatedAndModified, AlreadyExistsResponse onAlreadyExists, AlreadyExistsReferencedResponse onRelationshipAlreadyExists, ReferencedDocumentNotFoundResponse onReferenceNotFound, UnauthorizedResponse onUnauthorized, GeneralConflictResponse onFailure) { var resourceList = resourceKeys.Zip(resourceTypes, (k, v) => k.PairWithValue(v)).ToArray(); return(ProcessStageTypes.CreateAsync(processStageTypeId, ownerId, processStageGroupId, title, resourceType, resourceList, security, () => onCreated(), () => onAlreadyExists(), () => onReferenceNotFound(), (brokenId) => onReferenceNotFound(), (why) => onFailure(why))); }
public async static Task <IHttpResponse> UpdateAsync( [UpdateId(Name = AuthorizationIdPropertyName)] IRef <Authorization> authorizationRef, [Property(Name = LocationLogoutReturnPropertyName)] Uri locationLogoutReturn, EastFive.Api.SessionToken?securityMaybe, NoContentResponse onUpdated, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { return(await authorizationRef.StorageUpdateAsync( async (authorization, saveAsync) => { if (authorization.deleted.HasValue) { return onNotFound(); } if (authorization.authorized) { authorization.LocationAuthentication = default(Uri); if (!securityMaybe.HasValue) { return onUnauthorized(); } } authorization.LocationLogoutReturn = locationLogoutReturn; await saveAsync(authorization); return onUpdated(); }, () => onNotFound())); }
public static Task <IHttpResponse> CreateAsync( [Property(Name = ProcessStep.IdPropertyName)] Guid processId, [PropertyOptional(Name = ProcessStep.PreviousPropertyName)] Guid?previousStepId, [Property(Name = ProcessStep.ResourcePropertyName)] Guid resourceId, [Property(Name = ProcessStep.StagePropertyName)] Guid processStageId, [Property(Name = ProcessStep.CreatedOnPropertyName)] DateTime createdOn, [PropertyOptional(Name = ProcessStep.ConfirmedByPropertyName)] Guid?confirmedById, [PropertyOptional(Name = ProcessStep.ConfirmedWhenPropertyName)] DateTime?confirmedWhen, [PropertyOptional(Name = ProcessStep.ResourceKeysPropertyName)] string[] resourceKeys, [PropertyOptional(Name = ProcessStep.ResourcesPropertyName)] Guid[] resources, EastFive.Api.Security security, IProvideUrl url, CreatedResponse onCreated, AlreadyExistsResponse onAlreadyExists, ReferencedDocumentDoesNotExistsResponse <Resources.ProcessStage> onStageNotFound, UnauthorizedResponse onUnauthorized, GeneralConflictResponse onFailure) { return(EastFive.Azure.Processes.CreateAsync(processId, processStageId, resourceId, createdOn, resourceKeys.NullToEmpty().Zip(resources.NullToEmpty(), (k, id) => k.PairWithValue(id)).ToArray(), previousStepId, confirmedWhen, confirmedById, security, () => onCreated(), () => onAlreadyExists(), () => onStageNotFound(), (why) => onFailure(why))); }
public static Task <IHttpResponse> UpdateProcessStepAsync( [QueryParameter(Name = ProcessStep.IdPropertyName, CheckFileName = true)] Guid processId, [PropertyOptional(Name = ProcessStep.ConfirmedByPropertyName)] Guid?confirmedById, [PropertyOptional(Name = ProcessStep.ConfirmedWhenPropertyName)] DateTime?confirmedWhen, [PropertyOptional(Name = ProcessStep.ResourceKeysPropertyName)] string[] resourceKeys, [PropertyOptional(Name = ProcessStep.ResourcesPropertyName)] Guid[] resources, EastFive.Api.Security security, IProvideUrl url, NoContentResponse onUpdated, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized, GeneralConflictResponse onFailure) { return(EastFive.Azure.Processes.UpdateAsync(processId, confirmedById, confirmedWhen, resourceKeys.NullToEmpty().Zip(resources.NullToEmpty(), (k, id) => k.PairWithValue(id)).ToArray(), security, () => onUpdated(), () => onNotFound(), () => onUnauthorized(), (why) => onFailure(why))); //return Connectors.UpdateConnectorAsync(id, // Flow, security.performingAsActorId, security.claims, // () => onUpdated(), // () => onNotFound(), // (why) => onFailure(why)); }
public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out string userName, out HashSet<string> scope) { Requires.NotNull(httpRequestInfo, "httpRequestInfo"); AccessProtectedResourceRequest request = null; try { if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(httpRequestInfo, out request)) { if (this.AccessTokenAnalyzer.TryValidateAccessToken(request, request.AccessToken, out userName, out scope)) { // No errors to return. return null; } throw ErrorUtilities.ThrowProtocol("Bad access token"); } else { var response = new UnauthorizedResponse(new ProtocolException("Missing access token")); userName = null; scope = null; return this.Channel.PrepareResponse(response); } } catch (ProtocolException ex) { var response = request != null ? new UnauthorizedResponse(request, ex) : new UnauthorizedResponse(ex); userName = null; scope = null; return this.Channel.PrepareResponse(response); } }
public async static Task <HttpResponseMessage> QueryByActorId( [QueryParameter(Name = ActorPropertyName)] Guid actorId, Context context, AzureApplication application, EastFive.Api.SessionToken security, UrlHelper urlHelper, ContentResponse onFound, MultipartResponseAsync onFounds, ReferencedDocumentNotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized, ServiceUnavailableResponse onServiceUnavailable) { return(await await context.PasswordCredentials.GetPasswordCredentialByActorAsync( actorId, security, application, (credentials) => { var credentialResources = credentials .Select( passwordCredential => { var resource = Convert(passwordCredential, urlHelper); var response = onFound(resource); return response; }) .ToArray(); return onFounds(credentialResources); }, () => onNotFound().AsTask(), () => onUnauthorized().AsTask(), (why) => onServiceUnavailable().AsTask())); }
public async static Task <HttpResponseMessage> GetByIdAsync( [QueryParameter(Name = IntegrationIdPropertyName)] IRef <XIntegration> integrationRef, Api.Azure.AzureApplication application, SessionToken security, ContentTypeResponse <XIntegration> onFound, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { if (!security.accountIdMaybe.HasValue) { return(onUnauthorized()); } var accountId = security.accountIdMaybe.Value; return(await await integrationRef.StorageGetAsync( integration => { return Auth.Method.ById(integration.Method, application, method => { integration.methodName = method.name; return onFound(integration); }, () => onNotFound()); }, () => onNotFound().AsTask())); }
public async static Task <HttpResponseMessage> GetByMethodAsync( [QueryParameter(Name = Authorization.MethodPropertyName)] IRef <Method> methodRef, Api.Azure.AzureApplication application, SessionToken security, MultipartResponseAsync <XIntegration> onContents, UnauthorizedResponse onUnauthorized) { if (!security.accountIdMaybe.HasValue) { return(onUnauthorized()); } var accountId = security.accountIdMaybe.Value; var integrations = GetIntegrationsByAccount(accountId) .Where(integration => integration.Value.Method.id == methodRef.id) .Select( kvp => { var integration = kvp.Key; return(Auth.Method.ById(kvp.Value.Method, application, method => { integration.methodName = method.name; return integration; }, () => default(XIntegration?))); }) .Await() .SelectWhereHasValue(); return(await onContents(integrations)); }
public async static Task <HttpResponseMessage> GetByAccountAsync( [QueryParameter(Name = AccountPropertyName)] Guid accountId, Api.Azure.AzureApplication application, SessionToken security, MultipartResponseAsync <XIntegration> onContents, ReferencedDocumentNotFoundResponse <object> onAccountNotFound, UnauthorizedResponse onUnauthorized) { if (!await application.CanAdministerCredentialAsync(accountId, security)) { return(onUnauthorized()); } var integrations = GetIntegrationsByAccount(accountId) .Select( kvp => { var integration = kvp.Key; return(Auth.Method.ById(kvp.Value.Method, application, method => { integration.methodName = method.name; return integration; }, () => default(XIntegration?))); }) .Await() .SelectWhereHasValue(); return(await onContents(integrations)); }
public static Task <IHttpResponse> QueryBySessionAsync( [QueryParameter(Name = "session")] IRef <Session> sessionRef, IAuthApplication application, MultipartAsyncResponse <Method> onContent, ReferencedDocumentNotFoundResponse <Session> onSessionNotFound, UnauthorizedResponse onHacked) { return(sessionRef.StorageGetAsync( session => { var integrationProviders = application.LoginProviders .Where(loginProvider => loginProvider.Value.GetType().IsSubClassOfGeneric(typeof(IProvideSession))) .Select( async loginProvider => { var supportsIntegration = await(loginProvider.Value as IProvideSession).SupportsSessionAsync(session); return supportsIntegration.PairWithValue(loginProvider); }) .AsyncEnumerable() .Where(kvp => kvp.Key) .SelectValues() .Select( (loginProvider) => { return new Method { authenticationId = new Ref <Method>(loginProvider.Value.Id), name = loginProvider.Value.Method, }; }); return onContent(integrationProviders); }, //() => onSessionNotFound().AsTask()); () => onHacked())); }
public static async Task <IHttpResponse> GetAsync( [QueryParameter(Name = SessionIdPropertyName, CheckFileName = true)] IRef <Session> sessionRef, EastFive.Api.SessionTokenMaybe security, IAuthApplication application, ContentTypeResponse <Session> onFound, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized, ConfigurationFailureResponse onConfigurationFailure) { if (!IsAnonSessionAllowed()) { if (security.sessionId != sessionRef.id) { return(onUnauthorized()); } } return(await await sessionRef.StorageGetAsync( (session) => { return Web.Configuration.Settings.GetUri( EastFive.Security.AppSettings.TokenScope, scope => { return Web.Configuration.Settings.GetDouble(Security.SessionServer.Configuration.AppSettings.TokenExpirationInMinutes, (tokenExpirationInMinutes) => { return GetClaimsAsync(application, session.authorization, (claims, accountIdMaybe, authorized) => { session.account = accountIdMaybe; session.authorized = authorized; return Api.Auth.JwtTools.CreateToken(session.id, scope, TimeSpan.FromMinutes(tokenExpirationInMinutes), claims, (tokenNew) => { session.token = tokenNew; return onFound(session); }, (missingConfig) => onConfigurationFailure("Missing", missingConfig), (configName, issue) => onConfigurationFailure(configName, issue)); }, (why) => onNotFound()); }, (why) => onConfigurationFailure("Missing", why).AsTask()); }, (why) => onConfigurationFailure("Missing", why).AsTask()); }, () => onNotFound().AsTask())); bool IsAnonSessionAllowed() { var appType = application.GetType(); if (!appType.TryGetAttributeInterface <IConfigureAuthorization>(out IConfigureAuthorization authConfig)) { return(false); } return(authConfig.IsAnonymousSessionAllowed); } }
public static object ToOAuth2JsonResponse(this UnauthorizedResponse response) { return(new { error = response.ErrorCode, error_description = response.ErrorDescription, error_uri = response.ErrorUri }); }
[Api.HttpPost] //(MatchAllBodyParameters = false)] public async static Task <HttpResponseMessage> CreateAsync( [Property(Name = AccountPropertyName)] Guid accountId, [Property(Name = AuthorizationPropertyName)] IRef <Authorization> authorizationRef, [Resource] AccountMapping accountMapping, Api.Azure.AzureApplication application, Api.SessionToken security, CreatedResponse onCreated, ForbiddenResponse onForbidden, UnauthorizedResponse onUnauthorized, ReferencedDocumentDoesNotExistsResponse <Authorization> onAuthenticationDoesNotExist, GeneralConflictResponse onFailure) { if (!await application.CanAdministerCredentialAsync(accountId, security)) { return(onUnauthorized()); } return(await await authorizationRef.StorageGetAsync( async authorization => { accountMapping.Method = authorization.Method; // method is used in the .mappingId var authorizationLookup = new AuthorizationLookup { accountMappingRef = accountMapping.mappingId, authorizationLookupRef = authorizationRef, }; return await await authorizationLookup.StorageCreateAsync( async(idDiscard) => { accountMapping.accountMappingLookup = await await authorization.ParseCredentailParameters( application, (accountKey, loginProvider) => { var lookup = new AccountMappingLookup() { accountkey = accountKey, accountMappingId = accountMapping.mappingId, Method = authorization.Method, }; return lookup.StorageCreateAsync( (discard) => new RefOptional <AccountMappingLookup>( lookup.accountMappingLookupId), () => new RefOptional <AccountMappingLookup>()); }, (why) => { var amLookupMaybe = new RefOptional <AccountMappingLookup>(); return amLookupMaybe.AsTask(); }); return await accountMapping.StorageCreateAsync( createdId => { return onCreated(); }, () => onForbidden().AddReason("Account is already mapped to that authentication.")); }, () => onFailure("Authorization is already mapped to another account.").AsTask()); }, () => onAuthenticationDoesNotExist().AsTask())); }
public static async Task <HttpResponseMessage> FindAllAsync( EastFive.Api.Security security, HttpRequestMessage request, UrlHelper url, MultipartAcceptArrayResponseAsync onMultipart, UnauthorizedResponse onUnauthorized) { return(await await ProcessStageTypes.FindAllAsync(security, types => onMultipart(types.Select(type => GetResource(type, url))), () => onUnauthorized().ToTask())); }
public static Task <IHttpResponse> FindAllAsync( EastFive.Api.Security security, IProvideUrl url, MultipartAcceptArrayResponse onMultipart, UnauthorizedResponse onUnauthorized) { return(ProcessStageTypes.FindAllAsync(security, types => onMultipart(types.Select(type => GetResource(type, url))), () => onUnauthorized())); }
public static object ToGameApiUnauthorizedErrorResponse(this UnauthorizedResponse response) { return(new { err = GameApiErrorCode.InvalidToken, errdesc = response.ErrorDescription, error_uri = response.ErrorUri }); }
public static Task <HttpResponseMessage> FindByIdAsync( [QueryParameter(CheckFileName = true, Name = "id")] Guid adapterId, Security security, Context context, HttpRequestMessage request, UrlHelper url, ContentResponse onFound, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { return(EastFive.Azure.Synchronization.Connections.FindAdapterByIdAsync(adapterId, (adapter) => onFound(GetResource(adapter, url)), () => onNotFound())); }
public static Task <IHttpResponse> QueryByContentIdAsync( [QueryParameter(CheckFileName = true, Name = ContentIdPropertyName)] Guid contentId, [OptionalQueryParameter] int?width, [OptionalQueryParameter] int?height, [OptionalQueryParameter] bool?fill, [OptionalQueryParameter] string renderer, BytesResponse onRawResponse, ImageRawResponse onImageResponse, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { var response = EastFive.Api.Azure.Content.FindContentByContentIdAsync(contentId, (contentType, image) => { if (renderer.HasBlackSpace()) { if (renderer.ToLower() == "unzip") { using (var compressedStream = new MemoryStream(image)) using (var zipStream = new System.IO.Compression.ZipArchive(compressedStream, ZipArchiveMode.Read)) using (var resultStream = new MemoryStream()) { var zipFile = zipStream.Entries.First(); zipFile.Open().CopyTo(resultStream); var data = resultStream.ToArray(); return(onRawResponse(data, contentType: "application/object", filename: zipFile.Name)); //return request.CreateFileResponse(data, "application/object", filename: zipFile.Name); } } } //if (contentType.StartsWith("video", StringComparison.InvariantCultureIgnoreCase) && // (width.HasValue || height.HasValue || fill.HasValue)) //{ // var videoPreviewImage = default(System.Drawing.Image); // Properties.Resources.video_preview; // return request.CreateImageResponse(videoPreviewImage, // width: width, height: height, fill: fill, // filename: contentId.ToString("N")); //} return(onImageResponse(image, width: width, height: height, fill: fill, filename: contentId.ToString("N"), contentType: contentType)); //return request.CreateImageResponse(image, // width: width, height: height, fill: fill, // filename: contentId.ToString("N"), // contentType: contentType); }, () => onNotFound(), () => onUnauthorized()); return(response); }
public static async Task <HttpResponseMessage> FindByResourceAsync( [QueryParameter] Guid resourceId, EastFive.Api.Security security, UrlHelper url, MultipartAcceptArrayResponseAsync onMultipart, ReferencedDocumentNotFoundResponse onResourceNotFound, UnauthorizedResponse onUnauthorized) { return(await await EastFive.Azure.ProcessStages.FindByResourceAsync(resourceId, security, (processStages) => onMultipart(processStages.Select(ps => GetResource(ps, url))), () => onResourceNotFound().ToTask(), () => onUnauthorized().ToTask())); }
public static Task <IHttpResponse> DeleteByIdAsync( [QueryParameter(CheckFileName = true, Name = ProcessStep.IdPropertyName)] Guid processStepId, EastFive.Api.Security security, NoContentResponse onDeleted, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { return(EastFive.Azure.Processes.DeleteByIdAsync(processStepId, security, () => onDeleted(), () => onNotFound(), () => onUnauthorized())); }
public static Task <HttpResponseMessage> DeleteByIdAsync( [QueryParameter(CheckFileName = true, Name = ResourceBase.IdPropertyName)] Guid synchronizationId, Security security, Context context, HttpRequestMessage request, UrlHelper url, ContentResponse onFound, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { return(Connectors.DeleteByIdAsync(synchronizationId, security.performingAsActorId, security.claims, () => onFound(true), () => onNotFound())); }
public static Task <HttpResponseMessage> CreateConnectorAsync( [Property] Guid id, [Property(Name = EastFive.Api.Resources.Connector.SourcePropertyName)] Guid source, [Property(Name = EastFive.Api.Resources.Connector.DestinationPropertyName)] Guid destination, [Property(Name = EastFive.Api.Resources.Connector.FlowPropertyName)] Connector.SynchronizationMethod Flow, Security security, Context context, HttpRequestMessage request, UrlHelper url, CreatedResponse onCreated, CreatedBodyResponse <Resources.Connection> onCreatedAndModifiedConnection, CreatedBodyResponse <Resources.Connector> onCreatedAndModified, AlreadyExistsResponse onAlreadyExists, AlreadyExistsReferencedResponse onRelationshipAlreadyExists, ReferencedDocumentNotFoundResponse onReferenceNotFound, UnauthorizedResponse onUnauthorized, GeneralConflictResponse onFailure) { return(Connectors.CreateConnectorAsync(id, source, destination, Flow, security.performingAsActorId, security.claims, () => onCreated(), (connection) => { return request.Headers.Accept .OrderByDescending(accept => accept.Quality.HasValue ? accept.Quality.Value : 1.0) .First( (accept, next) => { if ( accept.MediaType.ToLower() == "x-ordering/connection" || accept.MediaType.ToLower() == "x-ordering/connection+json") { return onCreatedAndModifiedConnection( ConnectionController.GetResource(connection, url), "x-ordering/connection+json"); } if ( accept.MediaType.ToLower() == "x-ordering/connector" || accept.MediaType.ToLower() == "x-ordering/connector+json" || accept.MediaType.ToLower() == "application/json") { return onCreatedAndModified( GetResource(connection.connector, url), "x-ordering/connector+json"); } return next(); }, () => onCreatedAndModified(GetResource(connection.connector, url))); }, () => onAlreadyExists(), (existingConnectorId) => onRelationshipAlreadyExists(existingConnectorId), (brokenId) => onReferenceNotFound(), (why) => onFailure(why))); }
public static Task <IHttpResponse> UpdateAsync( [WorkflowParameter(Value = "{{TeamsNotification}}")] [UpdateId] IRef <TeamsNotification> teamsNotificationRef, [MutateResource] MutateResource <TeamsNotification> updated, ContentTypeResponse <TeamsNotification> onUpdated, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { return(teamsNotificationRef .HttpPatchAsync(updated, onUpdated, onNotFound)); }
public static Task <HttpResponseMessage> FindByIdAsync( [QueryParameter(CheckFileName = true)] Guid id, EastFive.Api.Security security, UrlHelper url, ContentResponse onFound, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { return(EastFive.Azure.ProcessStages.FindByIdAsync(id, security, (processStage) => onFound(GetResource(processStage, url)), () => onNotFound(), () => onUnauthorized())); }
public static Task <IHttpResponse> FindByIdAsync( [QueryParameter(CheckFileName = true, Name = ProcessStep.IdPropertyName)] Guid id, AzureApplication httpApplication, EastFive.Api.Security security, IProvideUrl url, ContentResponse onFound, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { return(EastFive.Azure.Processes.FindByIdAsync(id, security, (process) => onFound(GetResource(process, httpApplication, url)), () => onNotFound(), () => onUnauthorized())); }
public static Task <HttpResponseMessage> FindByIdAsync( [QueryParameter(CheckFileName = true)] Guid id, Security security, Context context, HttpRequestMessage request, UrlHelper url, ContentResponse onFound, NotFoundResponse onNotFound, UnauthorizedResponse onUnauthorized) { return(Connectors.FindByIdAsync(id, security.performingAsActorId, security.claims, (synchronization) => onFound(GetResource(synchronization, url)), () => onNotFound(), () => onUnauthorized())); }
public static HttpResponseMessage Options(HttpRequestMessage request, UrlHelper url, ContentResponse onOption, ReferencedDocumentNotFoundResponse onReferenceNotFound, UnauthorizedResponse onUnauthorized) { var adapter1Id = Guid.NewGuid(); var adapter2Id = Guid.NewGuid(); var connectorId = Guid.NewGuid(); var integration1 = Guid.NewGuid(); return(onOption( GetResource( new Connection() { connector = new Connector() { adapterExternalId = adapter1Id, adapterInternalId = adapter2Id, connectorId = connectorId, createdBy = adapter1Id, synchronizationMethod = Connector.SynchronizationMethod.useExternal, }, adapterInternal = new Adapter() { adapterId = adapter1Id, connectorIds = new Guid[] { connectorId }, identifiers = new KeyValuePair <string, string> [] { "name".PairWithValue("Example Name"), }, integrationId = integration1, key = Guid.NewGuid().ToString(), name = "Example", resourceType = "Product", }, adapterExternal = new Adapter() { adapterId = adapter1Id, connectorIds = new Guid[] { connectorId }, identifiers = new KeyValuePair <string, string>[] { "name".PairWithValue("Test Name"), }, integrationId = integration1, key = Guid.NewGuid().ToString("N"), name = "Test", resourceType = "Product", }, }, url))); }
/// <summary> /// Discovers what access the client should have considering the access token in the current request. /// </summary> /// <param name="httpRequestInfo">The HTTP request info.</param> /// <param name="requiredScopes">The set of scopes required to approve this request.</param> /// <returns> /// The access token describing the authorization the client has. Never <c>null</c>. /// </returns> /// <exception cref="ProtocolFaultResponseException"> /// Thrown when the client is not authorized. This exception should be caught and the /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage"/> message should be returned to the client. /// </exception> public virtual AccessToken GetAccessToken(HttpRequestBase httpRequestInfo = null, params string[] requiredScopes) { Requires.NotNull(requiredScopes, "requiredScopes"); RequiresEx.ValidState(this.ScopeSatisfiedCheck != null, Strings.RequiredPropertyNotYetPreset); if (httpRequestInfo == null) { httpRequestInfo = this.Channel.GetRequestFromContext(); } AccessToken accessToken; AccessProtectedResourceRequest request = null; try { if (this.Channel.TryReadFromRequest <AccessProtectedResourceRequest>(httpRequestInfo, out request)) { accessToken = this.AccessTokenAnalyzer.DeserializeAccessToken(request, request.AccessToken); ErrorUtilities.VerifyHost(accessToken != null, "IAccessTokenAnalyzer.DeserializeAccessToken returned a null reslut."); if (string.IsNullOrEmpty(accessToken.User) && string.IsNullOrEmpty(accessToken.ClientIdentifier)) { Logger.OAuth.Error("Access token rejected because both the username and client id properties were null or empty."); ErrorUtilities.ThrowProtocol(ResourceServerStrings.InvalidAccessToken); } var requiredScopesSet = OAuthUtilities.ParseScopeSet(requiredScopes); if (!this.ScopeSatisfiedCheck.IsScopeSatisfied(requiredScope: requiredScopesSet, grantedScope: accessToken.Scope)) { var response = UnauthorizedResponse.InsufficientScope(request, requiredScopesSet); throw new ProtocolFaultResponseException(this.Channel, response); } return(accessToken); } else { var ex = new ProtocolException(ResourceServerStrings.MissingAccessToken); var response = UnauthorizedResponse.InvalidRequest(ex); throw new ProtocolFaultResponseException(this.Channel, response, innerException: ex); } } catch (ProtocolException ex) { if (ex is ProtocolFaultResponseException) { // This doesn't need to be wrapped again. throw; } var response = request != null?UnauthorizedResponse.InvalidToken(request, ex) : UnauthorizedResponse.InvalidRequest(ex); throw new ProtocolFaultResponseException(this.Channel, response, innerException: ex); } }
[Api.HttpPatch] //(MatchAllBodyParameters = false)] public async static Task <IHttpResponse> UpdateAsync( [Property(Name = IntegrationIdPropertyName)] IRef <XIntegration> integrationRef, [Property(Name = AuthorizationPropertyName)] IRef <Authorization> authorizationRef, Api.Azure.AzureApplication application, EastFive.Api.SessionToken security, ContentTypeResponse <XIntegration> onUpdated, NotFoundResponse onNotFound, ForbiddenResponse onForbidden, ReferencedDocumentDoesNotExistsResponse <Authorization> onAuthorizationDoesNotExist, UnauthorizedResponse onUnauthorized) { return(await integrationRef.StorageUpdateAsync( async (integration, saveAsync) => { var accountId = integration.accountId; if (!await application.CanAdministerCredentialAsync(accountId, security)) { return onUnauthorized(); } return await await authorizationRef.StorageGetAsync( async authorization => { if (!await application.ShouldAuthorizeIntegrationAsync(integration, authorization)) { return onForbidden().AddReason("Authorization is not accessable to this account."); } integration.Method = authorization.Method; // method is used in the .mappingId integration.authorization = authorizationRef.Optional(); integration.methodName = await Auth.Method.ById(authorization.Method, application, method => method.name, () => string.Empty); await saveAsync(integration); return onUpdated(integration); }, () => onAuthorizationDoesNotExist().AsTask()); }, () => onNotFound(), onModificationFailures: StorageConstraintUniqueAttribute.ModificationFailure( (XIntegration x) => x.authorization, () => { // TODO: Check if mapping is to this integration and reply already created. return onForbidden().AddReason("Authorization is already in use."); }).AsArray())); }
public static async Task <HttpResponseMessage> FindByFirstStepByActorAndTypeAsync( [QueryParameter(Name = Resources.ProcessStage.OwnerPropertyName)] Guid ownerId, [QueryParameter(Name = Resources.ProcessStage.TypePropertyName)] Type resourceType, [QueryParameter(Name = "processstage." + Resources.ProcessStage.ConfirmablePropertyName + "." + Resources.ProcessStage.ConfirmableResource.ProcessStageNextPropertyName)] EastFive.Api.Controllers.WebIdNone nextStage, AzureApplication application, EastFive.Api.Security security, UrlHelper url, MultipartAcceptArrayResponseAsync onMultipart, ReferencedDocumentNotFoundResponse onResourceNotFound, UnauthorizedResponse onUnauthorized) { return(await await EastFive.Azure.ProcessStages.FindStartByActorAndResourceTypeAsync(ownerId, resourceType, security, (processStages) => onMultipart(processStages.Select(ps => GetResource(ps, url))), () => onResourceNotFound().ToTask(), () => onUnauthorized().ToTask())); }