57 lines
1.1 KiB
Go
57 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"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
|
|
}
|
|
|
|
c.Next()
|
|
|
|
}
|
|
}
|