Browse Source

Authorization JWT

widia
Widyarhn 2 years 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() { func init() {
initializers.LoadEnvVariables() initializers.LoadEnvVariables()
initializers.ConnectToDB() initializers.ConnectToDB()
initializers.SyncDatabase()
} }
func main() { func main() {
r := gin.Default() r := gin.Default()
@ -19,6 +20,7 @@ func main() {
r.POST("/login", controllers.LogIn) r.POST("/login", controllers.LogIn)
r.GET("/validate", middleware.RequireAuth, controllers.Validate) r.GET("/validate", middleware.RequireAuth, controllers.Validate)
r.Use(middleware.RequireAuth)
r.POST("/posts", controllers.PostsCreate) r.POST("/posts", controllers.PostsCreate)
r.PUT("/posts/:id", controllers.PostsUpdate) r.PUT("/posts/:id", controllers.PostsUpdate)
r.GET("/posts", controllers.PostsIndex) r.GET("/posts", controllers.PostsIndex)

7
middleware/requireAuth.go

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