Menyelesaikan fitur Login, Dashboard Mahasiswa, dan Admin Panel
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func AuthMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 1. Ambil Header "Authorization"
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Butuh Token untuk akses ini!"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Format token biasanya "Bearer <token_panjang>"
|
||||
// Kita pisahkan kata "Bearer" dan ambil tokennya saja
|
||||
tokenString := strings.Split(authHeader, " ")
|
||||
if len(tokenString) != 2 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Format Token salah!"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Validasi Token dengan Secret Key kita
|
||||
token, err := jwt.Parse(tokenString[1], func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("metode sign tidak valid")
|
||||
}
|
||||
return []byte(os.Getenv("JWT_SECRET")), nil
|
||||
})
|
||||
|
||||
// 4. Jika token valid, ambil data user di dalamnya
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
// Simpan user_id ke dalam konteks agar bisa dipakai di controller nanti
|
||||
c.Set("user_id", claims["user_id"])
|
||||
c.Set("role", claims["role"])
|
||||
c.Next() // Lanjut ke proses berikutnya
|
||||
} else {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token tidak valid: " + err.Error()})
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user