public static async Task <HttpResponseMessage> UpdateAsync(
            [Property(Name = UserIdentificationPropertyName)] string userIdentification,
            [Property(Name = PasswordPropertyName)] string password,
            Api.Azure.AzureApplication application,
            CreatedResponse onUpdated,
            AlreadyExistsResponse onUsernameAlreadyTaken,
            GeneralConflictResponse onInvalidPassword)
        {
            if (!password.HasBlackSpace())
            {
                return(onInvalidPassword("Password cannot be empty"));
            }

            var accountRef = userIdentification
                             .MD5HashGuid()
                             .AsRef <Account>();

            return(await accountRef
                   .StorageCreateOrUpdateAsync(
                       async (created, account, saveAsync) =>
            {
                if (!created)
                {
                    return onUsernameAlreadyTaken();
                }

                account.userIdentification = userIdentification;
                account.password = Account.GeneratePasswordHash(userIdentification, password);
                await saveAsync(account);
                return onUpdated();
            }));
        }
示例#2
0
 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)));
 }
示例#3
0
        public async Task <IActionResult> DeleteAsync(int id, string authorId)
        {
            if (CurrentUser == null)
            {
                return(BadRequest(new { ErrorMessage = "Unauthorized" }));
            }

            var post = await _postsService.GetPostAsync(id);

            // var comments = await _commentsService.GetCommentsForPostAsync(id);
            // comments.ForEach(comment => _commentsService.Delete(comment));
            await _postsService.GetPostAsync(id);

            if (!post.AuthorId.Equals(CurrentUser.Id))
            {
                return(BadRequest(new { ErrorMessage = "You are not an author of the post." }));
            }

            _postsService.Delete(post);

            var response = new CreatedResponse <int> {
                Id = id
            };

            return(Ok(response));
        }
示例#4
0
        public async Task <IActionResult> CreateAsync([FromBody] CreatePostRequest model)
        {
            if (CurrentUser == null)
            {
                return(BadRequest(new { ErrorMessage = "Unauthorized" }));
            }

            if (!ModelState.IsValid || string.IsNullOrWhiteSpace(model.AuthorId))
            {
                return(NotFound());
            }

            model.AuthorId = CurrentUser.Id;
            var postToCreate = _mapper.Map <Post>(model);
            var tags         = _mapper.Map <List <Tag> >(model.Tags.Distinct());
            await _postsService.InsertAsync(postToCreate, tags);

            var response = new CreatedResponse <int> {
                Id = postToCreate.Id
            };

            var baseUrl     = $@"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}";
            var locationUrl = baseUrl + "/" + ApiRoutes.PostsController.Show.Replace("{id}", postToCreate.Id.ToString());

            return(Created(locationUrl, response));
        }
示例#5
0
        /// <summary>
        /// Plays all matches on the given match day.
        /// </summary>
        public Response PostPlayDayMatches(string gameId, string dayId)
        {
            var game = GetGameInfo(gameId);

            DateTime matchDay = ValidateAndParseMatchDay(dayId);

            var matchService = ServiceFactory.CreateMatchService(game);

            try
            {
                matchService.PlayMatchDay(matchDay);
            }
            catch (BusinessLogicException businessLogicException)
            {
                throw Handle(businessLogicException);
            }

            // If the manager's team played a match the Location header URI is that match, otherwise it's the matches on that day.
            var locationUri         = UriHelper.GetMatchDayUri(gameId, dayId);
            var matchForCurrentTeam = matchService.GetByMatchDayAndTeam(matchDay, game.CurrentTeamId);

            if (matchForCurrentTeam != null)
            {
                locationUri = UriHelper.GetMatchUri(gameId, matchForCurrentTeam.Id);
            }

            var response = new CreatedResponse(locationUri);

            AddAccessControlAllowOriginHeader(response);

            return(response);
        }
        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)));
        }
 [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()));
 }
示例#8
0
 public static Task <IHttpResponse> HttpPostAsync <TResource>(
     this TResource resource,
     CreatedResponse onCreated,
     AlreadyExistsResponse onAlreadyExists)
     where TResource : IReferenceable
 {
     return(resource.StorageCreateAsync(
                discard => onCreated(),
                onAlreadyExists: () => onAlreadyExists()));
 }
        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)));
        }
示例#10
0
        public static async Task <IHttpResponse> CreateContentFormAsync(
            [Property(Name = ContentIdPropertyName)] Guid contentId,
            [Property(Name = ContentPropertyName)] byte[] contentBytes,
            [Header(Content = ContentPropertyName)] System.Net.Http.Headers.MediaTypeHeaderValue mediaHeader,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists)
        {
            var contentType = mediaHeader.MediaType;

            return(await EastFive.Api.Azure.Content.CreateContentAsync(contentId, contentType, contentBytes,
                                                                       () => onCreated(),
                                                                       () => onAlreadyExists()));
        }
示例#11
0
 public static Task <IHttpResponse> CreateAsync(
     [Property(Name = IdPropertyName)] IRef <Claim> claimRef,
     [Property(Name = ActorPropertyName)] Guid actorId,
     [Property(Name = TypePropertyName)] string type,
     [Property(Name = NamePropertyName)] string value,
     [Resource] Claim claim,
     CreatedResponse onCreated,
     AlreadyExistsResponse onAlreadyExists)
 {
     return(claim.StorageCreateAsync(
                (discard) => onCreated(),
                onAlreadyExists: () => onAlreadyExists()));
 }
示例#12
0
        public static async Task <IHttpResponse> CreateContentAsync(
            [QueryParameter(CheckFileName = true, Name = ContentIdPropertyName)] Guid contentId,
            [QueryParameter(Name = ContentPropertyName)] ByteArrayContent content,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists)
        {
            var contentType  = content.Headers.ContentType.MediaType;
            var contentBytes = await content.ReadAsByteArrayAsync();

            return(await EastFive.Api.Azure.Content.CreateContentAsync(contentId, contentType, contentBytes,
                                                                       () => onCreated(),
                                                                       () => onAlreadyExists()));
        }
示例#13
0
 public static async Task <IHttpResponse> CreateAsync(
     [Resource] Client client,
     CreatedResponse onCreated,
     AlreadyExistsResponse onAlreadyExists,
     GeneralConflictResponse onFailure)
 {
     return(await client
            .StorageCreateAsync(
                (discard) =>
     {
         return onCreated();
     },
                () => onAlreadyExists()));
 }
示例#14
0
        public async Task <IActionResult> DeleteAsync([FromRoute] int id)
        {
            var comment = await _tagsService.FindAsync(id);

            if (comment == null)
            {
                return(NotFound());
            }

            _tagsService.Delete(comment);
            var response = new CreatedResponse <int> {
                Id = id
            };

            return(Ok(response));
        }
示例#15
0
        public async Task <IActionResult> Post([FromBody] CustomerRequestModel customerRequestModel)
        {
            var customer = customerRequestModel.ToDomainType();
            await _customersRepository.CreateCustomer(customer);

            _logger.Information($"Created customer with customer reference: {customer.CustomerReference}.");

            var links = HypermediaLinkBuilder.ForCustomerDiscovery(Url, customer.CustomerReference.ToString());
            var customerResponseData = new Dictionary <string, string>
            {
                { "customer_reference", customer.CustomerReference.ToString() }
            };
            var response = new CreatedResponse <CustomerDiscovery>("customer_created", links, customerResponseData);

            return(Created(string.Empty, response));
        }
示例#16
0
 public static Task <HttpResponseMessage> CreateAsync(
     [Property(Name = Resources.ProcessStage.IdPropertyName)]
     Guid processStageId,
     [Property(Name = Resources.ProcessStage.OwnerPropertyName)]
     Guid ownerId,
     [Property(Name = Resources.ProcessStage.TypePropertyName)]
     Guid processStageTypeId,
     [PropertyOptional(Name = Resources.ProcessStage.TitlePropertyName)]
     string title,
     [PropertyOptional(Name = Resources.ProcessStage.ViewablePropertyName)]
     Guid [] viewableIds,
     [PropertyOptional(Name = Resources.ProcessStage.CompletablePropertyName)]
     Guid [] completableIds,
     [PropertyOptional(Name = Resources.ProcessStage.EditablePropertyName)]
     Guid [] editableIds,
     [PropertyOptional(Name = Resources.ProcessStage.ConfirmablePropertyName)]
     Resources.ProcessStage.ConfirmableResource [] confirmables,
     EastFive.Api.Security security, EastFive.Api.Azure.AzureApplication application,
     CreatedResponse onCreated,
     AlreadyExistsResponse onAlreadyExists,
     ReferencedDocumentDoesNotExistsResponse <Resources.ProcessStageType> onTypeDoesNotExist,
     ReferencedDocumentDoesNotExistsResponse <Resources.ProcessStage> onConfirmationStageDoesNotExist,
     ReferencedDocumentDoesNotExistsResponse <BlackBarLabs.Api.ResourceBase> onActorDoesNotExists,
     UnauthorizedResponse onUnauthorized,
     GeneralConflictResponse onFailure)
 {
     return(EastFive.Azure.ProcessStages.CreateAsync(processStageId, ownerId, processStageTypeId, title,
                                                     viewableIds, editableIds, completableIds,
                                                     confirmables
                                                     .Select(
                                                         confirmable =>
                                                         confirmable.ProcessStageNext.ToGuid().Value
                                                         .PairWithKey(
                                                             confirmable.Positions
                                                             .Select(position => position.ToGuid().Value)
                                                             .ToArray()))
                                                     .ToArray(),
                                                     security,
                                                     () => onCreated(),
                                                     () => onAlreadyExists(),
                                                     () => onTypeDoesNotExist(),
                                                     (missingStageId) => onConfirmationStageDoesNotExist(),
                                                     () => onActorDoesNotExists(),
                                                     (why) => onFailure(why)));
 }
示例#17
0
        public Response Post()
        {
            try
            {
                var gameCreationManager = new GameCreationManager();
                var game = gameCreationManager.CreateGame();

                string locationUri = UriHelper.GetGameUri(game.Id);
                var    response    = new CreatedResponse(locationUri);

                return(response);
            }
            catch (Exception exception)
            {
                Logger.LogWarning($"Creating the game failed: '{exception.Message}' {exception}");
                throw ResponseHelper.Get500InternalServerError("Creating the game failed");
            }
        }
        public Task <TradfriAuth> GenerateAppSecret(string GatewaySecret, string applicationName)
        {
            OneKey authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(GatewaySecret)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Client_identity")));

            return(MakeRequest(new EndPointRequest <TradfriAuth>($"/{(int)TradfriConstRoot.Gateway}/{(int)TradfriConstAttr.Auth}/")
            {
                Content = $"{{\"{(int)TradfriConstAttr.Identity}\":\"{applicationName}\"}}",
                Method = Call.POST,
                DTLSEndPoint = new DTLSClientEndPoint(authKey),
                RequestHandler = (resp) => resp switch
                {
                    CreatedResponse crea => crea.Convert <TradfriAuth>(),
                    var other => throw other.ToException()
                }
            }));
示例#19
0
        public static async Task <IHttpResponse> UpdateAsync(
            [WorkflowVariable(
                 Workflows.PasswordLoginCreateAccount.Variables.UserId,
                 UserIdentificationPropertyName)]
            [WorkflowParameter(Value = "{{$randomUserName}}")]
            [Property(Name = UserIdentificationPropertyName)]
            string userIdentification,

            [WorkflowVariable(
                 Workflows.PasswordLoginCreateAccount.Variables.Password,
                 PasswordPropertyName)]
            [WorkflowParameter(Value = "{{$randomPassword}}")]
            [Property(Name = PasswordPropertyName)]
            string password,

            CreatedResponse onCreated,
            AlreadyExistsResponse onUsernameAlreadyTaken,
            GeneralConflictResponse onInvalidPassword)
        {
            if (!password.HasBlackSpace())
            {
                return(onInvalidPassword("Password cannot be empty"));
            }

            var accountRef = userIdentification
                             .MD5HashGuid()
                             .AsRef <Account>();

            return(await accountRef
                   .StorageCreateOrUpdateAsync(
                       async (created, account, saveAsync) =>
            {
                if (!created)
                {
                    return onUsernameAlreadyTaken();
                }

                account.userIdentification = userIdentification;
                account.password = Account.GeneratePasswordHash(userIdentification, password);
                await saveAsync(account);
                return onCreated();
            }));
        }
示例#20
0
        public async Task <IActionResult> CreateASkill([FromBody] DisciplineSkillResource req, int disciplineID)
        {
            if (req == null)
            {
                var error = new BadRequestException("The given request body is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (disciplineID == 0 || disciplineID != req.DisciplineId)
            {
                var error = new BadRequestException("The given discipline ID is invalid");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (String.IsNullOrEmpty(req.Name))
            {
                var error = new BadRequestException("Skill Name cannot be null or empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var createdSkillID = await skillsRepository.CreateASkill(req);

                var response = new CreatedResponse <int>(createdSkillID, $"Successfully created skill '{createdSkillID}' associated with discipline '{disciplineID}'");
                return(StatusCode(StatusCodes.Status201Created, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
示例#21
0
        public async Task <IActionResult> CreateAProject([FromBody] ProjectProfile projectProfile)
        {
            if (projectProfile == null)
            {
                var error = new BadRequestException("The given project is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (
                projectProfile.ProjectManager == null || String.IsNullOrEmpty(projectProfile.ProjectManager.UserID) ||
                projectProfile.ProjectSummary == null ||
                String.IsNullOrEmpty(projectProfile.ProjectSummary.ProjectNumber) ||
                projectProfile.ProjectSummary.Location == null
                )
            {
                var error = new BadRequestException("The Project (Manager(ID) / Summary / Number / Location) cannot be null or empty string!");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }
            try
            {
                var location = await locationsRepository.GetALocation(projectProfile.ProjectSummary.Location.City);

                var createdProjectNumber = await projectsRepository.CreateAProject(projectProfile, location.Id);

                var response = new CreatedResponse <string>(createdProjectNumber, $"Successfully created project number '{createdProjectNumber}'");
                return(StatusCode(StatusCodes.Status201Created, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
示例#22
0
        public async static Task <IHttpResponse> CreateAsync(
            [Property(Name = AccountPropertyName)] Guid accountId,
            [PropertyOptional(Name = AuthorizationPropertyName)] IRefOptional <Authorization> authorizationRefMaybe,
            [Resource] XIntegration integration,
            IAuthApplication application, EastFive.Api.SessionToken security,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ForbiddenResponse onForbidden,
            ReferencedDocumentDoesNotExistsResponse <Authorization> onAuthorizationDoesNotExist,
            GeneralConflictResponse onFailure)
        {
            if (!await application.CanAdministerCredentialAsync(accountId, security))
            {
                return(onForbidden());
            }

            return(await await authorizationRefMaybe.StorageGetAsync(
                       async authorization =>
            {
                if (!await application.ShouldAuthorizeIntegrationAsync(integration, authorization))
                {
                    return onFailure("Authorization is not accessable to this account.");
                }

                return await CreateWithAuthorization(integration, authorization,
                                                     () => onCreated(),
                                                     () => onAlreadyExists(),
                                                     (why) => onFailure(why));
            },
                       async() =>
            {
                if (authorizationRefMaybe.HasValue)
                {
                    return onAuthorizationDoesNotExist();
                }
                return await integration.StorageCreateAsync(
                    (discard) => onCreated(),
                    () => onAlreadyExists());
            }));
        }
示例#23
0
        public async Task <IActionResult> DeleteAsync([FromRoute] int id, [FromBody] string authorId)
        {
            if (CurrentUser == null)
            {
                return(BadRequest(new { ErrorMessage = "Unauthorized" }));
            }

            var message = await _messagesService.FindAsync(id);

            if (!message.SenderId.Equals(CurrentUser.Id) || !message.RecipientId.Equals(CurrentUser.Id))
            {
                return(BadRequest(new { ErrorMessage = "You are not an author of the post." }));
            }

            await _messagesService.DeleteAsync(message);

            var response = new CreatedResponse <int> {
                Id = id
            };

            return(Ok(response));
        }
示例#24
0
        [Api.HttpPost] //(MatchAllBodyParameters = false)]
        public async static Task <IHttpResponse> CreateAsync(
            [Property(Name = AccountPropertyName)] Guid accountId,
            [PropertyOptional(Name = AuthorizationPropertyName)] IRefOptional <Authorization> authorizationRefMaybe,
            [Resource] Integration integration,
            Api.Azure.AzureApplication application,
            EastFive.Api.SessionToken security,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ForbiddenResponse forbidden,
            ReferencedDocumentDoesNotExistsResponse <Authorization> onAuthenticationDoesNotExist,
            GeneralConflictResponse onFailure)
        {
            if (!await application.CanAdministerCredentialAsync(accountId, security))
            {
                return(forbidden());
            }

            return(await await authorizationRefMaybe.StorageGetAsync(
                       authorization =>
            {
                // TODO? This
                // var accountIdDidMatch = await await authorization.ParseCredentailParameters(
                return CreateWithAuthorization(integration, authorization,
                                               accountId,
                                               () => onCreated(),
                                               () => onAlreadyExists(),
                                               (why) => onFailure(why));
            },
                       async() =>
            {
                return await await integration.StorageCreateAsync(
                    discard =>
                {
                    return SaveAccountLookupAsync(accountId, integration,
                                                  () => onCreated());
                },
                    () => onAlreadyExists().AsTask());
            }));
        }
示例#25
0
        public async Task <IActionResult> CreateAsync([FromBody] CreateCommentRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(Bad(ModelState));
            }

            var comment = _mapper.Map <Comment>(request);

            comment.CreatedAt = Now;
            await _commentService.InsertAsync(comment);

            var response = new CreatedResponse <int> {
                Id = comment.Id
            };
            var baseUrl     = $@"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}";
            var locationUrl = baseUrl + "/" +
                              ApiRoutes.CommentsController.Comments + "/" +
                              ApiRoutes.CommentsController.GetComment + "/" + comment.Id.ToString();

            return(CreatedAtRoute(locationUrl, response));
        }
        public static Task <HttpResponseMessage> CreatePasswordCredentialAsync(
            [Property(Name = IdPropertyName)] Guid credentialId,
            [Property(Name = ActorPropertyName)] Guid actorId,
            [PropertyOptional(Name = DisplayNamePropertyName)] string displayName,
            [PropertyOptional(Name = UserIdPropertyName)] string userId,
            [PropertyOptional(Name = TokenPropertyName)] string token,
            [PropertyOptional(Name = IsEmailPropertyName)] bool isEmail,
            [PropertyOptional(Name = ForceChangePropertyName)] bool forceChange,
            [PropertyOptional(Name = LastEmailSentPropertyName)] DateTime?lastEmailSent,
            Context context, AzureApplication application,
            UrlHelper url,
            EastFive.Api.SessionToken security,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            GeneralConflictResponse onUsernameAlreadyInUse,
            GeneralConflictResponse onInsufficentPassword,
            GeneralConflictResponse onUsernameAlreadyMappedToActor,
            UnauthorizedResponse onUnauthorized,
            ServiceUnavailableResponse onServiceUnavailable,
            GeneralConflictResponse onFailure)
        {
            var callbackUrl = url.GetLocation <EastFive.Api.Azure.Credentials.Controllers.OpenIdResponseController>();

            return(context.PasswordCredentials.CreatePasswordCredentialsAsync(
                       credentialId, actorId,
                       displayName, userId, isEmail, token, forceChange,
                       lastEmailSent, callbackUrl,
                       security, application,
                       () => onCreated(),
                       () => onAlreadyExists(),
                       (actorUsingId) => onUsernameAlreadyInUse($"Username already in use with Actor:{actorUsingId}"),
                       () => onInsufficentPassword($"Password is insufficient."),
                       () => onUsernameAlreadyMappedToActor($"Relationship already exists"),
                       () => onUsernameAlreadyMappedToActor($"Login is already in use"),
                       () => onUnauthorized(),
                       () => onServiceUnavailable(),
                       (why) => onFailure(why)));
        }
示例#27
0
        public async Task <IActionResult> CreateAProvince([FromBody] LocationResource location)
        {
            if (location == null)
            {
                var error = new BadRequestException("The given request body is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (String.IsNullOrEmpty(location.Province))
            {
                var error = new BadRequestException("Province cannot be null or empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var createdProvinceName = await locationsRepository.CreateAProvince(location.Province);

                var response = new CreatedResponse <string>(createdProvinceName, $"Successfully created province '{createdProvinceName}'");
                // Log.Information("@{a}", response);
                return(StatusCode(StatusCodes.Status201Created, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    // Log.Information("second bad request");
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
示例#28
0
        public async Task <IActionResult> Put(string customerReference, [FromBody] CustomerRequestModel customerRequestModel)
        {
            if (!Guid.TryParse(customerReference, out var guid))
            {
                _logger.Warning($"Could not parse customer reference: {customerReference}.");
                var errorResponse = new ValidationError("request_invalid", new List <string> {
                    ErrorCodes.CustomerReferenceInvalid
                });
                return(new Models.BadRequestObjectResult(errorResponse));
            }

            var customerOption = await _customersRepository.GetCustomerByCustomerReference(guid);

            if (!customerOption.TryUnwrap(out var customer))
            {
                _logger.Warning($"Cannot find customer with customer reference: {customerReference}.");
                return(NotFound());
            }

            var customertoUpdate = customerRequestModel.ToDomainType();
            var updatedCustomer  = new UpdateCustomer(
                customer.CustomerReference,
                customertoUpdate.FirstName,
                customertoUpdate.Surname,
                customertoUpdate.Status,
                customer.CreatedDate,
                customer.LastModifiedDate);

            var customerToSave = _customerService.UpdateCustomer(updatedCustomer);
            await _customersRepository.UpdateCustomer(customerToSave);

            _logger.Information($"Updated customer with customer reference: {customer.CustomerReference}.");

            var links    = HypermediaLinkBuilder.ForCustomerDiscovery(Url, customer.CustomerReference.ToString());
            var response = new CreatedResponse <CustomerDiscovery>("customer_updated", links);

            return(Ok(response));
        }
示例#29
0
        public static Task <IHttpResponse> CreateAsync(
            [EastFive.Api.Meta.Flows.WorkflowNewId]
            [WorkflowVariable(Workflows.MonitoringFlow.Variables.CreatedNotification, IdPropertyName)]
            [UpdateId]
            IRef <TeamsNotification> teamsNotificationRef,

            [PropertyOptional(Name = RouteFiltersPropertyName)]
            [WorkflowArrayObjectParameter(Value0 = "/api/*")]
            string routeFilters,

            [PropertyOptional(Name = CollectionPropertyName)]
            [WorkflowParameter(Value = "Collection1", Disabled = true)]
            string collection,

            [Resource] TeamsNotification storyBoard,

            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            UnauthorizedResponse onUnauthorized)
        {
            return(storyBoard.HttpPostAsync(
                       onCreated,
                       onAlreadyExists));
        }
示例#30
0
        public async static Task <IHttpResponse> CreateAuthorizedAsync(
            [UpdateId(Name = AuthorizationIdPropertyName)] IRef <Authorization> authorizationRef,
            [Property(Name = MethodPropertyName)] IRef <Method> methodRef,
            [Property(Name = ParametersPropertyName)] IDictionary <string, string> parameters,
            [Resource] Authorization authorization,
            Api.Azure.AzureApplication application, IProvideUrl urlHelper,
            IInvokeApplication endpoints,
            IHttpRequest request,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ForbiddenResponse onAuthorizationFailed,
            ServiceUnavailableResponse onServericeUnavailable,
            ForbiddenResponse onInvalidMethod)
        {
            authorization.accountIdMaybe = default;
            authorization.authorized     = false;
            return(await await Auth.Method.ById(methodRef, application,
                                                (method) =>
            {
                var paramsUpdated = parameters;
                //.Append(
                //    authorizationRef.id.ToString().PairWithKey("state"))
                //.ToDictionary();

                return Redirection.AuthenticationAsync(
                    method,
                    paramsUpdated,
                    application, request, endpoints, request.RequestUri,
                    authorizationRef.Optional(),
                    (redirect, accountIdMaybe, discardModifier) => onCreated(),
                    () => onAuthorizationFailed().AddReason("Authorization was not found"),     // Bad credentials
                    why => onServericeUnavailable().AddReason(why),
                    why => onAuthorizationFailed().AddReason(why));
            },
                                                () => onInvalidMethod().AddReason("The method was not found.").AsTask()));
        }