From 1322569cf6b7ab036659700bc2e7f7dcb8e79c0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemek=20Draga=C5=84czuk?= Date: Sun, 16 Feb 2020 16:05:09 +0100 Subject: [PATCH] Added a basic input validation for shortUrl --- src/main/java/tk/draganczuk/url/Routes.java | 15 +++++++++++---- src/main/java/tk/draganczuk/url/Utils.java | 9 +++++++++ src/main/resources/public/index.html | 5 +++-- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/main/java/tk/draganczuk/url/Routes.java b/src/main/java/tk/draganczuk/url/Routes.java index dad75b8..2ad5fd1 100644 --- a/src/main/java/tk/draganczuk/url/Routes.java +++ b/src/main/java/tk/draganczuk/url/Routes.java @@ -1,5 +1,6 @@ package tk.draganczuk.url; +import org.eclipse.jetty.http.HttpStatus; import spark.Request; import spark.Response; @@ -29,15 +30,21 @@ public class Routes { shortUrl = Utils.randomString(); } - return urlFile.addUrl(longUrl, shortUrl); + if (Utils.validate(shortUrl)) { + return urlFile.addUrl(longUrl, shortUrl); + } else { + res.status(HttpStatus.BAD_REQUEST_400); + return "shortUrl not valid ([a-z0-9]+)"; + } } - public static String goToLongUrl(Request req, Response res){ + + public static String goToLongUrl(Request req, Response res) { String shortUrl = req.params("shortUrl"); var longUrlOpt = urlFile - .findForShortUrl(shortUrl); + .findForShortUrl(shortUrl); - if(longUrlOpt.isEmpty()){ + if (longUrlOpt.isEmpty()) { res.status(404); return ""; } diff --git a/src/main/java/tk/draganczuk/url/Utils.java b/src/main/java/tk/draganczuk/url/Utils.java index efa312a..9292067 100644 --- a/src/main/java/tk/draganczuk/url/Utils.java +++ b/src/main/java/tk/draganczuk/url/Utils.java @@ -1,10 +1,14 @@ package tk.draganczuk.url; import java.util.Random; +import java.util.regex.Pattern; public class Utils { private static final Random random = new Random(System.currentTimeMillis()); + private static final String SHORT_URL_PATTERN = "[a-z0-9]+"; + private static final Pattern PATTERN = Pattern.compile(SHORT_URL_PATTERN); + public static String randomString() { int leftLimit = 48; // numeral '0' int rightLimit = 122; // letter 'z' @@ -18,4 +22,9 @@ public class Utils { StringBuilder::append) .toString(); } + + public static boolean validate(String shortUrl) { + return PATTERN.matcher(shortUrl) + .matches(); + } } diff --git a/src/main/resources/public/index.html b/src/main/resources/public/index.html index 988384d..e53d4fe 100644 --- a/src/main/resources/public/index.html +++ b/src/main/resources/public/index.html @@ -30,11 +30,12 @@ Add new URL
- +
- +