NAM-APJATEL-BACKEND/middleware/auth_middleware.go

68 lines
1.4 KiB
Go

package middleware
import (
"encoding/json"
"net/http"
"strings"
"users_management/m/model/dto/res"
"users_management/m/utils/common"
"github.com/gin-gonic/gin"
)
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
common.ErrorResponses(c, http.StatusUnauthorized, "authorization token required")
c.Abort()
return
}
token = strings.TrimPrefix(token, "Bearer ")
c.Set("token", token)
req, err := http.NewRequest("POST", "https://demo.api-hrm.winteraccess.id/api/v2/auth/me", nil)
if err != nil {
common.ErrorResponses(c, http.StatusInternalServerError, err.Error())
c.Abort()
return
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
common.ErrorResponses(c, http.StatusInternalServerError, err.Error())
c.Abort()
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
common.ErrorResponses(c, http.StatusUnauthorized, "Unauthroized")
c.Abort()
return
}
var authResponse res.AuthMeResponse
if err := json.NewDecoder(resp.Body).Decode(&authResponse); err != nil {
common.ErrorResponses(c, http.StatusInternalServerError, err.Error())
c.Abort()
return
}
c.Set("userID", authResponse.Data.NomorInduk)
c.Next()
}
}