From 0dd12627cf1f6a8031fbf77578142c3ae1d5722a Mon Sep 17 00:00:00 2001 From: Florian Sylvain Date: Thu, 20 Oct 2022 13:07:06 +0200 Subject: [PATCH] Added auth check on all routes --- cmd/main.go | 6 +++--- internal/auth.go | 20 ++++++++++++++++++++ web/admin-gui/src/views/Home.vue | 4 +++- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 7ea0a48..28fd106 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -20,9 +20,9 @@ func initGin() { r.GET("/ping", internal.Ping) - r.GET("/get-all-articles", internal.GetAllArticles) - r.POST("/add-article", internal.AddArticle) - r.DELETE("/delete-article", internal.DeleteArticle) + r.GET("/get-all-articles", internal.AuthCheck, internal.GetAllArticles) + r.POST("/add-article", internal.AuthCheck, internal.AddArticle) + r.DELETE("/delete-article", internal.AuthCheck, internal.DeleteArticle) r.POST("/login", internal.LoginUser) r.POST("/logout", internal.LogoutUser) diff --git a/internal/auth.go b/internal/auth.go index 1ee4e26..96672b6 100644 --- a/internal/auth.go +++ b/internal/auth.go @@ -78,3 +78,23 @@ func LogoutUser(c *gin.Context) { removeSession(user) SendOkMessageToClient(c, "User successfully logged out.") } + +func AuthCheck(c *gin.Context) { + var user User + username, password, isOk := c.Request.BasicAuth() + if !isOk { + SendErrorMessageToClient(c, "Incorrect or missing user credentials.") + c.Abort() + return + } + + user.Email = username + user.Password = password + user.Password = getUserHashedPassword(user) + + if !isUserLoggedIn(user) { + SendErrorMessageToClient(c, "Authentification failed, credentials could be wrong, user may not be logged in, session may have expired.") + c.Abort() + return + } +} diff --git a/web/admin-gui/src/views/Home.vue b/web/admin-gui/src/views/Home.vue index 0862bff..4fd8a30 100644 --- a/web/admin-gui/src/views/Home.vue +++ b/web/admin-gui/src/views/Home.vue @@ -16,6 +16,7 @@ onMounted(async function() { function addArticle() { fetch("http://localhost:8080/add-article", { method: "POST", + headers: {"Authorization" : `Basic ${btoa(`${username.value}:${password.value}`)}`}, body: JSON.stringify({ id_name: `${Math.random() * 100}`, content: {}, @@ -27,7 +28,7 @@ function addArticle() { } function logArticles() { - fetch("http://localhost:8080/get-all-articles") + fetch("http://localhost:8080/get-all-articles", {headers: {"Authorization" : `Basic ${btoa(`${username.value}:${password.value}`)}`}}) .then(response => response.json()) .then(result => console.log(result)) } @@ -35,6 +36,7 @@ function logArticles() { function deleteArticle(articleID: String) { fetch("http://localhost:8080/delete-article", { method: "DELETE", + headers: {"Authorization" : `Basic ${btoa(`${username.value}:${password.value}`)}`}, body: JSON.stringify({ id_name: articleID })