diff --git a/QA/README.md b/QA/README.md new file mode 100644 index 0000000..f97c86f --- /dev/null +++ b/QA/README.md @@ -0,0 +1 @@ +我做了更新 \ No newline at end of file diff --git a/QA/auth/auth.go b/QA/auth/auth.go new file mode 100644 index 0000000..2c2f95f --- /dev/null +++ b/QA/auth/auth.go @@ -0,0 +1,70 @@ +package auth + +import ( + "QA/models" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "fmt" + "github.com/dgrijalva/jwt-go" + "time" +) + +var jwtKey = []byte("tobeempireofhduhelp") + +// 加密密码 +func GenerateSalt() string { + bytes := make([]byte, 16) + if _, err := rand.Read(bytes); err != nil { + panic("Error generating salt") + } + return hex.EncodeToString(bytes) +} + +type MyClaims struct { + Username string `json:"username"` + jwt.StandardClaims +} + +func HashPassword(password, salt string) string { + saltedPassword := password + salt + hash := sha256.New() + hash.Write([]byte(saltedPassword)) + return hex.EncodeToString(hash.Sum(nil)) +} + +// jwt +func GenerateJWT(u models.User) (string, error) { + claims := MyClaims{ + Username: u.Name, + StandardClaims: jwt.StandardClaims{ + NotBefore: time.Now().Unix() - 60, // Token生效时间 + ExpiresAt: time.Now().Unix() + 60*60*24*7, // Token过期时间 + Issuer: u.Name, + }, + } + + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) // 使用HS256算法 + tokenString, err := token.SignedString(jwtKey) // 使用密钥进行签名 + if err != nil { + return "", err + } + return tokenString, nil +} +func AuthenticateToken(tokenString string) (*jwt.Token, error) { + token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + return jwtKey, nil + }) + if err != nil { + return nil, err + } + if claims, ok := token.Claims.(*MyClaims); ok && token.Valid { + fmt.Println(claims.Username) + return token, nil + } else { + return nil, fmt.Errorf("invalid token") + } +} diff --git a/QA/config/config.go b/QA/config/config.go new file mode 100644 index 0000000..e9a14fc --- /dev/null +++ b/QA/config/config.go @@ -0,0 +1,31 @@ +package config + +import ( + "QA/models" + "gorm.io/driver/mysql" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +var DB1 *gorm.DB +var DB2 *gorm.DB +var err error + +func InitDB() { + dsn1 := "root:123456@tcp(127.0.0.1:3306)/mydatabase?charset=utf8mb4&parseTime=True&loc=Local" + DB1, err = gorm.Open(mysql.Open(dsn1), &gorm.Config{ + Logger: logger.Default.LogMode(logger.Info), + }) + if err != nil { + panic("failed to connect database") + } + DB1.AutoMigrate(&models.User{}) + dsn2 := "root:123456@tcp(127.0.0.1:3306)/mydatabase?charset=utf8mb4&parseTime=True&loc=Local" + DB2, err = gorm.Open(mysql.Open(dsn2), &gorm.Config{ + Logger: logger.Default.LogMode(logger.Info), + }) + if err != nil { + panic("failed to connect database") + } + DB2.AutoMigrate(&models.Question{}, &models.Answer{}) +} diff --git a/QA/go.mod b/QA/go.mod new file mode 100644 index 0000000..178d059 --- /dev/null +++ b/QA/go.mod @@ -0,0 +1,45 @@ +module QA + +go 1.23.2 + +require ( + github.com/dgrijalva/jwt-go v3.2.0+incompatible + github.com/gin-contrib/cors v1.7.2 + github.com/gin-gonic/gin v1.10.0 + gorm.io/driver/mysql v1.5.7 + gorm.io/gorm v1.25.12 +) + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/bytedance/sonic v1.12.3 // indirect + github.com/bytedance/sonic/loader v0.2.0 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.5 // indirect + github.com/gin-contrib/sse v0.1.0 // 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.22.1 // indirect + github.com/go-sql-driver/mysql v1.8.1 // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.8 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.10.0 // indirect + golang.org/x/crypto v0.27.0 // indirect + golang.org/x/net v0.29.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect + google.golang.org/protobuf v1.34.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/QA/go.sum b/QA/go.sum new file mode 100644 index 0000000..4ee0b8a --- /dev/null +++ b/QA/go.sum @@ -0,0 +1,112 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/bytedance/sonic v1.12.3 h1:W2MGa7RCU1QTeYRTPE3+88mVC0yXmsRQRChiyVocVjU= +github.com/bytedance/sonic v1.12.3/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM= +github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +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/gabriel-vasile/mimetype v1.4.5 h1:J7wGKdGu33ocBOhGy0z653k/lFKLFDPJMG8Gql0kxn4= +github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4= +github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw= +github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +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= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA= +github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM= +github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +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/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +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/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +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.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8= +golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= +golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +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= +gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= +gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= +gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= +gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8= +gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= diff --git a/QA/handlers/handlers.go b/QA/handlers/handlers.go new file mode 100644 index 0000000..86af776 --- /dev/null +++ b/QA/handlers/handlers.go @@ -0,0 +1,166 @@ +package handlers + +import ( + "QA/auth" + "QA/config" + "QA/models" + "github.com/gin-gonic/gin" + "net/http" + "strconv" +) + +// Yes 验证注册时用户名学号密码的合理性 +func yes(c *gin.Context, u models.User) bool { + const ( + minNameLen = 2 + maxNameLen = 5 + StudentIdLen = 8 + minPasswordLen = 6 + maxPasswordLen = 20 + ) + if len(u.Name) < minNameLen || len(u.Name) > maxNameLen { + c.JSON(http.StatusBadRequest, gin.H{"error": "用户名请控制在2-5字内"}) + return false + } + + if len(u.StudentID) != StudentIdLen { + c.JSON(http.StatusBadRequest, gin.H{"error": "请使用你本人的学号"}) + return false + } + + if len(u.Password) < minPasswordLen || len(u.Password) > maxPasswordLen { + c.JSON(http.StatusBadRequest, gin.H{"error": "密码请控制在6-20字内"}) + return false + } + + return true +} + +// RegisterUser 注册用户的处理器函数 + +func RegisterUser(c *gin.Context) { + var u models.User + if err := c.ShouldBindJSON(&u); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"}) + return + } + if !yes(c, u) { + return + } + if config.DB1 == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Database connection is not initialized"}) + return + } + var existingUser models.User + res := config.DB1.Where("student_id = ?", u.StudentID).First(&existingUser) + if res.RowsAffected != 0 { + c.JSON(http.StatusBadRequest, gin.H{"message": "该学号已被注册"}) + return + } + u.Salt = auth.GenerateSalt() + u.Password = auth.HashPassword(u.Password, u.Salt) + if err := config.DB1.Create(&u).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "注册成功"}) +} + +// LoginUser 用户登录的处理器函数 +func LoginUser(c *gin.Context) { + var u models.User + c.BindJSON(&u) + var existingUser models.User + res := config.DB1.Where("student_id = ?", u.StudentID).First(&existingUser) + if res.RowsAffected == 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "学号或密码不正确!"}) + return + } + if auth.HashPassword(u.Password, existingUser.Salt) != existingUser.Password { + c.JSON(http.StatusBadRequest, gin.H{"error": "学号或密码不正确!"}) + return + } + token, err := auth.GenerateJWT(existingUser) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Error generating JWT"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "登录成功!", "token": token}) +} + +// PostQuestion 发布问题的处理器函数 +func PostQuestion(c *gin.Context) { + var question models.Question + c.BindJSON(&question) + if len(question.Title) == 0 || len(question.Title) > 10 { + c.JSON(http.StatusBadRequest, gin.H{ + "message": "标题请设置在1-10字内", + }) + return + } + if len(question.Content) < 10 || len(question.Content) > 100 { + c.JSON(http.StatusBadRequest, gin.H{"error": "问题内容需要控制在10-100字内"}) + return + } + config.DB2.Create(&question) + c.JSON(http.StatusCreated, question) +} + +// PostAnswer 发布回答的处理器函数 +func PostAnswer(c *gin.Context) { + var answer models.Answer + c.BindJSON(&answer) + var existingQuestion models.Question + res := config.DB2.Where("question_id = ?", answer.QuestionID).First(&existingQuestion) + if res.RowsAffected == 0 { + c.JSON(http.StatusBadRequest, gin.H{ + "message": "未找到该问题", + }) + return + } + if len(answer.Content) == 0 || len(answer.Content) > 1000 { + c.JSON(http.StatusBadRequest, gin.H{ + "message": "回答请设置在1-1000字内", + }) + return + } + config.DB2.Create(&answer) + c.JSON(http.StatusCreated, answer) +} + +// ListQuestions 列出问题的处理器函数 +func ListQuestions(c *gin.Context) { + var questions []models.Question + config.DB2.Preload("Answers").Find(&questions) + c.JSON(http.StatusOK, questions) +} + +// DeleteQuestion 删除问题的处理器函数 +func DeleteQuestion(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + result := config.DB2.Delete(&models.Question{}, id) + if result.RowsAffected == 0 { + c.JSON(http.StatusNotFound, gin.H{"message": "这个问题不存在!"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "这个问题已被删除"}) +} + +// DeleteAnswer 删除回答的处理器函数 +func DeleteAnswer(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + result := config.DB2.Delete(&models.Answer{}, id) + if result.RowsAffected == 0 { + c.JSON(http.StatusNotFound, gin.H{"error": "这个回答不存在!"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "这个回答已被删除"}) +} + +// SearchQuestions 搜索问题的处理器函数 +func SearchQuestions(c *gin.Context) { + query := c.Query("query") + var results []models.Question + config.DB2.Where("title LIKE ? OR content LIKE ?", "%"+query+"%", "%"+query+"%").Find(&results) + c.JSON(http.StatusOK, results) +} diff --git a/QA/main.go b/QA/main.go new file mode 100644 index 0000000..2f5ea98 --- /dev/null +++ b/QA/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "QA/config" + "QA/handlers" + "QA/middleware" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" +) + +func main() { + config.InitDB() + r := gin.Default() + r.Use(cors.Default()) + r.POST("/hdu.wiki/register", handlers.RegisterUser) + r.POST("/hdu.wiki/login", handlers.LoginUser) + r.POST("/hdu.wiki/question", middleware.JWTMiddleware(), handlers.PostQuestion) + r.POST("/hdu.wiki/answers", middleware.JWTMiddleware(), handlers.PostAnswer) + r.GET("/hdu.wiki/questions", handlers.ListQuestions) + r.DELETE("/hdu.wiki/questions/:id", middleware.JWTMiddleware(), handlers.DeleteQuestion) + r.DELETE("/hdu.wiki/answers/:id", middleware.JWTMiddleware(), handlers.DeleteAnswer) + r.GET("/hdu.wiki/search", handlers.SearchQuestions) + r.Run(":8080") +} diff --git a/QA/middleware/middleware.go b/QA/middleware/middleware.go new file mode 100644 index 0000000..fe6c11f --- /dev/null +++ b/QA/middleware/middleware.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "QA/auth" + "github.com/gin-gonic/gin" + "net/http" + "strings" +) + +// JWTMiddleware 是用于Gin框架的JWT认证中间件 +func JWTMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + authHeader := c.GetHeader("Authorization") + if authHeader == "" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"}) + c.Abort() + return + } + tokenString := strings.TrimPrefix(authHeader, "Bearer ") + token, err := auth.AuthenticateToken(tokenString) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) + c.Abort() + return + } + claims, ok := token.Claims.(*auth.MyClaims) + if !ok { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid claims"}) + c.Abort() + return + } + c.Set("username", claims.Username) + c.Next() + } +} diff --git a/QA/models/models.go b/QA/models/models.go new file mode 100644 index 0000000..47605ff --- /dev/null +++ b/QA/models/models.go @@ -0,0 +1,21 @@ +package models + +type User struct { + Name string + StudentID string `gorm:"primaryKey"` + Password string + Salt string +} +type Question struct { + QuestionID int `json:"QuestionID" gorm:"primaryKey;AUTO_INCREMENT"` + Ask_userID string `json:"Ask_UserID"` + Title string `json:"title"` + Content string `json:"content"` + Answers []Answer `json:"answers" gorm:"foreignKey:QuestionID"` +} + +type Answer struct { + Answer_userID string `json:"Answer_UserID"` + QuestionID int `json:"QuestionID"` + Content string `json:"content"` +} diff --git a/QA/static/background.jpg b/QA/static/background.jpg new file mode 100644 index 0000000..3de209f Binary files /dev/null and b/QA/static/background.jpg differ diff --git a/QA/static/logo.jpg b/QA/static/logo.jpg new file mode 100644 index 0000000..2d5e129 Binary files /dev/null and b/QA/static/logo.jpg differ diff --git a/QA/template/login.tmpl b/QA/template/login.tmpl new file mode 100644 index 0000000..5f60014 --- /dev/null +++ b/QA/template/login.tmpl @@ -0,0 +1,96 @@ + + + + + + 登录 + + + +
+

登录

+
+
+ + +
+
+ + +
+
+ + +
+
+
+ + + + diff --git a/QA/template/open.tmpl b/QA/template/open.tmpl new file mode 100644 index 0000000..0470ac5 --- /dev/null +++ b/QA/template/open.tmpl @@ -0,0 +1,32 @@ + + + + + Welcome to Hdu.wiki + + + +

欢迎来到杭电论坛!

+Logo +登录 +注册 + + diff --git a/QA/template/register.tmpl b/QA/template/register.tmpl new file mode 100644 index 0000000..3b0b521 --- /dev/null +++ b/QA/template/register.tmpl @@ -0,0 +1,99 @@ + + + + + + 登录 + + + +
+

注册

+
+
+ + +
+
+ + +
+ +
+ +
+ + \ No newline at end of file