clean: refactor auth & login page auth

This commit is contained in:
Florian Sylvain
2024-05-13 11:11:58 +02:00
parent dca17a744d
commit 00a4e464ff
4 changed files with 37 additions and 35 deletions
+28 -20
View File
@@ -1,6 +1,7 @@
package api package api
import ( import (
"GohCMS2/domain/user"
"GohCMS2/useCases" "GohCMS2/useCases"
"encoding/json" "encoding/json"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
@@ -11,13 +12,13 @@ import (
"time" "time"
) )
type UserRegister struct { type RegisterCredentials struct {
Username string `json:"username" validate:"required,min=3,max=20"` Username string `json:"username" validate:"required,min=3,max=20"`
Password string `json:"password" validate:"required,min=8"` Password string `json:"password" validate:"required,min=8"`
Email string `json:"email" validate:"required,email"` Email string `json:"email" validate:"required,email"`
} }
type UserLogin struct { type LoginCredentials struct {
Username string `json:"username" validate:"required,min=3,max=20"` Username string `json:"username" validate:"required,min=3,max=20"`
Password string `json:"password" validate:"required,min=8"` Password string `json:"password" validate:"required,min=8"`
} }
@@ -60,31 +61,38 @@ func IsLoggedIn(r *http.Request) bool {
return token != nil && err == nil return token != nil && err == nil
} }
func login(w http.ResponseWriter, r *http.Request) { func getUserFromCredentials(credentials LoginCredentials) (user.User, error) {
var user UserLogin dbUser, err := Container.GetUserUseCase.GetUserByUsername(credentials.Username)
if err != nil {
return user.User{}, err
}
err := json.NewDecoder(r.Body).Decode(&user) err = bcrypt.CompareHashAndPassword([]byte(dbUser.Password), []byte(credentials.Password))
if err != nil {
return user.User{}, err
}
return dbUser, nil
}
func login(w http.ResponseWriter, r *http.Request) {
var credentials LoginCredentials
err := json.NewDecoder(r.Body).Decode(&credentials)
if err != nil { if err != nil {
http.Error(w, bodyErrorMessage, http.StatusBadRequest) http.Error(w, bodyErrorMessage, http.StatusBadRequest)
return return
} }
err = validate.Struct(user) err = validate.Struct(credentials)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
dbUser, err := Container.GetUserUseCase.GetUserByUsername(user.Username) dbUser, err := getUserFromCredentials(credentials)
if err != nil { if err != nil {
http.Error(w, logsErrorMessage, http.StatusForbidden) http.Error(w, logsErrorMessage, http.StatusForbidden)
return
}
err = bcrypt.CompareHashAndPassword([]byte(dbUser.Password), []byte(user.Password))
if err != nil {
http.Error(w, logsErrorMessage, http.StatusForbidden)
return
} }
_ = SetJwtCookie(&w, dbUser.ID) _ = SetJwtCookie(&w, dbUser.ID)
@@ -99,23 +107,23 @@ func register(w http.ResponseWriter, r *http.Request) {
return return
} }
var user UserRegister var credentials RegisterCredentials
err := json.NewDecoder(r.Body).Decode(&user) err := json.NewDecoder(r.Body).Decode(&credentials)
if err != nil { if err != nil {
http.Error(w, bodyErrorMessage, http.StatusBadRequest) http.Error(w, bodyErrorMessage, http.StatusBadRequest)
return return
} }
err = validate.Struct(user) err = validate.Struct(credentials)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
createdUser, err := Container.CreateUserUseCase.CreateUser(useCases.CreateUserCommand{ createdUser, err := Container.CreateUserUseCase.CreateUser(useCases.CreateUserCommand{
Username: user.Username, Username: credentials.Username,
Password: user.Password, Password: credentials.Password,
Email: user.Email, Email: credentials.Email,
}) })
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
+6 -12
View File
@@ -1,10 +1,7 @@
package api package api
import ( import (
"bytes"
"encoding/json"
"net/http" "net/http"
"os"
) )
const LoginRoute = "/login" const LoginRoute = "/login"
@@ -48,10 +45,11 @@ func GetLoginPageHandler(loginPage *LoginPage) http.HandlerFunc {
func PostLoginPage(w http.ResponseWriter, r *http.Request) { func PostLoginPage(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm() _ = r.ParseForm()
credentials, err := json.Marshal(&UserLogin{ credentials := LoginCredentials{
Username: r.FormValue("username"), Username: r.FormValue("username"),
Password: r.FormValue("password"), Password: r.FormValue("password"),
}) }
err := validate.Struct(credentials)
if err != nil { if err != nil {
r.Method = http.MethodGet r.Method = http.MethodGet
GetLoginPageHandler(&LoginPage{ GetLoginPageHandler(&LoginPage{
@@ -61,12 +59,8 @@ func PostLoginPage(w http.ResponseWriter, r *http.Request) {
return return
} }
response, err := http.Post( dbUser, err := getUserFromCredentials(credentials)
"http://localhost:"+os.Getenv("PORT")+"/v1/auth/login", if err != nil {
"application/json",
bytes.NewBuffer(credentials))
if err != nil || response.StatusCode != http.StatusOK {
r.Method = http.MethodGet r.Method = http.MethodGet
GetLoginPageHandler(&LoginPage{ GetLoginPageHandler(&LoginPage{
PageError: NewPageError("Invalid username or password."), PageError: NewPageError("Invalid username or password."),
@@ -75,7 +69,7 @@ func PostLoginPage(w http.ResponseWriter, r *http.Request) {
return return
} }
w.Header().Set("Set-Cookie", response.Header.Get("Set-Cookie")) _ = SetJwtCookie(&w, dbUser.ID)
http.Redirect(w, r, "/home", http.StatusSeeOther) http.Redirect(w, r, "/home", http.StatusSeeOther)
} }
+1 -1
View File
@@ -45,7 +45,7 @@ func GetRegisterPageHandler(registerPage *RegisterPage) http.HandlerFunc {
func PostRegisterPage(w http.ResponseWriter, r *http.Request) { func PostRegisterPage(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm() _ = r.ParseForm()
credentials, err := json.Marshal(&UserRegister{ credentials, err := json.Marshal(&RegisterCredentials{
Username: r.FormValue("username"), Username: r.FormValue("username"),
Password: r.FormValue("password"), Password: r.FormValue("password"),
Email: r.FormValue("email"), Email: r.FormValue("email"),
+2 -2
View File
@@ -121,13 +121,13 @@ var TestGetAllPostsSuccess = func(t *testing.T) {
} }
var TestPostCreate = func(t *testing.T) { var TestPostCreate = func(t *testing.T) {
t.Run("Should return an post with the given title and body", TestCreatePostSuccess) t.Run("Should return a post with the given title and body", TestCreatePostSuccess)
t.Run("Should return an error if the title is missing", TestCreatePostFailTitleMissing) t.Run("Should return an error if the title is missing", TestCreatePostFailTitleMissing)
t.Run("Should return an error if the title is too short", TestCreatePostTitleTooShort) t.Run("Should return an error if the title is too short", TestCreatePostTitleTooShort)
} }
var TestPostGet = func(t *testing.T) { var TestPostGet = func(t *testing.T) {
t.Run("Should return an post with the given id", TestGetPostSuccess) t.Run("Should return a post with the given id", TestGetPostSuccess)
} }
var TestPostGetAll = func(t *testing.T) { var TestPostGetAll = func(t *testing.T) {