public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "UrlRedirect/{shortUrl}")] HttpRequestMessage req, string shortUrl, ExecutionContext context, ILogger log) { log.LogInformation($"C# HTTP trigger function processed for Url: {shortUrl}"); string redirectUrl = "https://costv.guide"; if (!string.IsNullOrWhiteSpace(shortUrl)) { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); redirectUrl = config["defaultRedirectUrl"]; StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); var tempUrl = new ShortUrlEntity(string.Empty, shortUrl); var newUrl = await stgHelper.GetShortUrlEntity(tempUrl); if (newUrl != null) { log.LogInformation($"Found it: {newUrl.Url}"); newUrl.Clicks++; stgHelper.SaveClickStatsEntity(new ClickStatsEntity(newUrl.RowKey)); await stgHelper.SaveShortUrlEntity(newUrl); redirectUrl = WebUtility.UrlDecode(newUrl.Url); } } else { log.LogInformation("Bad Link, resorting to fallback."); } var currentQuery = HttpUtility.ParseQueryString(req.RequestUri.Query); var redirectUriBuilder = new UriBuilder(redirectUrl); var redirectQuery = HttpUtility.ParseQueryString(redirectUriBuilder.Query); foreach (var key in currentQuery.AllKeys) { redirectQuery[key] = currentQuery[key]; redirectUriBuilder.Query = redirectQuery.ToString(); } var response = req.CreateResponse(HttpStatusCode.Redirect); response.Headers.Add("Location", redirectUriBuilder.ToString()); return(response); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "UrlRedirect/{shortUrl}")] HttpRequestMessage req, string shortUrl, ExecutionContext context, ILogger log) { log.LogInformation($"C# HTTP trigger function processed for Url: {shortUrl}"); string redirectUrl = "https://azure.com"; if (!String.IsNullOrWhiteSpace(shortUrl)) { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); redirectUrl = config["defaultRedirectUrl"]; StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); var tempUrl = new ShortUrlEntity(string.Empty, shortUrl); var newUrl = await stgHelper.GetShortUrlEntity(tempUrl); if (newUrl != null) { log.LogInformation($"Found it: {newUrl.Url}"); newUrl.Clicks++; var host = req.RequestUri.GetLeftPart(UriPartial.Authority); var shortUrlAddress = Utility.GetShortUrl(host, shortUrl); await RunWebhooks(stgHelper, new ClickStatsResponse(newUrl.Title, shortUrlAddress, newUrl.Url, newUrl.Clicks)); stgHelper.SaveClickStatsEntity(new ClickStatsEntity(newUrl.RowKey)); await stgHelper.SaveShortUrlEntity(newUrl); redirectUrl = newUrl.Url; } } else { log.LogInformation("Bad Link, resorting to fallback."); } var res = req.CreateResponse(HttpStatusCode.Redirect); res.Headers.Add("Location", redirectUrl); return(res); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context, ClaimsPrincipal principal) { log.LogInformation($"C# HTTP trigger function processed this request: {req}"); string userId = string.Empty; ShortRequest input; var result = new ShortResponse(); try { var invalidRequest = Utility.CatchUnauthorize(principal, log); if (invalidRequest != null) { return(invalidRequest); } else { userId = principal.FindFirst(ClaimTypes.GivenName).Value; log.LogInformation("Authenticated user {user}.", userId); } // Validation of the inputs if (req == null) { return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound })); } using (var reader = new StreamReader(req.Body)) { var strBody = reader.ReadToEnd(); input = JsonSerializer.Deserialize <ShortRequest>(strBody, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (input == null) { return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound })); } } // If the Url parameter only contains whitespaces or is empty return with BadRequest. if (string.IsNullOrWhiteSpace(input.Url)) { return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.BadRequest, Message = "The url parameter can not be empty." })); } // Validates if input.url is a valid aboslute url, aka is a complete refrence to the resource, ex: http(s)://google.com if (!Uri.IsWellFormedUriString(input.Url, UriKind.Absolute)) { return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.BadRequest, Message = $"{input.Url} is not a valid absolute Url. The Url parameter must start with 'http://' or 'http://'." })); } var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); string longUrl = input.Url.Trim(); string vanity = string.IsNullOrWhiteSpace(input.Vanity) ? "" : input.Vanity.Trim(); string title = string.IsNullOrWhiteSpace(input.Title) ? "" : input.Title.Trim(); ShortUrlEntity newRow; if (!string.IsNullOrEmpty(vanity)) { newRow = new ShortUrlEntity(longUrl, vanity, title, input.Schedules); if (await stgHelper.IfShortUrlEntityExist(newRow)) { return(new ConflictObjectResult(new{ Message = "This Short URL already exist." })); } } else { newRow = new ShortUrlEntity(longUrl, await Utility.GetValidEndUrl(vanity, stgHelper), title, input.Schedules); } await stgHelper.SaveShortUrlEntity(newRow); var host = string.IsNullOrEmpty(config["customDomain"]) ? req.Host.Host: config["customDomain"].ToString(); result = new ShortResponse(host, newRow.Url, newRow.RowKey, newRow.Title); log.LogInformation("Short Url created."); } catch (Exception ex) { log.LogError(ex, "An unexpected error was encountered."); return(new BadRequestObjectResult(new { message = ex.Message, StatusCode = HttpStatusCode.BadRequest })); } return(new OkObjectResult(result)); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log, ExecutionContext context) { log.LogInformation($"C# HTTP trigger function processed this request: {req}"); // Validation of the inputs if (req == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>(); if (input == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } // If the Url parameter only contains whitespaces or is empty return with BadRequest. if (string.IsNullOrWhiteSpace(input.Url)) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "The url parameter can not be empty.")); } // Validates if input.url is a valid aboslute url, aka is a complete refrence to the resource, ex: http(s)://google.com if (!Uri.IsWellFormedUriString(input.Url, UriKind.Absolute)) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, $"{input.Url} is not a valid absolute Url. The Url parameter must start with 'http://' or 'http://'.")); } var result = new ShortResponse(); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); try { string longUrl = input.Url.Trim(); string vanity = string.IsNullOrWhiteSpace(input.Vanity) ? "" : input.Vanity.Trim(); string title = string.IsNullOrWhiteSpace(input.Title) ? "" : input.Title.Trim(); ShortUrlEntity newRow; if (!string.IsNullOrEmpty(vanity)) { newRow = new ShortUrlEntity(longUrl, vanity, title); if (await stgHelper.IfShortUrlEntityExist(newRow)) { return(req.CreateResponse(HttpStatusCode.Conflict, "This Short URL already exist.")); } } else { newRow = new ShortUrlEntity(longUrl, Utility.GetValidEndUrl(vanity), title); } await stgHelper.SaveShortUrlEntity(newRow); var host = req.RequestUri.GetLeftPart(UriPartial.Authority); log.LogInformation($"-> host = {host}"); result = new ShortResponse(host, newRow.Url, newRow.RowKey, newRow.Title); log.LogInformation("Short Url created."); } catch (Exception ex) { log.LogError(ex, "An unexpected error was encountered."); return(req.CreateResponse(HttpStatusCode.BadRequest, ex)); } return(req.CreateResponse(HttpStatusCode.OK, result)); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log, ExecutionContext context) { log.LogInformation($"C# HTTP trigger function processed this request: {req}"); // Validation of the inputs if (req == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>(); if (input == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } var result = new ShortResponse(); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); try { string longUrl = input.Url.Trim(); string vanity = input.Vanity.Trim(); ShortUrlEntity newRow; if (!string.IsNullOrEmpty(vanity)) { newRow = new ShortUrlEntity(longUrl, vanity); if (await stgHelper.IfShortUrlEntityExist(newRow)) { return(req.CreateResponse(HttpStatusCode.Conflict, "This Short URL already exist.")); } } else { newRow = new ShortUrlEntity(longUrl, await Utility.GetValidEndUrl(vanity, stgHelper)); } await stgHelper.SaveShortUrlEntity(newRow); var host = req.RequestUri.GetLeftPart(UriPartial.Authority); log.LogInformation($"-> host = {host}"); result = new ShortResponse(host, newRow.Url, newRow.RowKey); log.LogInformation("Short Url created."); } catch (Exception ex) { log.LogError(ex, "An unexpected error was encountered."); return(req.CreateResponse(HttpStatusCode.BadRequest, ex)); } return(req.CreateResponse(HttpStatusCode.OK, result)); }