mv logic into userService

allows reusing it in the views more easy
This commit is contained in:
2025-01-05 22:38:48 +01:00
parent 4e48e87f6c
commit 273918f542
2 changed files with 73 additions and 51 deletions

View File

@@ -1,17 +1,14 @@
package controllers
import(
"os"
"fmt"
"time"
"net/http"
"golang.org/x/crypto/bcrypt"
"github.com/golang-jwt/jwt/v5"
"github.com/gin-gonic/gin"
"example.com/gin/test/models"
"example.com/gin/test/repositories"
"example.com/gin/test/services"
)
@@ -40,20 +37,7 @@ func (uc *UserController) Register(c *gin.Context) {
return
}
//hash pw
hash, err := bcrypt.GenerateFromPassword([]byte(body.Password), 10)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to hash password",
})
return
}
//create user
user := models.User{Name: body.Name, Email: body.Email, Password: string(hash)}
_, err = repositories.Users.Create(user)
_, err = services.Users.Register(body.Name, body.Email, body.Password)
if err != nil {
fmt.Println("Error: ", err)
@@ -81,46 +65,17 @@ func (uc *UserController) Login(c *gin.Context) {
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to read body",
"error": "Login Failed",
})
return
}
//lookup requested user
user, err := repositories.Users.GetByEmail(body.Email)
tokenString, err := services.Users.Login(body.Email, body.Password)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid email or password",
})
return
}
// compare sent with saved pass
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(body.Password))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid email or password",
})
return
}
//generate jwt token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": user.ID,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(os.Getenv("SECRET")))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to create token",
"error": "Login Failed",
})
return
@@ -129,7 +84,6 @@ func (uc *UserController) Login(c *gin.Context) {
// send it back
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("Authorization", tokenString, 3600 * 24, "", "", false, true)
c.JSON(http.StatusOK, gin.H{})
}