mirror of
https://github.com/Floriansylvain/RenewCMS.git
synced 2026-08-19 11:43:22 +02:00
refac: separated api content into sub-packages & renamed usecases
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"html/template"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func GetHomePage(w http.ResponseWriter, _ *http.Request) {
|
||||
navbarTmpl, _ := api.Container.GetPageUseCase.GetPage("componentNavbar", nil)
|
||||
homeTmpl, _ := api.Container.GetPageUseCase.GetPage("home", map[string]interface{}{
|
||||
"Navbar": template.HTML(navbarTmpl),
|
||||
"Head": headTmpl,
|
||||
})
|
||||
_, _ = w.Write(homeTmpl)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
func GetPageIntegration(w http.ResponseWriter, r *http.Request) {
|
||||
navbarTmpl, _ := api.Container.GetPageUseCase.GetPage("componentNavbar", nil)
|
||||
templ, _ := api.Container.GetPageUseCase.GetPage("integration", map[string]interface{}{
|
||||
"Navbar": template.HTML(navbarTmpl),
|
||||
"Head": headTmpl,
|
||||
"Host": os.Getenv("HOST"),
|
||||
})
|
||||
_, _ = w.Write(templ)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"GoCMS/api/controllers/auth"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const LoginRoute = "/login"
|
||||
|
||||
type LoginPage struct {
|
||||
PageError *PageError `json:"error"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
var EmptyLoginPage = &LoginPage{
|
||||
PageError: NewPageError(""),
|
||||
Username: "",
|
||||
}
|
||||
|
||||
func GetLoginPageHandler(loginPage *LoginPage) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if auth.IsLoggedIn(r) {
|
||||
http.Redirect(w, r, "/home", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodPost {
|
||||
PostLoginPage(w, r)
|
||||
return
|
||||
}
|
||||
if auth.IsUserTableEmpty() {
|
||||
http.Redirect(w, r, "/register", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
success, _ := url.QueryUnescape(r.URL.Query().Get("success"))
|
||||
failure, _ := url.QueryUnescape(r.URL.Query().Get("failure"))
|
||||
bs, _ := api.Container.GetPageUseCase.GetPage("login", map[string]interface{}{
|
||||
"PageError": loginPage.PageError,
|
||||
"Username": loginPage.Username,
|
||||
"Head": headTmpl,
|
||||
"Success": success,
|
||||
"Failure": failure,
|
||||
})
|
||||
_, _ = w.Write(bs)
|
||||
}
|
||||
}
|
||||
|
||||
func PostLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
|
||||
credentials := auth.LoginCredentials{
|
||||
Username: r.FormValue("username"),
|
||||
Password: r.FormValue("password"),
|
||||
}
|
||||
err := api.Validate.Struct(credentials)
|
||||
if err != nil {
|
||||
r.Method = http.MethodGet
|
||||
GetLoginPageHandler(&LoginPage{
|
||||
PageError: NewPageError("Invalid username or password format."),
|
||||
Username: r.FormValue("username"),
|
||||
})(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
dbUser, err := auth.GetUserFromCredentials(credentials)
|
||||
if err != nil {
|
||||
r.Method = http.MethodGet
|
||||
GetLoginPageHandler(&LoginPage{
|
||||
PageError: NewPageError("Invalid username or password combination."),
|
||||
Username: r.FormValue("username"),
|
||||
})(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
_ = auth.SetJwtCookie(&w, dbUser.ID)
|
||||
|
||||
http.Redirect(w, r, "/home", http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"GoCMS/api/controllers/auth"
|
||||
"GoCMS/api/controllers/image"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
var headTmpl template.HTML
|
||||
|
||||
var contentTypes = map[string]string{
|
||||
".css": "text/css",
|
||||
".js": "application/javascript",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".webp": "image/webp",
|
||||
".svg": "image/svg+xml",
|
||||
".ico": "image/x-icon",
|
||||
}
|
||||
|
||||
type PageError struct {
|
||||
Message string `json:"message"`
|
||||
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 !auth.IsLoggedIn(r) {
|
||||
http.Redirect(w, r, LoginRoute, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func IsVerifiedMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !auth.IsVerified(r) {
|
||||
http.Redirect(w, r, "/register/pending", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func IsNotVerifiedMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if auth.IsVerified(r) {
|
||||
http.Redirect(w, r, "/register/pending", 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) {
|
||||
auth.RemoveJwtCookie(w)
|
||||
http.Redirect(w, r, LoginRoute, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func StaticFileServerWithContentType(fsys http.FileSystem) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
filePath := filepath.Join("api/static", r.URL.Path)
|
||||
fileInfo, err := os.Stat(filePath)
|
||||
if err == nil && fileInfo.IsDir() {
|
||||
http.Error(w, "Folder direct access is disabled.", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if ext := filepath.Ext(path); ext != "" {
|
||||
if ct, ok := contentTypes[ext]; ok {
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000")
|
||||
w.Header().Set("Content-Type", ct)
|
||||
}
|
||||
}
|
||||
http.FileServer(fsys).ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func InitHeadTmpl() {
|
||||
headTmplHtml, _ := api.Container.GetPageUseCase.GetPage("utilsHead", nil)
|
||||
headTmpl = template.HTML(headTmplHtml)
|
||||
}
|
||||
|
||||
func NewPageRouter() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
InitHeadTmpl()
|
||||
|
||||
fileServer := StaticFileServerWithContentType(http.Dir("api/static"))
|
||||
r.Handle("/static/*", http.StripPrefix("/static/", fileServer))
|
||||
|
||||
r.Get("/", GetLogin)
|
||||
|
||||
r.Get(LoginRoute, GetLoginPageHandler(EmptyLoginPage))
|
||||
r.Post(LoginRoute, GetLoginPageHandler(EmptyLoginPage))
|
||||
|
||||
r.Get("/register", GetRegisterPageHandler(EmptyRegisterPage))
|
||||
r.Post("/register", GetRegisterPageHandler(EmptyRegisterPage))
|
||||
|
||||
r.Get("/logout", GetLogout)
|
||||
|
||||
r.Get("/register/reset/request", GetPasswordResetRequest)
|
||||
r.Post("/register/reset/request", PostPasswordResetRequest)
|
||||
|
||||
r.Get("/register/reset/validate", GetPasswordResetValidate)
|
||||
r.Post("/register/reset/validate", PostPasswordResetValidate)
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(IsLoggedInMiddleware)
|
||||
r.Use(IsNotVerifiedMiddleware)
|
||||
|
||||
r.Get("/register/pending", GetRegisterPendingPage)
|
||||
r.Post("/register/pending", PostRegisterPendingPage)
|
||||
|
||||
r.Get("/register/validate", GetRegisterValidatePage)
|
||||
})
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(IsLoggedInMiddleware)
|
||||
r.Use(IsVerifiedMiddleware)
|
||||
|
||||
r.Get("/home", GetHomePage)
|
||||
|
||||
r.Get("/post", GetPostsPage)
|
||||
|
||||
r.Get("/post/{id}/edit", GetPostEditPage)
|
||||
r.Post("/post/{id}/edit", PostPostEditPage)
|
||||
|
||||
r.Get("/post/{id}/delete", GetPostDeletePage)
|
||||
|
||||
r.Get("/post/create", GetPostCreatePage)
|
||||
r.Post("/post/create", PostPostCreatePage)
|
||||
|
||||
r.Post("/post/{id}/image/create", image.PostImage)
|
||||
|
||||
r.Get("/post/{id}/publish", GetPostPublishPage)
|
||||
r.Get("/post/{id}/unpublish", GetPostUnpublishPage)
|
||||
|
||||
r.Get("/integration", GetPageIntegration)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type PasswordResetRequest struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
var successMessage = "An email has been sent to the provided email address if it exists."
|
||||
|
||||
func GetPasswordResetRequest(w http.ResponseWriter, r *http.Request) {
|
||||
success := r.URL.Query().Get("success")
|
||||
email := r.URL.Query().Get("email")
|
||||
|
||||
bs, _ := api.Container.GetPageUseCase.GetPage("passwordResetRequest", map[string]interface{}{
|
||||
"Head": headTmpl,
|
||||
"Email": email,
|
||||
"Success": success,
|
||||
})
|
||||
_, _ = w.Write(bs)
|
||||
}
|
||||
|
||||
func PostPasswordResetRequest(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
passResetReq := PasswordResetRequest{
|
||||
Email: r.FormValue("email"),
|
||||
}
|
||||
var getRedirectUrl = "/register/reset/request?success=" + successMessage + "&email=" + passResetReq.Email
|
||||
|
||||
err := api.Validate.Struct(passResetReq)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, getRedirectUrl, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
fetchedUser, err := api.Container.GetUserUseCase.GetUserByEmail(passResetReq.Email)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, getRedirectUrl, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
verificationCode := uuid.NewString()
|
||||
updatedUser, _ := api.Container.UpdateUserUseCase.UpdatePasswordResetCode(fetchedUser.ID, verificationCode)
|
||||
|
||||
_ = api.Container.SendMailUseCase.SendMail(updatedUser.Email, "passwordReset", map[string]string{
|
||||
"Host": os.Getenv("HOST"),
|
||||
"VerificationCode": verificationCode,
|
||||
"Email": updatedUser.Email,
|
||||
})
|
||||
|
||||
http.Redirect(w, r, getRedirectUrl, http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
var PasswordLinkErrorMessage = "The reset password link you used is invalid."
|
||||
var PasswordLinkSuccessMessage = "Your account password was successfully updated."
|
||||
|
||||
func GetPasswordResetValidate(w http.ResponseWriter, r *http.Request) {
|
||||
failure := r.URL.Query().Get("failure")
|
||||
pageError := NewPageError("")
|
||||
if failure != "" {
|
||||
pageError = NewPageError(failure)
|
||||
}
|
||||
template, _ := api.Container.GetPageUseCase.GetPage("passwordResetValidate", map[string]interface{}{
|
||||
"Head": headTmpl,
|
||||
"Error": pageError,
|
||||
"Email": r.URL.Query().Get("email"),
|
||||
"Code": r.URL.Query().Get("c"),
|
||||
})
|
||||
_, _ = w.Write(template)
|
||||
}
|
||||
|
||||
func PostPasswordResetValidate(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
resetCode := r.FormValue("code")
|
||||
|
||||
var redirectionErrorLink = "/register/reset/validate?email=" + email + "&c=" + resetCode
|
||||
|
||||
if len(password) < 8 {
|
||||
http.Redirect(w, r, redirectionErrorLink+"&failure=Password length should be at least 8 characters.", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
fetchedUser, err := api.Container.GetUserUseCase.GetUserByEmail(email)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, redirectionErrorLink+"&failure="+PasswordLinkErrorMessage, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(fetchedUser.PasswordResetCode), []byte(resetCode))
|
||||
if err != nil {
|
||||
http.Redirect(w, r, redirectionErrorLink+"&failure="+PasswordLinkErrorMessage, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
_, _ = api.Container.UpdateUserUseCase.UpdatePassword(fetchedUser.ID, password)
|
||||
_, _ = api.Container.UpdateUserUseCase.UpdatePasswordResetCode(fetchedUser.ID, "")
|
||||
|
||||
http.Redirect(w, r, "/login?success="+PasswordLinkSuccessMessage, http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"GoCMS/useCases"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type PostCreatePageError struct {
|
||||
IsError bool
|
||||
Message string
|
||||
}
|
||||
|
||||
func GetPostCreatePageTemplate(postName string, errorMessage string) ([]byte, error) {
|
||||
navbarTmpl, _ := api.Container.GetPageUseCase.GetPage("componentNavbar", nil)
|
||||
return api.Container.GetPageUseCase.GetPage("postCreate", map[string]interface{}{
|
||||
"Navbar": template.HTML(navbarTmpl),
|
||||
"Head": headTmpl,
|
||||
"PageError": PostCreatePageError{
|
||||
IsError: errorMessage != "",
|
||||
Message: errorMessage,
|
||||
},
|
||||
"Name": postName,
|
||||
})
|
||||
}
|
||||
|
||||
func PostPostCreatePage(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
|
||||
postName := r.FormValue("name")
|
||||
pattern := regexp.MustCompile("^[a-zA-Z0-9À-ÖØ-öø-ÿĀ-ſḀ-ỿ ]{3,50}$")
|
||||
|
||||
if !pattern.MatchString(postName) {
|
||||
postsTmpl, _ := GetPostCreatePageTemplate(postName, "Name should be alphanumeric, and between 3 and 50 characters.")
|
||||
_, _ = w.Write(postsTmpl)
|
||||
return
|
||||
}
|
||||
|
||||
post, err := api.Container.CreatePostUseCase.CreatePost(useCases.CreatePostCommand{
|
||||
Title: postName,
|
||||
Body: "",
|
||||
})
|
||||
if err != nil {
|
||||
postsTmpl, _ := GetPostCreatePageTemplate(postName, "Something went wrong when creating the post, please contact admin.")
|
||||
_, _ = w.Write(postsTmpl)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/post/"+strconv.Itoa(int(post.ID))+"/edit", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func GetPostCreatePage(w http.ResponseWriter, _ *http.Request) {
|
||||
postsTmpl, _ := GetPostCreatePageTemplate("", "")
|
||||
_, _ = w.Write(postsTmpl)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"GoCMS/api/controllers/post"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func GetPostDeletePage(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||
if err != nil {
|
||||
http.Error(w, post.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
localPost, err := api.Container.GetPostUseCase.GetPost(uint32(id))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println(localPost.Images)
|
||||
for _, image := range localPost.Images {
|
||||
err = api.Container.DeleteImageUseCase.DeleteImage(image.ID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err = api.Container.DeletePostUseCase.DeletePost(uint32(id))
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(400), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/post", http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"GoCMS/domain/post"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type PostEditPageAlert struct {
|
||||
IsError bool
|
||||
Message string
|
||||
}
|
||||
|
||||
func getPostEditPageTemplate(post post.Post, alert PostEditPageAlert) []byte {
|
||||
navbarTmpl, _ := api.Container.GetPageUseCase.GetPage("componentNavbar", nil)
|
||||
postTmpl, _ := api.Container.GetPageUseCase.GetPage("postEdit", map[string]interface{}{
|
||||
"Navbar": template.HTML(navbarTmpl),
|
||||
"Head": headTmpl,
|
||||
"Post": post,
|
||||
"Alert": alert,
|
||||
"Secured": os.Getenv("ENVIRONMENT") == "production",
|
||||
})
|
||||
return postTmpl
|
||||
}
|
||||
|
||||
func PostPostEditPage(w http.ResponseWriter, r *http.Request) {
|
||||
postID := chi.URLParam(r, "id")
|
||||
postIDint, err := strconv.Atoi(postID)
|
||||
if err != nil {
|
||||
_, _ = w.Write(getPostEditPageTemplate(post.Post{}, PostEditPageAlert{
|
||||
IsError: true,
|
||||
Message: "Could not find the requested post.",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
_ = r.ParseForm()
|
||||
postBody := r.FormValue("postBody")
|
||||
|
||||
getPost, _ := api.Container.GetPostUseCase.GetPost(uint32(postIDint))
|
||||
updatedPost, err := api.Container.UpdatePostUseCase.UpdateBody(getPost.ID, postBody)
|
||||
if err != nil {
|
||||
_, _ = w.Write(getPostEditPageTemplate(post.Post{Body: postBody}, PostEditPageAlert{
|
||||
IsError: true,
|
||||
Message: "Could not save the post: " + err.Error(),
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
_, _ = w.Write(getPostEditPageTemplate(updatedPost, PostEditPageAlert{
|
||||
IsError: false,
|
||||
Message: "Post successfully edited!",
|
||||
}))
|
||||
}
|
||||
|
||||
func GetPostEditPage(w http.ResponseWriter, r *http.Request) {
|
||||
postID := chi.URLParam(r, "id")
|
||||
postIDint, err := strconv.Atoi(postID)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
getPost, _ := api.Container.GetPostUseCase.GetPost(uint32(postIDint))
|
||||
|
||||
_, _ = w.Write(getPostEditPageTemplate(getPost, PostEditPageAlert{
|
||||
IsError: false,
|
||||
Message: "",
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func updateIsOnline(postId string, isOnline bool) (error, int) {
|
||||
postIdInt, err := strconv.Atoi(postId)
|
||||
if err != nil {
|
||||
return errors.New("the server expects the ID to be in the format of an unsigned 32-bit integer (uint32)"), http.StatusBadRequest
|
||||
}
|
||||
|
||||
_, err = api.Container.UpdatePostUseCase.UpdateIsOnline(uint32(postIdInt), isOnline)
|
||||
if err != nil {
|
||||
return errors.New("the requested resource, identified by its unique ID, could not be found on the server"), http.StatusNotFound
|
||||
}
|
||||
|
||||
return nil, http.StatusOK
|
||||
}
|
||||
|
||||
func GetPostUnpublishPage(w http.ResponseWriter, r *http.Request) {
|
||||
postId := chi.URLParam(r, "id")
|
||||
err, statusCode := updateIsOnline(postId, false)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), statusCode)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/post", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func GetPostPublishPage(w http.ResponseWriter, r *http.Request) {
|
||||
postId := chi.URLParam(r, "id")
|
||||
err, statusCode := updateIsOnline(postId, true)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), statusCode)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/post", http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"html/template"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func GetPostsPage(w http.ResponseWriter, _ *http.Request) {
|
||||
posts := api.Container.ListPostsUseCase.ListPosts()
|
||||
|
||||
var formattedPosts []map[string]interface{}
|
||||
for _, post := range posts {
|
||||
formattedPosts = append(formattedPosts, map[string]interface{}{
|
||||
"ID": post.ID,
|
||||
"Title": post.Title,
|
||||
"IsOnline": post.IsOnline,
|
||||
"CreatedAt": post.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
"UpdatedAt": post.UpdatedAt.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
navbarTmpl, _ := api.Container.GetPageUseCase.GetPage("componentNavbar", nil)
|
||||
postsTmpl, _ := api.Container.GetPageUseCase.GetPage("posts", map[string]interface{}{
|
||||
"Navbar": template.HTML(navbarTmpl),
|
||||
"Head": headTmpl,
|
||||
"Posts": formattedPosts,
|
||||
})
|
||||
|
||||
_, _ = w.Write(postsTmpl)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"GoCMS/api/controllers/auth"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type RegisterPageError struct {
|
||||
Email bool `json:"email"`
|
||||
Password bool `json:"password"`
|
||||
Username bool `json:"username"`
|
||||
}
|
||||
|
||||
type RegisterPage struct {
|
||||
PageError *RegisterPageError `json:"error"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
var EmptyRegisterPage = &RegisterPage{
|
||||
PageError: &RegisterPageError{
|
||||
Email: false,
|
||||
Password: false,
|
||||
Username: false,
|
||||
},
|
||||
Username: "",
|
||||
Email: "",
|
||||
}
|
||||
|
||||
func GetRegisterPageHandler(registerPage *RegisterPage) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !auth.IsLoggedIn(r) && auth.SomeUsersVerified() {
|
||||
http.Redirect(w, r, "/login?failure=There is already a verified account, please login.", http.StatusSeeOther)
|
||||
}
|
||||
if (auth.IsLoggedIn(r) && auth.IsVerified(r)) || auth.SomeUsersVerified() {
|
||||
http.Redirect(w, r, "/home", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodPost {
|
||||
PostRegisterPage(w, r)
|
||||
return
|
||||
}
|
||||
bs, err := api.Container.GetPageUseCase.GetPage("register", map[string]interface{}{
|
||||
"PageError": registerPage.PageError,
|
||||
"Username": registerPage.Username,
|
||||
"Email": registerPage.Email,
|
||||
"Head": headTmpl,
|
||||
})
|
||||
if err != nil {
|
||||
_, _ = w.Write([]byte(err.Error()))
|
||||
}
|
||||
_, _ = w.Write(bs)
|
||||
}
|
||||
}
|
||||
|
||||
func PostRegisterPage(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
|
||||
credentials := auth.RegisterCredentials{
|
||||
Username: r.FormValue("username"),
|
||||
Password: r.FormValue("password"),
|
||||
Email: r.FormValue("email"),
|
||||
}
|
||||
err := api.Validate.Struct(credentials)
|
||||
if err != nil {
|
||||
r.Method = http.MethodGet
|
||||
GetRegisterPageHandler(&RegisterPage{
|
||||
PageError: &RegisterPageError{
|
||||
Email: true,
|
||||
Password: true,
|
||||
Username: true,
|
||||
},
|
||||
Username: r.FormValue("username"),
|
||||
Email: r.FormValue("email"),
|
||||
})(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
verificationCode := uuid.NewString()
|
||||
createdUser, err := auth.GetNewUser(credentials, verificationCode)
|
||||
if err != nil {
|
||||
r.Method = http.MethodGet
|
||||
GetRegisterPageHandler(&RegisterPage{
|
||||
PageError: &RegisterPageError{
|
||||
Email: true,
|
||||
Password: false,
|
||||
Username: false,
|
||||
},
|
||||
Username: r.FormValue("username"),
|
||||
Email: r.FormValue("email"),
|
||||
})(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
_ = api.Container.SendMailUseCase.SendMail(createdUser.Email, "mailValidation", map[string]string{
|
||||
"Host": os.Getenv("HOST"),
|
||||
"VerificationCode": verificationCode,
|
||||
})
|
||||
|
||||
_ = auth.SetJwtCookie(&w, createdUser.ID)
|
||||
|
||||
http.Redirect(w, r, "/register/pending", http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"GoCMS/api/controllers/auth"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
func PostRegisterPendingPage(w http.ResponseWriter, r *http.Request) {
|
||||
token, _ := jwtauth.VerifyRequest(
|
||||
auth.Token, r,
|
||||
jwtauth.TokenFromCookie,
|
||||
jwtauth.TokenFromHeader,
|
||||
jwtauth.TokenFromQuery)
|
||||
userId := token.PrivateClaims()["user_id"].(float64)
|
||||
err := api.Container.DeleteUserUseCase.DeleteUser(uint32(userId))
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
r.Method = http.MethodGet
|
||||
http.Redirect(w, r, "/register/pending", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
auth.RemoveJwtCookie(w)
|
||||
|
||||
http.Redirect(w, r, "/register", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func GetRegisterPendingPage(w http.ResponseWriter, _ *http.Request) {
|
||||
registerPendingTmpl, _ := api.Container.GetPageUseCase.GetPage("registerPending", map[string]interface{}{
|
||||
"Head": headTmpl,
|
||||
})
|
||||
_, _ = w.Write(registerPendingTmpl)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"GoCMS/api"
|
||||
"GoCMS/api/controllers/auth"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func GetRegisterValidatePage(w http.ResponseWriter, r *http.Request) {
|
||||
queryVerificationCode := r.URL.Query().Get("c")
|
||||
if queryVerificationCode == "" {
|
||||
http.Redirect(w, r, "/register/pending", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
token, _ := jwtauth.VerifyRequest(
|
||||
auth.Token,
|
||||
r,
|
||||
jwtauth.TokenFromCookie,
|
||||
jwtauth.TokenFromHeader,
|
||||
jwtauth.TokenFromQuery)
|
||||
|
||||
userId := token.PrivateClaims()["user_id"].(float64)
|
||||
user, _ := api.Container.GetUserUseCase.GetUser(uint32(userId))
|
||||
errorMessage := ""
|
||||
|
||||
err := bcrypt.CompareHashAndPassword([]byte(user.VerificationCode), []byte(queryVerificationCode))
|
||||
if err != nil || user.VerificationExpiration.Before(time.Now()) {
|
||||
errorMessage = "Verification link is incorrect or has expired."
|
||||
} else {
|
||||
_, err := api.Container.UpdateUserUseCase.UpdateVerificationStatus(user.ID, true)
|
||||
if err != nil {
|
||||
errorMessage = "Something went wrong server-side. User account may not exist."
|
||||
}
|
||||
}
|
||||
|
||||
registerValidateTmpl, _ := api.Container.GetPageUseCase.GetPage("registerValidate", map[string]interface{}{
|
||||
"Head": headTmpl,
|
||||
"PageError": NewPageError(errorMessage),
|
||||
})
|
||||
_, _ = w.Write(registerValidateTmpl)
|
||||
}
|
||||
Reference in New Issue
Block a user