Browse Source

Authorization JWT

widia
Widyarhn 1 year ago
parent
commit
d67b6f64a6
  1. BIN
      go-crud.exe
  2. 9
      initializers/syncDatabase.go
  3. 2
      main.go
  4. 7
      middleware/requireAuth.go
  5. 15
      migrate/migrate.go

BIN
go-crud.exe

Binary file not shown.

9
initializers/syncDatabase.go

@ -0,0 +1,9 @@
package initializers
import "go-crud/models"
func SyncDatabase() {
DB.AutoMigrate(&models.Post{})
DB.AutoMigrate(&models.Event{})
DB.AutoMigrate(&models.User{})
}

2
main.go

@ -11,6 +11,7 @@ import (
func init() {
initializers.LoadEnvVariables()
initializers.ConnectToDB()
initializers.SyncDatabase()
}
func main() {
r := gin.Default()
@ -19,6 +20,7 @@ func main() {
r.POST("/login", controllers.LogIn)
r.GET("/validate", middleware.RequireAuth, controllers.Validate)
r.Use(middleware.RequireAuth)
r.POST("/posts", controllers.PostsCreate)
r.PUT("/posts/:id", controllers.PostsUpdate)
r.GET("/posts", controllers.PostsIndex)

7
middleware/requireAuth.go

@ -52,11 +52,18 @@ func RequireAuth(c *gin.Context) {
var user models.User
initializers.DB.First(&user, claims["sub"])
var post models.Post
initializers.DB.First(&post, claims["sub"])
var event models.Event
initializers.DB.First(&event, claims["sub"])
if user.ID == 0 {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// Attach to req
c.Set("user", user)

15
migrate/migrate.go

@ -1,15 +0,0 @@
package main
import "go-crud/initializers"
import "go-crud/models"
func init() {
initializers.LoadEnvVariables()
initializers.ConnectToDB()
}
func main() {
initializers.DB.AutoMigrate(&models.Post{})
initializers.DB.AutoMigrate(&models.Event{})
initializers.DB.AutoMigrate(&models.User{})
}
Loading…
Cancel
Save