public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"C# HTTP trigger function {nameof(HttpHelloWorldFunction)} processed a request.");

            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }
            log.LogWarning($"HTTP trigger function {nameof(HttpHelloWorldFunction)} request is authorized.");


            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            string  name        = data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return(new OkObjectResult(responseMessage));
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }
            log.LogWarning($"HTTP trigger function {nameof(BookmarkRuleFunction)} request is authorized.");

            Bookmark data;

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            data = JsonConvert.DeserializeObject <Bookmark>(requestBody);
            bool isNull = string.IsNullOrEmpty(data?.RuleGuid) || string.IsNullOrEmpty(data?.UserId);

            if (data == null || isNull)
            {
                return(new JsonResult(new
                {
                    error = true,
                    message = "Request body is empty",
                }));
            }

            var results = await _dbContext.Bookmarks.Query(q => q.Where(w => w.RuleGuid == data.RuleGuid && w.UserId == data.UserId));

            var model = results.FirstOrDefault();

            if (model == null)
            {
                model = await _dbContext.Bookmarks.Add(data);

                log.LogInformation("Added new bookmark on rule. Id: {0}", model.Id);
            }
            else
            {
                log.LogInformation("Bookmark already exists for user {0}", model.UserId);
                return(new JsonResult(new
                {
                    error = true,
                    message = "This rule has already been bookmarked"
                }));
            }

            log.LogInformation($"User: {model.UserId}, Rule: {model.RuleGuid}, Id: {model.Id}");

            return(new JsonResult(new
            {
                error = false,
                message = "",
            }));
        }
Beispiel #3
0
        public async Task <ActionResult <Order[]> > GetOrdersForUser(
            [HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "GetOrdersForUser")] HttpRequest req,
            ILogger log)
        {
            log.LogWarning("GetOrdersForUser function processed a request.");
            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogError(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }

            log.LogWarning($"HTTP trigger function GetOrdersForUser request is authorized.");
            string userId  = req.Query["userId"];
            var    results = OrderRepository.GetAll().Where(x => x.UserId == userId).ToArray();

            return(results);
        }
Beispiel #4
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }
            log.LogWarning($"HTTP trigger function {nameof(RemoveReactionFunction)} request is authorized.");

            Reaction data;

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            data = JsonConvert.DeserializeObject <Reaction>(requestBody);

            bool isNull = string.IsNullOrEmpty(data?.RuleGuid) || string.IsNullOrEmpty(data?.UserId) || data?.Type == null;

            if (data == null || isNull)
            {
                return(new JsonResult(new
                {
                    error = true,
                    message = "Request body is empty",
                }));
            }

            var results = await _dbContext.Reactions.Query(q => q.Where(w => w.RuleGuid == data.RuleGuid && w.UserId == data.UserId));

            var model = results.FirstOrDefault();

            if (model == null)
            {
                log.LogInformation("No reaction exists for User {0} and Rule {1}", data.UserId, data.RuleGuid);
                return(new JsonResult(new
                {
                    error = true,
                    message = "No reaction exists for this rule and user",
                    data.UserId,
                    data.RuleGuid,
                }));
            }
            var deleteResults = await _dbContext.Reactions.Delete(model);

            log.LogInformation($"User: {model.UserId}, Rule: {model.RuleGuid}, Id: {model.Id}");

            return(new JsonResult(new
            {
                error = false,
                message = ""
            }));
        }
        public async Task <IActionResult> GenerateSasToken(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
            HttpRequest req, ILogger log, ExecutionContext context)
        {
            log.LogWarning($"HTTP trigger function {nameof(GetSasToken)} received a request.");

            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }
            log.LogWarning($"HTTP trigger function {nameof(GetSasToken)} request is authorized.");

            string    requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            ImageData imageData   = JsonConvert.DeserializeObject <ImageData>(requestBody);

            CloudStorageAccount storageAccount = GetCloudStorageAccount(context);
            var credentials = storageAccount.Credentials;
            var accountName = credentials.AccountName;
            var accountKey  = credentials.ExportBase64EncodedKey();

            var fullFileName = GetFullFileName(imageData.SasAccessType);
            var blobNamePath = GetBlobNamePath(imageData.SasAccessType);
            var blobName     = $"{blobNamePath}/{fullFileName}";

            // Create an instance of the CloudBlobClient
            CloudBlobClient client = storageAccount.CreateCloudBlobClient();

            // Retrieve an instance of the container using hard-code container name
            CloudBlobContainer container = client.GetContainerReference("cdn");

            // Create a SAS token that's valid for one hour
            BlobSasBuilder sasBuilder = new BlobSasBuilder
            {
                ExpiresOn         = DateTime.UtcNow.AddHours(1),
                BlobContainerName = container.Name,
                BlobName          = blobName,
                Resource          = "b"
            };

            // Specify permission for the SAS
            sasBuilder.SetPermissions(BlobSasPermissions.Create);

            // Use the key to get the SAS token
            string sasToken = sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential(accountName, accountKey))
                              .ToString();

            var sasUri = $"{container.GetBlobReference(blobName).Uri}?{sasToken}";

            return(new OkObjectResult(sasUri));
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }

            log.LogWarning($"HTTP trigger function {nameof(AddUserOrganisationFunction)} request is authorized.");

            User data;

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            data = JsonConvert.DeserializeObject <User>(requestBody);

            if (data == null || string.IsNullOrEmpty(data?.UserId))
            {
                return(new JsonResult(new
                {
                    error = true,
                    message = "Request body is empty",
                }));
            }

            var existingOrganisation = await _dbContext.Users.Query(q => q.Where(w => w.UserId == data.UserId && w.OrganisationId == data.OrganisationId));

            var model = existingOrganisation.FirstOrDefault();

            if (model != null)
            {
                return(new JsonResult(new
                {
                    error = true,
                    message = "User is already assigned to this organisation",
                }));
            }

            var result = await _dbContext.Users.Add(data);

            return(new JsonResult(new
            {
                error = false,
                message = "",
                user = result,
            }));
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, Route = null)] HttpRequest req,
            ILogger log)
        {
            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }

            log.LogWarning($"HTTP trigger function {nameof(GetUserFunction)} request is authorized.");

            string UserId = req.Query["user_id"];

            if (string.IsNullOrEmpty(UserId))
            {
                return(new BadRequestObjectResult(new
                {
                    message = "Missing or empty user_id param",
                }));
            }

            var result = await _dbContext.Users.Query(q => q.Where(w => w.UserId == UserId));

            User user = result.FirstOrDefault();

            if (user == null)
            {
                log.LogInformation($"Could not find results for user: {UserId}");
                return(new BadRequestObjectResult(new
                {
                    message = "User " + UserId + " was not found",
                }));
            }

            bool commentsConnected = !string.IsNullOrEmpty(user?.CommentsUserId);

            return(new OkObjectResult(new
            {
                user = user,
                commentsConnected = commentsConnected,
            }));
        }
Beispiel #8
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }
            log.LogInformation($"C# HTTP trigger function {nameof(GetSecretContentFunction)} processed a request.");

            string SecretContentId = req.Query["id"];

            if (string.IsNullOrEmpty(SecretContentId))
            {
                return(new JsonResult(new
                {
                    error = true,
                    message = "Missing or empty id param",
                }));
            }

            var SecretContents = await _dbContext.SecretContents.Query(q => q.Where(w => w.Id == SecretContentId));

            var model = SecretContents.FirstOrDefault();

            if (model == null)
            {
                return(new JsonResult(new
                {
                    error = true,
                    message = $"Could not find content with id: {SecretContentId}"
                }));
            }

            return(new JsonResult(new
            {
                error = false,
                message = "",
                Content = model
            }));
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }

            log.LogWarning($"HTTP trigger function {nameof(RemoveUserCommentsAccountFunction)} request is authorized.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            User data = JsonConvert.DeserializeObject <User>(requestBody);

            if (data == null || string.IsNullOrEmpty(data?.UserId))
            {
                return(new BadRequestObjectResult(new
                {
                    message = "Request body is empty or UserId is missing",
                }));
            }

            var user = await _dbContext.Users.Query(q => q.Where(w => w.UserId == data.UserId));

            User model = user.FirstOrDefault();

            if (model == null)
            {
                return(new BadRequestObjectResult(new
                {
                    message = "User does not exsist"
                }));
            }

            model.CommentsUserId = null;

            await _dbContext.Users.Update(model);

            return(new OkResult());
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogWarning($"HTTP trigger function {nameof(HelloFunction)} received a request.");

            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }
            log.LogWarning($"HTTP trigger function {nameof(HelloFunction)} request is authorized.");

            // Get name from request body.
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            string  name        = data?.name;

            return(!string.IsNullOrWhiteSpace(name)
                ? (ActionResult) new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name the request body."));
        }
Beispiel #11
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }

            log.LogWarning($"HTTP trigger function {nameof(ConnectUserToCommentsFunction)} request is authorized.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            User   data        = JsonConvert.DeserializeObject <User>(requestBody);

            if (data == null || string.IsNullOrEmpty(data?.CommentsUserId) || string.IsNullOrEmpty(data?.UserId))
            {
                return(new BadRequestObjectResult(new
                {
                    message = "Request body is empty or is missing CommentsUserId or UserId fields",
                }));
            }

            var existingUser = await _dbContext.Users.Query(q => q.Where(w => w.UserId == data.UserId));

            User user = existingUser.FirstOrDefault();

            if (user == null)
            {
                await _dbContext.Users.Add(data);

                return(new OkResult());
            }

            if (user?.CommentsUserId == data.CommentsUserId)
            {
                return(new OkObjectResult(new
                {
                    message = "User already has the same comments account associated",
                }));
            }

            if (!string.IsNullOrEmpty(user?.CommentsUserId))
            {
                return(new ConflictObjectResult(new {
                    message = "Different comments account already connected"
                }));
            }

            var exisitingCommentsId = await _dbContext.Users.Query(q => q.Where(w => w.CommentsUserId == data.CommentsUserId));

            if (exisitingCommentsId.FirstOrDefault() != null)
            {
                return(new ConflictObjectResult(new
                {
                    message = "This comments account is already being used by another user",
                }));
            }

            user.CommentsUserId = data.CommentsUserId;
            await _dbContext.Users.Update(user);

            return(new OkResult());
        }
Beispiel #12
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }
            log.LogWarning($"HTTP trigger function {nameof(ReactFunction)} request is authorized.");

            Reaction data;

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            data = JsonConvert.DeserializeObject <Reaction>(requestBody);

            bool isNull = string.IsNullOrEmpty(data?.RuleGuid) || string.IsNullOrEmpty(data?.UserId) || data?.Type == null;

            if (data == null || isNull)
            {
                return(new JsonResult(new
                {
                    error = true,
                    message = "Request body is empty",
                }));
            }

            var results = await _dbContext.Reactions.Query(q => q.Where(w => w.RuleGuid == data.RuleGuid && w.UserId == data.UserId));

            var model = results.FirstOrDefault();

            log.LogInformation($"reactions on same rule by same user: {results.Count()}");

            if (model == null)
            {
                model = await _dbContext.Reactions.Add(data);

                log.LogInformation("Added new reaction. Id: {0}", model.Id);
            }
            else
            {
                log.LogInformation("Reaction already exists for user {0}", model.UserId);

                if (model.Type != data.Type)
                {
                    model.Type = data.Type;
                    model      = await _dbContext.Reactions.Update(model);

                    log.LogInformation("Updated reaction to " + model.Type);
                }
                else
                {
                    log.LogInformation("Reaction is the same. No change");
                }
            }

            log.LogInformation($"User: {model.UserId}, Type: {model.Type}, Rule: {model.RuleGuid}, Id: {model.Id}");

            return(new JsonResult(new
            {
                error = false,
                message = "",
                reaction = model.Type
            }));
        }