Browse Source

Implementasi JWT 3

news
David Ervardy 1 year ago
parent
commit
b75270a5aa
  1. BIN
      go-crud.exe
  2. BIN
      go-crud.exe~
  3. 16
      middleware/requireAuth.go

BIN
go-crud.exe

Binary file not shown.

BIN
go-crud.exe~

Binary file not shown.

16
middleware/requireAuth.go

@ -17,7 +17,7 @@ func RequireAuth(c *gin.Context) {
// Get the cookie off req // Get the cookie off req
tokenString, err := c.Cookie("Authorization") tokenString, err := c.Cookie("Authorization")
if err != nil { if err != nil {
c.AbortWithStatus(http.StatusUnauthorized) c.JSON(http.StatusUnauthorized, gin.H{"error": "Anda belum login"})
return return
} }
@ -32,19 +32,19 @@ func RequireAuth(c *gin.Context) {
}) })
if err != nil || !token.Valid { if err != nil || !token.Valid {
c.AbortWithStatus(http.StatusUnauthorized) c.JSON(http.StatusUnauthorized, gin.H{"error": "Token tidak valid"})
return return
} }
claims, ok := token.Claims.(jwt.MapClaims) claims, ok := token.Claims.(jwt.MapClaims)
if !ok { if !ok {
c.AbortWithStatus(http.StatusUnauthorized) c.JSON(http.StatusUnauthorized, gin.H{"error": "Token tidak valid"})
return return
} }
// Check the exp // Check the exp
if exp, ok := claims["exp"].(float64); ok && float64(time.Now().Unix()) > exp { if exp, ok := claims["exp"].(float64); ok && float64(time.Now().Unix()) > exp {
c.AbortWithStatus(http.StatusUnauthorized) c.JSON(http.StatusUnauthorized, gin.H{"error": "Token kedaluwarsa"})
return return
} }
@ -53,7 +53,13 @@ func RequireAuth(c *gin.Context) {
initializers.DB.First(&user, claims["sub"]) initializers.DB.First(&user, claims["sub"])
if user.ID == 0 { if user.ID == 0 {
c.AbortWithStatus(http.StatusUnauthorized) c.JSON(http.StatusUnauthorized, gin.H{"error": "User tidak ditemukan"})
return
}
// Check user's level
if user.Email != "dave@gmail." {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Anda tidak memiliki akses yang cukup"})
return return
} }

Loading…
Cancel
Save