mirror of
https://github.com/Floriansylvain/RenewCMS.git
synced 2026-08-19 11:43:22 +02:00
clean: moved funcs to specific files + GetPage usecase/repo
This commit is contained in:
+3
-3
@@ -20,7 +20,7 @@ func getArticle(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
article, err := container.GetArticleUseCase.GetArticle(uint32(id))
|
||||
article, err := Container.GetArticleUseCase.GetArticle(uint32(id))
|
||||
if err != nil {
|
||||
http.Error(w, "The requested resource, identified by its unique ID, could not be found on the server.", http.StatusNotFound)
|
||||
return
|
||||
@@ -44,7 +44,7 @@ func postArticle(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
createdArticle, err := container.CreateArticleUseCase.CreateArticle(CreateArticleCommand{
|
||||
createdArticle, err := Container.CreateArticleUseCase.CreateArticle(CreateArticleCommand{
|
||||
Title: article.Title,
|
||||
Body: article.Body,
|
||||
})
|
||||
@@ -58,7 +58,7 @@ func postArticle(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func listArticles(w http.ResponseWriter, _ *http.Request) {
|
||||
articles := container.ListArticlesUseCase.ListArticles()
|
||||
articles := Container.ListArticlesUseCase.ListArticles()
|
||||
articlesJson, _ := json.Marshal(articles)
|
||||
|
||||
_, _ = w.Write(articlesJson)
|
||||
|
||||
+7
-7
@@ -45,8 +45,8 @@ func SetJwtCookie(w *http.ResponseWriter, userId uint32) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func isUserTableEmpty() bool {
|
||||
users := container.ListUsersUseCase.ListUsers()
|
||||
func IsUserTableEmpty() bool {
|
||||
users := Container.ListUsersUseCase.ListUsers()
|
||||
return len(users) == 0
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ func login(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
dbUser, err := container.GetUserUseCase.GetUserByUsername(user.Username)
|
||||
dbUser, err := Container.GetUserUseCase.GetUserByUsername(user.Username)
|
||||
if err != nil {
|
||||
http.Error(w, logsErrorMessage, http.StatusForbidden)
|
||||
return
|
||||
@@ -94,7 +94,7 @@ func login(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func register(w http.ResponseWriter, r *http.Request) {
|
||||
if !IsLoggedIn(r) && !isUserTableEmpty() {
|
||||
if !IsLoggedIn(r) && !IsUserTableEmpty() {
|
||||
http.Error(w, "You are not allowed to create a user. Log in or reset database.", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
@@ -112,7 +112,7 @@ func register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
createdUser, err := container.CreateUserUseCase.CreateUser(useCases.CreateUserCommand{
|
||||
createdUser, err := Container.CreateUserUseCase.CreateUser(useCases.CreateUserCommand{
|
||||
Username: user.Username,
|
||||
Password: user.Password,
|
||||
Email: user.Email,
|
||||
@@ -128,7 +128,7 @@ func register(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(message)
|
||||
}
|
||||
|
||||
func removeJwtCookie(w http.ResponseWriter) {
|
||||
func RemoveJwtCookie(w http.ResponseWriter) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "jwt",
|
||||
Value: "",
|
||||
@@ -141,7 +141,7 @@ func removeJwtCookie(w http.ResponseWriter) {
|
||||
}
|
||||
|
||||
func logout(w http.ResponseWriter, _ *http.Request) {
|
||||
removeJwtCookie(w)
|
||||
RemoveJwtCookie(w)
|
||||
message, _ := json.Marshal(map[string]interface{}{"message": "User logged out! HTTPonly jwt cookie deleted"})
|
||||
_, _ = w.Write(message)
|
||||
}
|
||||
|
||||
@@ -8,16 +8,17 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Container struct {
|
||||
type LocalContainer struct {
|
||||
CreateArticleUseCase *CreateArticleUseCase
|
||||
GetArticleUseCase *GetArticleUseCase
|
||||
ListArticlesUseCase *ListArticlesUseCase
|
||||
GetUserUseCase *GetUserUseCase
|
||||
CreateUserUseCase *CreateUserUseCase
|
||||
ListUsersUseCase *ListUsersUseCase
|
||||
GetPageUseCase *GetPageUseCase
|
||||
}
|
||||
|
||||
var container *Container
|
||||
var Container *LocalContainer
|
||||
|
||||
func setContainer(
|
||||
createArticle *CreateArticleUseCase,
|
||||
@@ -26,20 +27,22 @@ func setContainer(
|
||||
getUser *GetUserUseCase,
|
||||
createUser *CreateUserUseCase,
|
||||
listUsers *ListUsersUseCase,
|
||||
) *Container {
|
||||
container = &Container{
|
||||
getPage *GetPageUseCase,
|
||||
) *LocalContainer {
|
||||
Container = &LocalContainer{
|
||||
CreateArticleUseCase: createArticle,
|
||||
GetArticleUseCase: getArticle,
|
||||
ListArticlesUseCase: listArticle,
|
||||
GetUserUseCase: getUser,
|
||||
CreateUserUseCase: createUser,
|
||||
ListUsersUseCase: listUsers,
|
||||
GetPageUseCase: getPage,
|
||||
}
|
||||
return container
|
||||
return Container
|
||||
}
|
||||
|
||||
func InitContainer() {
|
||||
if container != nil {
|
||||
if Container != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -59,6 +62,7 @@ func InitContainer() {
|
||||
_ = digContainer.Provide(func(db *gorm.DB) *GetUserUseCase { return NewGetUserUseCase(db) })
|
||||
_ = digContainer.Provide(func(db *gorm.DB) *CreateUserUseCase { return NewCreateUserUseCase(db) })
|
||||
_ = digContainer.Provide(func(db *gorm.DB) *ListUsersUseCase { return NewListUsersUseCase(db) })
|
||||
_ = digContainer.Provide(NewGetPageUseCase)
|
||||
|
||||
_ = digContainer.Invoke(setContainer)
|
||||
}
|
||||
|
||||
+9
-120
@@ -1,22 +1,14 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed web/templates/*
|
||||
var templateFiles embed.FS
|
||||
|
||||
//go:embed web/static
|
||||
//go:embed static
|
||||
var staticFolder embed.FS
|
||||
|
||||
var contentTypes = map[string]string{
|
||||
@@ -29,110 +21,7 @@ var contentTypes = map[string]string{
|
||||
".ico": "image/x-icon",
|
||||
}
|
||||
|
||||
const loginRoute = "/login"
|
||||
|
||||
type LoginPage struct {
|
||||
IsError bool `json:"isError"`
|
||||
Error string `json:"error"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
func NewLoginPage(error string, username string) *LoginPage {
|
||||
return &LoginPage{
|
||||
IsError: strings.Compare(error, "") != 0,
|
||||
Error: error,
|
||||
Username: username,
|
||||
}
|
||||
}
|
||||
|
||||
func getPage(page string, data interface{}) ([]byte, error) {
|
||||
var processedHTML bytes.Buffer
|
||||
tmpl, err := template.ParseFS(templateFiles, "web/templates/"+page+".html")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = tmpl.Execute(&processedHTML, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return processedHTML.Bytes(), nil
|
||||
}
|
||||
|
||||
func getLoginPageHandler(loginPage *LoginPage) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if IsLoggedIn(r) {
|
||||
http.Redirect(w, r, "/home", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodPost {
|
||||
postLoginPage(w, r)
|
||||
return
|
||||
}
|
||||
bs, err := getPage("login", &loginPage)
|
||||
if err != nil {
|
||||
_, _ = w.Write([]byte(err.Error()))
|
||||
}
|
||||
_, _ = w.Write(bs)
|
||||
}
|
||||
}
|
||||
|
||||
func postLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
|
||||
credentials, err := json.Marshal(&UserLogin{
|
||||
Username: r.FormValue("username"),
|
||||
Password: r.FormValue("password"),
|
||||
})
|
||||
if err != nil {
|
||||
r.Method = http.MethodGet
|
||||
getLoginPageHandler(NewLoginPage("Invalid username or password.", r.FormValue("username")))(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := http.Post(
|
||||
"http://localhost:"+os.Getenv("PORT")+"/v1/auth/login",
|
||||
"application/json",
|
||||
bytes.NewBuffer(credentials))
|
||||
|
||||
if err != nil || response.StatusCode != http.StatusOK {
|
||||
r.Method = http.MethodGet
|
||||
getLoginPageHandler(NewLoginPage("Invalid username or password.", r.FormValue("username")))(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Set-Cookie", response.Header.Get("Set-Cookie"))
|
||||
|
||||
http.Redirect(w, r, "/home", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func getHomePage(w http.ResponseWriter, _ *http.Request) {
|
||||
navbarTmpl, _ := getPage("componentNavbar", nil)
|
||||
homeTmpl, _ := getPage("home", map[string]interface{}{
|
||||
"Navbar": template.HTML(navbarTmpl),
|
||||
})
|
||||
_, _ = w.Write(homeTmpl)
|
||||
}
|
||||
|
||||
func getLogin(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, loginRoute, http.StatusPermanentRedirect)
|
||||
}
|
||||
|
||||
func getLogout(w http.ResponseWriter, r *http.Request) {
|
||||
removeJwtCookie(w)
|
||||
http.Redirect(w, r, loginRoute, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func IsLoggedInMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !IsLoggedIn(r) {
|
||||
http.Redirect(w, r, loginRoute, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func staticFileServerWithContentType(fsys http.FileSystem) http.Handler {
|
||||
func StaticFileServerWithContentType(fsys http.FileSystem) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
if ext := filepath.Ext(path); ext != "" {
|
||||
@@ -147,9 +36,9 @@ func staticFileServerWithContentType(fsys http.FileSystem) http.Handler {
|
||||
func NewPageRouter() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
contentStatic, _ := fs.Sub(fs.FS(staticFolder), "web/static")
|
||||
contentStatic := fs.FS(staticFolder)
|
||||
|
||||
r.Handle("/static/*", staticFileServerWithContentType(http.FS(contentStatic)))
|
||||
r.Handle("/static/*", StaticFileServerWithContentType(http.FS(contentStatic)))
|
||||
r.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := http.FS(staticFolder).Open("favicon.ico")
|
||||
if err != nil {
|
||||
@@ -157,14 +46,14 @@ func NewPageRouter() http.Handler {
|
||||
}
|
||||
})
|
||||
|
||||
r.Get("/", getLogin)
|
||||
r.Get(loginRoute, getLoginPageHandler(NewLoginPage("", "")))
|
||||
r.Post(loginRoute, getLoginPageHandler(NewLoginPage("", "")))
|
||||
r.Get("/logout", getLogout)
|
||||
r.Get("/", GetLogin)
|
||||
r.Get(LoginRoute, GetLoginPageHandler(NewLoginPage("", "")))
|
||||
r.Post(LoginRoute, GetLoginPageHandler(NewLoginPage("", "")))
|
||||
r.Get("/logout", GetLogout)
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(IsLoggedInMiddleware)
|
||||
r.Get("/home", getHomePage)
|
||||
r.Get("/home", GetHomePage)
|
||||
})
|
||||
|
||||
return r
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const LoginRoute = "/login"
|
||||
|
||||
type LoginPage struct {
|
||||
IsError bool `json:"isError"`
|
||||
Error string `json:"error"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
func NewLoginPage(error string, username string) *LoginPage {
|
||||
return &LoginPage{
|
||||
IsError: strings.Compare(error, "") != 0,
|
||||
Error: error,
|
||||
Username: username,
|
||||
}
|
||||
}
|
||||
|
||||
func GetLoginPageHandler(loginPage *LoginPage) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if IsLoggedIn(r) {
|
||||
http.Redirect(w, r, "/home", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodPost {
|
||||
PostLoginPage(w, r)
|
||||
return
|
||||
}
|
||||
bs, err := Container.GetPageUseCase.GetPage("login", &loginPage)
|
||||
if err != nil {
|
||||
_, _ = w.Write([]byte(err.Error()))
|
||||
}
|
||||
_, _ = w.Write(bs)
|
||||
}
|
||||
}
|
||||
|
||||
func PostLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
|
||||
credentials, err := json.Marshal(&UserLogin{
|
||||
Username: r.FormValue("username"),
|
||||
Password: r.FormValue("password"),
|
||||
})
|
||||
if err != nil {
|
||||
r.Method = http.MethodGet
|
||||
GetLoginPageHandler(NewLoginPage("Invalid username or password.", r.FormValue("username")))(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := http.Post(
|
||||
"http://localhost:"+os.Getenv("PORT")+"/v1/auth/login",
|
||||
"application/json",
|
||||
bytes.NewBuffer(credentials))
|
||||
|
||||
if err != nil || response.StatusCode != http.StatusOK {
|
||||
r.Method = http.MethodGet
|
||||
GetLoginPageHandler(NewLoginPage("Invalid username or password.", r.FormValue("username")))(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Set-Cookie", response.Header.Get("Set-Cookie"))
|
||||
|
||||
http.Redirect(w, r, "/home", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func GetLogin(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, LoginRoute, http.StatusPermanentRedirect)
|
||||
}
|
||||
|
||||
func GetLogout(w http.ResponseWriter, r *http.Request) {
|
||||
RemoveJwtCookie(w)
|
||||
http.Redirect(w, r, LoginRoute, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func IsLoggedInMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !IsLoggedIn(r) {
|
||||
http.Redirect(w, r, LoginRoute, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func GetHomePage(w http.ResponseWriter, _ *http.Request) {
|
||||
navbarTmpl, _ := Container.GetPageUseCase.GetPage("componentNavbar", nil)
|
||||
homeTmpl, _ := Container.GetPageUseCase.GetPage("home", map[string]interface{}{
|
||||
"Navbar": template.HTML(navbarTmpl),
|
||||
})
|
||||
_, _ = w.Write(homeTmpl)
|
||||
}
|
||||
|
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 1.8 KiB |
@@ -1,32 +0,0 @@
|
||||
<nav class="navbar navbar-expand-lg bg-body-tertiary">
|
||||
<div class="container">
|
||||
<div class="d-flex gap-2 justify-content-center align-items-center">
|
||||
<img src="/static/gohcms-favicon-128.png" alt="Logo" style="width: 2.5rem"/>
|
||||
<a class="navbar-brand h1 my-auto" href="https://github.com/Floriansylvain/GohCMS" target="_blank">
|
||||
GohCMS
|
||||
</a>
|
||||
</div>
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
|
||||
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="collapse navbar-collapse" id="navbarNav">
|
||||
<ul class="navbar-nav me-auto">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/home">Accueil</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="#">Link 2</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="#">Link 3</a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul class="navbar-nav">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link disconnect-link" href="/logout">Se déconnecter</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
@@ -1,21 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta content="width=device-width, initial-scale=1.0" name="viewport">
|
||||
<title>GohCMS | Accueil</title>
|
||||
|
||||
<link rel="stylesheet" href="/static/bootstrap.min.css" type="text/css">
|
||||
<script src="/static/bootstrap.min.js"
|
||||
type="application/javascript"
|
||||
defer></script>
|
||||
|
||||
</head>
|
||||
<body class="text-dark">
|
||||
{{.Navbar}}
|
||||
<div class="container mt-3 text-black-50">
|
||||
<h1>Accueil</h1>
|
||||
<p>Bienvenue sur GohCMS !</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,89 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta content="width=device-width, initial-scale=1.0" name="viewport">
|
||||
<title>GohCMS | Connexion</title>
|
||||
|
||||
<link rel="stylesheet" href="/static/bootstrap.min.css" type="text/css">
|
||||
<script src="/static/bootstrap.min.js"
|
||||
type="application/javascript"
|
||||
defer></script>
|
||||
|
||||
<style>
|
||||
.form-container {
|
||||
max-width: 24rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="d-flex min-vh-100 vw-100 justify-content-center align-items-center text-dark">
|
||||
<div class="container">
|
||||
<div class="d-flex flex-column gap-5 m-auto form-container">
|
||||
<h1>GohCMS</h1>
|
||||
<form action="login" class="" method="POST">
|
||||
<div class="d-flex flex-column gap-4">
|
||||
<div class="form-floating">
|
||||
<input class="form-control {{ if .IsError }} is-invalid {{ end }}"
|
||||
id="username"
|
||||
name="username"
|
||||
placeholder="Nom d'utilisateur"
|
||||
required
|
||||
type="text"
|
||||
value="{{.Username}}">
|
||||
<label for="username">Nom d'utilisateur</label>
|
||||
</div>
|
||||
<div class="form-floating">
|
||||
<input class="form-control {{ if .IsError }} is-invalid {{ end }}"
|
||||
id="password"
|
||||
name="password"
|
||||
placeholder="Mot de passe"
|
||||
required
|
||||
type="password">
|
||||
<label for="password">Mot de passe</label>
|
||||
<div class="invalid-feedback">{{.Error}}</div>
|
||||
</div>
|
||||
<button id="loginFormButton" class="btn btn-primary" disabled type="submit">
|
||||
<span class="loginFormButtonLoading visually-hidden spinner-border spinner-border-sm"
|
||||
role="status"></span>
|
||||
<span class="loginFormButtonDefault">Se connecter</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const button = document.querySelector("#loginFormButton")
|
||||
const inputs = document.querySelectorAll('input')
|
||||
|
||||
function formFieldsEmpty() {
|
||||
return Array.from(inputs).some((input) => input.value === "")
|
||||
}
|
||||
|
||||
function setButtonDisabled() {
|
||||
button.disabled = formFieldsEmpty() ? "disabled" : ""
|
||||
}
|
||||
|
||||
function setButtonLoading() {
|
||||
button.classList.add("disabled")
|
||||
button.querySelector(".loginFormButtonDefault").classList.add("visually-hidden")
|
||||
button.querySelector(".loginFormButtonLoading").classList.remove("visually-hidden")
|
||||
}
|
||||
|
||||
function onLoginFormSubmit(event) {
|
||||
event.preventDefault()
|
||||
setButtonLoading()
|
||||
event.target.submit()
|
||||
}
|
||||
|
||||
function onInput(event) {
|
||||
if (event.target.tagName === "INPUT") setButtonDisabled()
|
||||
}
|
||||
|
||||
window.addEventListener('submit', onLoginFormSubmit)
|
||||
window.addEventListener('input', onInput)
|
||||
setButtonDisabled()
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user