Browse Source

Implementasi JWT 2

news
David Ervardy 1 year ago
parent
commit
2b2527aeb4
  1. BIN
      go-crud.exe
  2. BIN
      go-crud.exe~
  3. 1
      main.go
  4. 17
      middleware/requireAuth.go

BIN
go-crud.exe

Binary file not shown.

BIN
go-crud.exe~

Binary file not shown.

1
main.go

@ -27,6 +27,7 @@ func main() {
r.PUT("/posts/:id", controllers.PostsUpdate)
r.DELETE("/posts/:id", controllers.PostDelete)
r.Use(middleware.RequireAuth)
r.POST("/news", controllers.NewsCreate)
r.GET("/newsData", controllers.NewsIndex)
r.GET("/newsShow/:id", controllers.NewsShow)

17
middleware/requireAuth.go

@ -2,14 +2,15 @@ package middleware
import (
"fmt"
"go-crud/initializers"
"go-crud/models"
"net/http"
"os"
"time"
"github.com/dgrijalva/jwt-go"
"go-crud/initializers"
"go-crud/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4"
)
func RequireAuth(c *gin.Context) {
@ -47,17 +48,17 @@ func RequireAuth(c *gin.Context) {
return
}
// Find the news with token sub
var news models.News
initializers.DB.First(&news, claims["sub"])
// Find the user with token sub
var user models.User
initializers.DB.First(&user, claims["sub"])
if news.ID == 0 {
if user.ID == 0 {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// Attach to req
c.Set("news", news)
c.Set("user", user)
// Continue
c.Next()

Loading…
Cancel
Save