Abstract db handling into repositories

This commit is contained in:
2025-01-05 22:22:00 +01:00
parent 2eadad9135
commit 4e48e87f6c
5 changed files with 303 additions and 105 deletions

View File

@@ -9,20 +9,16 @@ import(
"github.com/golang-jwt/jwt/v5"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"example.com/gin/test/models"
"example.com/gin/test/repositories"
)
type UserController struct {
DB *gorm.DB
}
type UserController struct {}
func NewUserController(db *gorm.DB) UserController {
return UserController{
DB: db,
}
func NewUserController() UserController {
return UserController{}
}
@@ -57,10 +53,10 @@ func (uc *UserController) Register(c *gin.Context) {
//create user
user := models.User{Name: body.Name, Email: body.Email, Password: string(hash)}
result := uc.DB.Create(&user)
_, err = repositories.Users.Create(user)
if result.Error != nil {
fmt.Println("Error: ", result.Error)
if err != nil {
fmt.Println("Error: ", err)
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to create user",
})
@@ -92,10 +88,9 @@ func (uc *UserController) Login(c *gin.Context) {
}
//lookup requested user
var user models.User
result := uc.DB.First(&user, "email = ?", body.Email)
user, err := repositories.Users.GetByEmail(body.Email)
if result.Error != nil {
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid email or password",
})
@@ -151,3 +146,48 @@ func (uc *UserController) Validate(c *gin.Context) {
})
}
}
func (rc *UserController) LoginView(c *gin.Context) {
rooms, _ := repositories.Rooms.GetAll()
data := gin.H{
"title": "Room Page",
"rooms": rooms,
}
c.HTML(http.StatusOK, "login.html", data)
}
func (rc *UserController) RegisterView(c *gin.Context) {
rooms, _ := repositories.Rooms.GetAll()
data := gin.H{
"title": "Room Page",
"rooms": rooms,
}
c.HTML(http.StatusOK, "register.html", data)
}
func (rc *UserController) ResetView(c *gin.Context) {
rooms, _ := repositories.Rooms.GetAll()
data := gin.H{
"title": "Room Page",
"rooms": rooms,
}
c.HTML(http.StatusOK, "passwordreset.html", data)
}
func (rc *UserController) MainView(c *gin.Context) {
rooms, _ := repositories.Rooms.GetAll()
data := gin.H{
"title": "Room Page",
"rooms": rooms,
}
c.HTML(http.StatusOK, "index.html", data)
}