feat: setup/register flow impl and login refactor

This commit is contained in:
Florian Sylvain
2023-08-13 00:24:50 +02:00
parent 5c61796313
commit 04ebbfda87
7 changed files with 292 additions and 33 deletions
@@ -19,7 +19,10 @@
<body class="d-flex min-vh-100 vw-100 justify-content-center align-items-center text-dark"> <body class="d-flex min-vh-100 vw-100 justify-content-center align-items-center text-dark">
<div class="container"> <div class="container">
<div class="d-flex flex-column gap-5 m-auto form-container"> <div class="d-flex flex-column gap-5 m-auto form-container">
<h1>GohCMS</h1> <div>
<h1>GohCMS</h1>
<h2>Connexion</h2>
</div>
<form action="login" class="" method="POST"> <form action="login" class="" method="POST">
<div class="d-flex flex-column gap-4"> <div class="d-flex flex-column gap-4">
<div class="form-floating"> <div class="form-floating">
@@ -0,0 +1,102 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>GohCMS | Installation</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">
<div>
<h1>GohCMS</h1>
<h2>Création du compte administrateur</h2>
</div>
<form action="register" class="" method="POST">
<div class="d-flex flex-column gap-4">
<div class="form-floating">
<input class="form-control {{ if .PageError.IsError }} is-invalid {{ end }}"
id="email"
name="email"
placeholder="E-mail"
required
type="email"
value="{{.Email}}">
<label for="email">E-mail</label>
</div>
<div class="form-floating">
<input class="form-control {{ if .PageError.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 .PageError.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">{{.PageError.Message}}</div>
</div>
<button id="registerFormButton" class="btn btn-primary" disabled type="submit">
<span class="registerFormButtonLoading visually-hidden spinner-border spinner-border-sm"
role="status"></span>
<span class="registerFormButtonDefault">Suivant</span>
</button>
</div>
</form>
</div>
</div>
<script>
const button = document.querySelector("#registerFormButton")
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(".registerFormButtonDefault").classList.add("visually-hidden")
button.querySelector(".registerFormButtonLoading").classList.remove("visually-hidden")
}
function onRegisterFormSubmit(event) {
event.preventDefault()
setButtonLoading()
event.target.submit()
}
function onInput(event) {
if (event.target.tagName === "INPUT") setButtonDisabled()
}
window.addEventListener('submit', onRegisterFormSubmit)
window.addEventListener('input', onInput)
setButtonDisabled()
</script>
</body>
</html>
@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>GohCMS | Installation</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">
<div>
<h1>GohCMS</h1>
<h2>Installation terminée !</h2>
</div>
<p>GohCMS est maintenant prêt à être utilisé.</p>
<button id="finalSetupFormButton" class="btn btn-primary" type="button">
<span class="finalSetupFormButtonLoading visually-hidden spinner-border spinner-border-sm"
role="status"></span>
<span class="finalSetupFormButtonDefault">Terminer</span>
</button>
</div>
</div>
<script>
const button = document.querySelector("#finalSetupFormButton")
function setButtonLoading() {
button.classList.add("disabled")
button.querySelector(".finalSetupFormButtonDefault").classList.add("visually-hidden")
button.querySelector(".finalSetupFormButtonLoading").classList.remove("visually-hidden")
}
function onFinalSetupFormSubmit() {
setButtonLoading()
window.location.replace("/home")
}
button.addEventListener('click', onFinalSetupFormSubmit)
</script>
</body>
</html>
+32 -2
View File
@@ -6,6 +6,7 @@ import (
"io/fs" "io/fs"
"net/http" "net/http"
"path/filepath" "path/filepath"
"strings"
) )
//go:embed static //go:embed static
@@ -26,6 +27,32 @@ type PageError struct {
IsError bool `json:"isError"` IsError bool `json:"isError"`
} }
func NewPageError(message string) *PageError {
return &PageError{
Message: message,
IsError: strings.Compare(message, "") != 0,
}
}
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 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 StaticFileServerWithContentType(fsys http.FileSystem) http.Handler { func StaticFileServerWithContentType(fsys http.FileSystem) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path path := r.URL.Path
@@ -52,12 +79,15 @@ func NewPageRouter() http.Handler {
}) })
r.Get("/", GetLogin) r.Get("/", GetLogin)
r.Get(LoginRoute, GetLoginPageHandler(NewLoginPage("", ""))) r.Get(LoginRoute, GetLoginPageHandler(EmptyLoginPage))
r.Post(LoginRoute, GetLoginPageHandler(NewLoginPage("", ""))) r.Post(LoginRoute, GetLoginPageHandler(EmptyLoginPage))
r.Get("/register", GetRegisterPageHandler(EmptyRegisterPage))
r.Post("/register", GetRegisterPageHandler(EmptyRegisterPage))
r.Get("/logout", GetLogout) r.Get("/logout", GetLogout)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(IsLoggedInMiddleware) r.Use(IsLoggedInMiddleware)
r.Get("/register-confirm", GetRegisterConfirmPage)
r.Get("/home", GetHomePage) r.Get("/home", GetHomePage)
}) })
+15 -30
View File
@@ -5,7 +5,6 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"os" "os"
"strings"
) )
const LoginRoute = "/login" const LoginRoute = "/login"
@@ -15,14 +14,9 @@ type LoginPage struct {
Username string `json:"username"` Username string `json:"username"`
} }
func NewLoginPage(error string, username string) *LoginPage { var EmptyLoginPage = &LoginPage{
return &LoginPage{ PageError: NewPageError(""),
PageError: &PageError{ Username: "",
IsError: strings.Compare(error, "") != 0,
Message: error,
},
Username: username,
}
} }
func GetLoginPageHandler(loginPage *LoginPage) http.HandlerFunc { func GetLoginPageHandler(loginPage *LoginPage) http.HandlerFunc {
@@ -35,6 +29,10 @@ func GetLoginPageHandler(loginPage *LoginPage) http.HandlerFunc {
PostLoginPage(w, r) PostLoginPage(w, r)
return return
} }
if IsUserTableEmpty() {
http.Redirect(w, r, "/register", http.StatusSeeOther)
return
}
bs, err := Container.GetPageUseCase.GetPage("login", &loginPage) bs, err := Container.GetPageUseCase.GetPage("login", &loginPage)
if err != nil { if err != nil {
_, _ = w.Write([]byte(err.Error())) _, _ = w.Write([]byte(err.Error()))
@@ -52,7 +50,10 @@ func PostLoginPage(w http.ResponseWriter, r *http.Request) {
}) })
if err != nil { if err != nil {
r.Method = http.MethodGet r.Method = http.MethodGet
GetLoginPageHandler(NewLoginPage("Invalid username or password.", r.FormValue("username")))(w, r) GetLoginPageHandler(&LoginPage{
PageError: NewPageError("Invalid form data format."),
Username: r.FormValue("username"),
})(w, r)
return return
} }
@@ -63,7 +64,10 @@ func PostLoginPage(w http.ResponseWriter, r *http.Request) {
if err != nil || response.StatusCode != http.StatusOK { if err != nil || response.StatusCode != http.StatusOK {
r.Method = http.MethodGet r.Method = http.MethodGet
GetLoginPageHandler(NewLoginPage("Invalid username or password.", r.FormValue("username")))(w, r) GetLoginPageHandler(&LoginPage{
PageError: NewPageError("Invalid username or password."),
Username: r.FormValue("username"),
})(w, r)
return return
} }
@@ -71,22 +75,3 @@ func PostLoginPage(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/home", http.StatusSeeOther) 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)
})
}
+76
View File
@@ -0,0 +1,76 @@
package api
import (
"bytes"
"encoding/json"
"net/http"
"os"
)
type RegisterPage struct {
PageError *PageError `json:"error"`
Username string `json:"username"`
Email string `json:"email"`
}
var EmptyRegisterPage = &RegisterPage{
PageError: NewPageError(""),
Username: "",
Email: "",
}
func GetRegisterPageHandler(registerPage *RegisterPage) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if IsLoggedIn(r) || !IsUserTableEmpty() {
http.Redirect(w, r, "/home", http.StatusSeeOther)
return
}
if r.Method == http.MethodPost {
PostRegisterPage(w, r)
return
}
bs, err := Container.GetPageUseCase.GetPage("setup1", &registerPage)
if err != nil {
_, _ = w.Write([]byte(err.Error()))
}
_, _ = w.Write(bs)
}
}
func PostRegisterPage(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
credentials, err := json.Marshal(&UserRegister{
Username: r.FormValue("username"),
Password: r.FormValue("password"),
Email: r.FormValue("email"),
})
if err != nil {
r.Method = http.MethodGet
GetRegisterPageHandler(&RegisterPage{
PageError: NewPageError("Invalid register form data format."),
Username: r.FormValue("username"),
Email: r.FormValue("email"),
})(w, r)
return
}
response, err := http.Post(
"http://localhost:"+os.Getenv("PORT")+"/v1/auth/register",
"application/json",
bytes.NewBuffer(credentials))
if err != nil || response.StatusCode != http.StatusOK {
r.Method = http.MethodGet
GetRegisterPageHandler(&RegisterPage{
PageError: NewPageError("Username should be between 3 and 20 characters long, password should be between 8 and 20 characters long, and email should be a valid email address."),
Username: r.FormValue("username"),
Email: r.FormValue("email"),
})(w, r)
return
}
w.Header().Set("Set-Cookie", response.Header.Get("Set-Cookie"))
http.Redirect(w, r, "/register-confirm", http.StatusSeeOther)
}
+10
View File
@@ -0,0 +1,10 @@
package api
import (
"net/http"
)
func GetRegisterConfirmPage(w http.ResponseWriter, _ *http.Request) {
registerConfirmTmpl, _ := Container.GetPageUseCase.GetPage("setup2", nil)
_, _ = w.Write(registerConfirmTmpl)
}