diff --git a/README.md b/README.md index a3b8999..6e70a9c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ * @Author: Vincent Young * @Date: 2022-10-18 07:32:29 * @LastEditors: Vincent Young - * @LastEditTime: 2023-09-14 13:58:57 + * @LastEditTime: 2023-10-28 22:45:58 * @FilePath: /DeepLX/README.md * @Telegram: https://t.me/missuo * @@ -55,12 +55,29 @@ "target_lang": "EN" } ``` -### Specify the port +### Specify the port (Optional) **Thanks to [cijiugechu](https://github.com/cijiugechu) for [his contribution](https://github.com/OwO-Network/DeepLX/commit/4a0920579ea868b0f05ccdff6bceae316bfd5dc8) to make this feature possible for this project!** ```bash ./deeplx -p 3333 # or ./deeplx -port 3333 +``` +### Set access password (Optional) +**To prevent abuse of your public API, you can use a token to restrict translation requests.** +```bash +./deeplx -token hellodeeplx +``` + +``` +curl -X POST http://localhost:1188/translate \ +-H "Content-Type: application/json" \ +-H "Authorization: Bearer your_access_token" \ +-d '{ + "text": "Hello, world!", + "source_lang": "EN", + "target_lang": "DE" +}' + ``` ### Run with Docker diff --git a/main.go b/main.go index 8bbe450..7f80a94 100644 --- a/main.go +++ b/main.go @@ -2,7 +2,7 @@ * @Author: Vincent Young * @Date: 2023-07-01 21:45:34 * @LastEditors: Vincent Young - * @LastEditTime: 2023-09-14 13:34:42 + * @LastEditTime: 2023-10-28 22:42:08 * @FilePath: /DeepLX/main.go * @Telegram: https://t.me/missuo * @@ -32,6 +32,7 @@ import ( ) var port int +var token string func init() { const ( @@ -41,6 +42,7 @@ func init() { flag.IntVar(&port, "port", defaultPort, usage) flag.IntVar(&port, "p", defaultPort, usage) + flag.StringVar(&token, "token", "", "set the access token for /translate endpoint") log.SetFlags(log.LstdFlags | log.Lshortfile) } @@ -129,6 +131,21 @@ func main() { fmt.Printf("DeepL X has been successfully launched! Listening on 0.0.0.0:%v\n", port) fmt.Println("Developed by sjlleo and missuo .") + // Check if the token is set in the environment variable + if token == "" { + envToken, ok := os.LookupEnv("TOKEN") + if ok { + token = envToken + fmt.Println("Access token is set from the environment variable.") + } + } + + if token == "" { + fmt.Println("Access token is not set. You can set it using the -token flag or the TOKEN environment variable.") + } else { + fmt.Println("Access token is set. Use the Authorization: Bearer header to access /translate.") + } + // Generating a random ID id := getRandomNumber() @@ -150,6 +167,17 @@ func main() { reqj := ResData{} c.BindJSON(&reqj) + if token != "" { + providedToken := c.GetHeader("Authorization") + if providedToken != "Bearer "+token { + c.JSON(http.StatusUnauthorized, gin.H{ + "code": http.StatusUnauthorized, + "message": "Invalid access token", + }) + return + } + } + // Extracting details from the request JSON sourceLang := reqj.SourceLang targetLang := reqj.TargetLang