(c *gin.Context, logger log.Logger, db dal.Dal, apiKeyHelper *apikeyhelper.ApiKeyHelper, authHeader, path string)
| 132 | } |
| 133 | |
| 134 | func CheckAuthorizationHeader(c *gin.Context, logger log.Logger, db dal.Dal, apiKeyHelper *apikeyhelper.ApiKeyHelper, authHeader, path string) bool { |
| 135 | if authHeader == "" { |
| 136 | c.Abort() |
| 137 | c.JSON(http.StatusUnauthorized, &apiBody{ |
| 138 | Success: false, |
| 139 | Message: "token is missing", |
| 140 | }) |
| 141 | return false |
| 142 | } |
| 143 | apiKeyStr := strings.TrimPrefix(authHeader, "Bearer ") |
| 144 | if apiKeyStr == authHeader || apiKeyStr == "" { |
| 145 | c.Abort() |
| 146 | c.JSON(http.StatusUnauthorized, &apiBody{ |
| 147 | Success: false, |
| 148 | Message: "token is not present or malformed", |
| 149 | }) |
| 150 | return false |
| 151 | } |
| 152 | |
| 153 | hashedApiKey, err := apiKeyHelper.DigestToken(apiKeyStr) |
| 154 | if err != nil { |
| 155 | logger.Error(err, "DigestToken") |
| 156 | c.Abort() |
| 157 | c.JSON(http.StatusInternalServerError, &apiBody{ |
| 158 | Success: false, |
| 159 | Message: err.Error(), |
| 160 | }) |
| 161 | return false |
| 162 | } |
| 163 | |
| 164 | apiKey, err := apiKeyHelper.GetApiKey(nil, dal.Where("api_key = ?", hashedApiKey)) |
| 165 | if err != nil { |
| 166 | c.Abort() |
| 167 | if db.IsErrorNotFound(err) { |
| 168 | c.JSON(http.StatusForbidden, &apiBody{ |
| 169 | Success: false, |
| 170 | Message: "api key is invalid", |
| 171 | }) |
| 172 | } else { |
| 173 | logger.Error(err, "query api key from db") |
| 174 | c.JSON(http.StatusInternalServerError, &apiBody{ |
| 175 | Success: false, |
| 176 | Message: err.Error(), |
| 177 | }) |
| 178 | } |
| 179 | return false |
| 180 | } |
| 181 | |
| 182 | if apiKey.ExpiredAt != nil && time.Until(*apiKey.ExpiredAt) < 0 { |
| 183 | c.Abort() |
| 184 | c.JSON(http.StatusForbidden, &apiBody{ |
| 185 | Success: false, |
| 186 | Message: "api key has expired", |
| 187 | }) |
| 188 | return false |
| 189 | } |
| 190 | matched, matchErr := regexp.MatchString(apiKey.AllowedPath, path) |
| 191 | if matchErr != nil { |
no test coverage detected