diff --git a/api/anonymous.go b/api/anonymous.go
index 15b83e2..f012aeb 100644
--- a/api/anonymous.go
+++ b/api/anonymous.go
@@ -1,11 +1,10 @@
package api
import (
- "chat/connection"
"chat/utils"
- "context"
"fmt"
"github.com/gin-gonic/gin"
+ "github.com/go-redis/redis/v8"
"github.com/spf13/viper"
"net/http"
"strings"
@@ -21,14 +20,14 @@ func GetAnonymousResponse(message string) (string, error) {
"Content-Type": "application/json",
"Authorization": "Bearer " + viper.GetString("openai.anonymous"),
}, ChatGPTRequest{
- Model: "gpt-3.5-turbo",
+ Model: "gpt-3.5-turbo-16k",
Messages: []ChatGPTMessage{
{
Role: "user",
Content: message,
},
},
- MaxToken: 150,
+ MaxToken: 250,
})
if err != nil {
return "", err
@@ -37,14 +36,15 @@ func GetAnonymousResponse(message string) (string, error) {
return data.(string), nil
}
-func GetAnonymousResponseWithCache(c context.Context, message string) (string, error) {
- res, err := connection.Cache.Get(c, fmt.Sprintf(":chatgpt:%s", message)).Result()
+func GetAnonymousResponseWithCache(c *gin.Context, message string) (string, error) {
+ cache := c.MustGet("cache").(*redis.Client)
+ res, err := cache.Get(c, fmt.Sprintf(":chatgpt:%s", message)).Result()
if err != nil || len(res) == 0 {
res, err := GetAnonymousResponse(message)
if err != nil {
return "There was something wrong...", err
}
- connection.Cache.Set(c, fmt.Sprintf(":chatgpt:%s", message), res, time.Hour*6)
+ cache.Set(c, fmt.Sprintf(":chatgpt:%s", message), res, time.Hour*6)
return res, nil
}
return res, nil
diff --git a/app/router/index.ts b/app/router/index.ts
index ff12495..2b87f9a 100644
--- a/app/router/index.ts
+++ b/app/router/index.ts
@@ -1,5 +1,6 @@
import {createRouter, createWebHistory} from "vue-router";
import HomeView from "../src/views/HomeView.vue";
+import {auth, awaitUtilSetup} from "../src/assets/script/auth";
const router = createRouter({ //@ts-ignore
history: createWebHistory(import.meta.env.BASE_URL),
@@ -22,4 +23,14 @@ const router = createRouter({ //@ts-ignore
],
});
+router.beforeEach(async (to, from, next) => {
+ document.title = to.meta.title as string;
+ await awaitUtilSetup();
+ if (to.name === "login" && auth.value) {
+ next({ name: "index" });
+ return;
+ }
+ next();
+});
+
export default router;
diff --git a/app/src/App.vue b/app/src/App.vue
index acf3dc8..48820a3 100644
--- a/app/src/App.vue
+++ b/app/src/App.vue
@@ -1,5 +1,6 @@
-
+
+ {{ message }}
diff --git a/auth/middleware.go b/auth/middleware.go
new file mode 100644
index 0000000..cc6c425
--- /dev/null
+++ b/auth/middleware.go
@@ -0,0 +1,26 @@
+package auth
+
+import (
+ "github.com/gin-gonic/gin"
+ "strings"
+)
+
+func Middleware() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ token := strings.TrimSpace(c.GetHeader("Authorization"))
+ if token != "" {
+ if user := ParseToken(c, token); user != nil {
+ c.Set("token", token)
+ c.Set("auth", true)
+ c.Set("user", user.Username)
+ c.Next()
+ return
+ }
+ }
+
+ c.Set("token", token)
+ c.Set("auth", false)
+ c.Set("user", "")
+ c.Next()
+ }
+}
diff --git a/auth/user.go b/auth/user.go
new file mode 100644
index 0000000..914f0c6
--- /dev/null
+++ b/auth/user.go
@@ -0,0 +1,155 @@
+package auth
+
+import (
+ "chat/utils"
+ "database/sql"
+ "fmt"
+ "github.com/dgrijalva/jwt-go"
+ "github.com/gin-gonic/gin"
+ "github.com/go-redis/redis/v8"
+ "github.com/spf13/viper"
+ "net/http"
+ "time"
+)
+
+type User struct {
+ ID int64 `json:"id"`
+ Username string `json:"username"`
+ BindID int64 `json:"bind_id"`
+ Password string `json:"password"`
+ Token string `json:"token"`
+}
+
+type LoginForm struct {
+ Token string `form:"token" binding:"required"`
+}
+
+func (u *User) Validate(c *gin.Context) bool {
+ if u.Username == "" || u.Password == "" {
+ return false
+ }
+ cache := c.MustGet("cache").(*redis.Client)
+
+ if password, err := cache.Get(c, fmt.Sprintf("nio:user:%s", u.Username)).Result(); err == nil && len(password) > 0 {
+ return u.Password == password
+ }
+
+ db := c.MustGet("db").(*sql.DB)
+ var count int
+ if err := db.QueryRow("SELECT COUNT(*) FROM auth WHERE username = ? AND password = ?", u.Username, u.Password).Scan(&count); err != nil || count == 0 {
+ return false
+ }
+
+ cache.Set(c, fmt.Sprintf("nio:user:%s", u.Username), u.Password, 30*time.Minute)
+ return true
+}
+
+func (u *User) GenerateToken() string {
+ instance := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
+ "username": u.Username,
+ "password": u.Password,
+ "exp": time.Now().Add(time.Hour * 24 * 30).Unix(),
+ })
+ token, err := instance.SignedString([]byte(viper.GetString("secret")))
+ if err != nil {
+ return ""
+ }
+ return token
+}
+
+func IsUserExist(db *sql.DB, username string) bool {
+ var count int
+ if err := db.QueryRow("SELECT COUNT(*) FROM auth WHERE username = ?", username).Scan(&count); err != nil {
+ return false
+ }
+ return count > 0
+}
+
+func ParseToken(c *gin.Context, token string) *User {
+ instance, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
+ return []byte(viper.GetString("secret")), nil
+ })
+ if err != nil {
+ return nil
+ }
+ if claims, ok := instance.Claims.(jwt.MapClaims); ok && instance.Valid {
+ if int64(claims["exp"].(float64)) < time.Now().Unix() {
+ return nil
+ }
+ user := &User{
+ Username: claims["username"].(string),
+ Password: claims["password"].(string),
+ }
+ if !user.Validate(c) {
+ return nil
+ }
+ return user
+ }
+ return nil
+}
+
+func Login(c *gin.Context, token string) (bool, string) {
+ // DeepTrain Token Validation
+ user := Validate(token)
+ if user == nil {
+ return false, ""
+ }
+
+ db := c.MustGet("db").(*sql.DB)
+ if !IsUserExist(db, user.Username) {
+ // register
+ password := utils.GenerateChar(64)
+ _ = db.QueryRow("INSERT INTO auth (bind_id, username, token, password) VALUES (?, ?, ?, ?)",
+ user.ID, user.Username, token, password)
+ u := &User{
+ Username: user.Username,
+ Password: password,
+ }
+ return true, u.GenerateToken()
+ }
+
+ // login
+ _ = db.QueryRow("UPDATE auth SET token = ? WHERE username = ?", token, user.Username)
+ var password string
+ err := db.QueryRow("SELECT password FROM auth WHERE username = ?", user.Username).Scan(&password)
+ if err != nil {
+ return false, ""
+ }
+ u := &User{
+ Username: user.Username,
+ Password: password,
+ }
+ return true, u.GenerateToken()
+}
+
+func LoginAPI(c *gin.Context) {
+ var form LoginForm
+ if err := c.ShouldBind(&form); err != nil {
+ c.JSON(http.StatusOK, gin.H{
+ "status": false,
+ "error": "bad request",
+ })
+ return
+ }
+
+ state, token := Login(c, form.Token)
+ if !state {
+ c.JSON(http.StatusOK, gin.H{
+ "status": false,
+ "error": "user not found",
+ })
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "status": true,
+ "token": token,
+ })
+}
+
+func StateAPI(c *gin.Context) {
+ username := c.MustGet("user").(string)
+ c.JSON(http.StatusOK, gin.H{
+ "status": len(username) != 0,
+ "user": username,
+ })
+}
diff --git a/config.example.yaml b/config.example.yaml
index a5d4d8d..a74666f 100644
--- a/config.example.yaml
+++ b/config.example.yaml
@@ -1,3 +1,4 @@
+debug: true
server:
port: 8094
diff --git a/connection/cache.go b/connection/cache.go
index 54a644d..a38a949 100644
--- a/connection/cache.go
+++ b/connection/cache.go
@@ -10,7 +10,7 @@ import (
var Cache *redis.Client
-func ConnectRedis() {
+func ConnectRedis() *redis.Client {
// connect to redis
Cache = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", viper.GetString("redis.host"), viper.GetInt("redis.port")),
@@ -27,6 +27,7 @@ func ConnectRedis() {
if viper.GetBool("debug") {
Cache.FlushAll(context.Background())
- log.Println("Flushed all cache")
+ log.Println("Redis: Flushed all cache")
}
+ return Cache
}
diff --git a/go.mod b/go.mod
index 4cb0bb4..73f1b49 100644
--- a/go.mod
+++ b/go.mod
@@ -2,6 +2,14 @@ module chat
go 1.20
+require (
+ github.com/dgrijalva/jwt-go v3.2.0+incompatible
+ github.com/gin-gonic/gin v1.9.1
+ github.com/go-redis/redis/v8 v8.11.5
+ github.com/go-sql-driver/mysql v1.7.1
+ github.com/spf13/viper v1.16.0
+)
+
require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
@@ -10,12 +18,9 @@ require (
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
- github.com/gin-gonic/gin v1.9.1 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
- github.com/go-redis/redis/v8 v8.11.5 // indirect
- github.com/go-sql-driver/mysql v1.7.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
@@ -31,7 +36,6 @@ require (
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
- github.com/spf13/viper v1.16.0 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
diff --git a/go.sum b/go.sum
index 6d76280..c89fbfa 100644
--- a/go.sum
+++ b/go.sum
@@ -55,7 +55,10 @@ github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGX
github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
+github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
@@ -64,6 +67,7 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po=
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
+github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY=
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
@@ -75,6 +79,7 @@ github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SU
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
+github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
@@ -125,6 +130,7 @@ github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
@@ -160,8 +166,10 @@ github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZX
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
@@ -175,13 +183,18 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
+github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
+github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
+github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/spf13/afero v1.9.5 h1:stMpOSZFs//0Lv29HduCmli3GUfpFoF3Y1Q/aXj/wVM=
github.com/spf13/afero v1.9.5/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ=
github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA=
@@ -204,6 +217,7 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8=
github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
@@ -516,11 +530,14 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/main.go b/main.go
index eda2447..aa55b97 100644
--- a/main.go
+++ b/main.go
@@ -2,6 +2,7 @@ package main
import (
"chat/api"
+ "chat/auth"
"chat/connection"
"chat/middleware"
"github.com/gin-gonic/gin"
@@ -13,16 +14,22 @@ func main() {
if err := viper.ReadInConfig(); err != nil {
panic(err)
}
- connection.ConnectRedis()
- connection.ConnectMySQL()
app := gin.Default()
{
app.Use(middleware.CORSMiddleware())
- app.Use(middleware.BuiltinMiddleWare(connection.Database, connection.Cache))
+ app.Use(middleware.BuiltinMiddleWare(connection.ConnectMySQL(), connection.ConnectRedis()))
app.Use(middleware.ThrottleMiddleware())
+ app.Use(auth.Middleware())
- app.POST("/api/anonymous", api.AnonymousAPI)
+ app.POST("/anonymous", api.AnonymousAPI)
+ app.POST("/login", auth.LoginAPI)
+ app.POST("/state", auth.StateAPI)
+ }
+ if viper.GetBool("debug") {
+ gin.SetMode(gin.DebugMode)
+ } else {
+ gin.SetMode(gin.ReleaseMode)
}
if err := app.Run(":" + viper.GetString("server.port")); err != nil {
panic(err)
diff --git a/middleware/cors.go b/middleware/cors.go
index 792acfb..912b443 100644
--- a/middleware/cors.go
+++ b/middleware/cors.go
@@ -9,9 +9,8 @@ import (
var allowedOrigins = []string{
"https://fystart.cn",
"https://www.fystart.cn",
- "https://deeptrain.net",
- "https://www.deeptrain.net",
- "http://localhost",
+ "https://nio.fystart.cn",
+ "http://localhost:5173",
}
func CORSMiddleware() gin.HandlerFunc {
diff --git a/middleware/throttle.go b/middleware/throttle.go
index de9b5aa..776b803 100644
--- a/middleware/throttle.go
+++ b/middleware/throttle.go
@@ -26,9 +26,9 @@ func (l *Limiter) RateLimit(ctx *gin.Context, rds *redis.Client, ip string, path
}
var limits = map[string]Limiter{
- "/login": {Duration: 10, Count: 5},
- "/api/anonymous": {Duration: 60, Count: 15},
- "/api/user": {Duration: 1, Count: 1},
+ "/login": {Duration: 10, Count: 5},
+ "/anonymous": {Duration: 60, Count: 15},
+ "/user": {Duration: 1, Count: 1},
}
func GetPrefixMap[T comparable](s string, p map[string]T) *T {