feat: add authmiddleware to all routes

This commit is contained in:
Vincent Yang 2024-04-13 18:54:16 -04:00
parent 7b97e65ec7
commit 15cca97b81
No known key found for this signature in database
GPG Key ID: 55F1635E821BF0E8

36
main.go
View File

@ -2,7 +2,7 @@
* @Author: Vincent Yang * @Author: Vincent Yang
* @Date: 2023-07-01 21:45:34 * @Date: 2023-07-01 21:45:34
* @LastEditors: Vincent Yang * @LastEditors: Vincent Yang
* @LastEditTime: 2024-04-09 03:02:08 * @LastEditTime: 2024-04-13 18:50:25
* @FilePath: /DeepLX/main.go * @FilePath: /DeepLX/main.go
* @Telegram: https://t.me/missuo * @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo * @GitHub: https://github.com/missuo
@ -338,6 +338,24 @@ func translateByDeepLX(sourceLang string, targetLang string, translateText strin
}, nil }, nil
} }
func authMiddleware(cfg *Config) gin.HandlerFunc {
return func(c *gin.Context) {
if cfg.Token != "" {
providedTokenInQuery := c.Query("token")
providedTokenInHeader := c.GetHeader("Authorization")
if providedTokenInHeader != "Bearer "+cfg.Token && providedTokenInQuery != cfg.Token {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "Invalid access token",
})
c.Abort()
return
}
}
c.Next()
}
}
func main() { func main() {
cfg := initConfig() cfg := initConfig()
@ -365,22 +383,10 @@ func main() {
}) })
// Defining the translation endpoint which receives translation requests and returns translations // Defining the translation endpoint which receives translation requests and returns translations
r.POST("/translate", func(c *gin.Context) { r.POST("/translate", authMiddleware(cfg), func(c *gin.Context) {
req := PayloadFree{} req := PayloadFree{}
c.BindJSON(&req) c.BindJSON(&req)
if cfg.Token != "" {
providedTokenInQuery := c.Query("token")
providedTokenInHeader := c.GetHeader("Authorization")
if providedTokenInHeader != "Bearer "+cfg.Token && providedTokenInQuery != cfg.Token {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "Invalid access token",
})
return
}
}
sourceLang := req.SourceLang sourceLang := req.SourceLang
targetLang := req.TargetLang targetLang := req.TargetLang
translateText := req.TransText translateText := req.TransText
@ -410,7 +416,7 @@ func main() {
} }
}) })
r.POST("/v2/translate", func(c *gin.Context) { r.POST("/v2/translate", authMiddleware(cfg), func(c *gin.Context) {
authorizationHeader := c.GetHeader("Authorization") authorizationHeader := c.GetHeader("Authorization")
parts := strings.Split(authorizationHeader, " ") parts := strings.Split(authorizationHeader, " ")
var authKey string var authKey string