diff --git a/api/auth.go b/api/auth.go index 220710d..9f60d0f 100644 --- a/api/auth.go +++ b/api/auth.go @@ -14,10 +14,8 @@ func (AuthApi) Login(c *gin.Context) { middleware.Fail(c, model.ErrParam.AddErr(err)) return } - token, err := authService.Login(param) - middleware.Auto(c, err, map[string]string{ - "token": token, - }) + err := authService.Login(param, c) + middleware.Auto(c, err, nil) return } @@ -31,3 +29,8 @@ func (AuthApi) Register(c *gin.Context) { middleware.Auto(c, err, nil) return } + +func (AuthApi) Logout(c *gin.Context) { + err := authService.Logout(c) + middleware.Auto(c, err, nil) +} diff --git a/config/config.go b/config/config.go index 053da2e..f090fd3 100644 --- a/config/config.go +++ b/config/config.go @@ -7,19 +7,21 @@ import ( ) var ( - ServerName = "auth-server" // 服务名称 - ServerHost string - ServerPort int - DebugMode bool - JwtSecret []byte //jwt密钥 - JwtExpire = 3 * time.Hour //jwt过期时间 - DataBaseHost string - DataBasePort int - DataBaseName string + ServerName = "auth-server" // 服务名称 + ServerHost string + ServerPort int + DebugMode bool + JwtSecret []byte //jwt密钥 + JwtExpire = 3 * time.Hour //jwt过期时间 + SessionExpire = 3600 * 1 // session过期时间 1h + SessionSecret = "bGjW7xiMrxC9lmXN" + DataBaseHost string + DataBasePort int + DataBaseName string ) func initConfig() { - //环境变量生效优先级 命令航》环境变量》配置文件 + //环境变量生效优先级 命令行》环境变量》配置文件 if serverHost := os.Getenv("SERVER_HOST"); serverHost != "" { ServerHost = serverHost } @@ -42,4 +44,7 @@ func initConfig() { if dataBaseName := os.Getenv("DATABASE_NAME"); dataBaseName != "" { DataBaseName = dataBaseName } + if sessionSecret := os.Getenv("SESSION_SECRET"); sessionSecret != "" { + SessionSecret = sessionSecret + } } diff --git a/go.mod b/go.mod index 9e5752b..0bf67e8 100644 --- a/go.mod +++ b/go.mod @@ -3,16 +3,18 @@ module auth-server go 1.20 require ( + github.com/gin-gonic/contrib v0.0.0-20221130124618-7e01895a63f2 github.com/gin-gonic/gin v1.9.1 github.com/golang-jwt/jwt/v5 v5.2.0 github.com/pkg/errors v0.9.1 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.16.0 - gorm.io/driver/sqlite v1.5.4 - gorm.io/gorm v1.25.5 + gorm.io/driver/sqlite v1.5.5 + gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde ) require ( + github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect github.com/bytedance/sonic v1.10.0 // indirect github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect github.com/chenzhuoyu/iasm v0.9.0 // indirect @@ -23,6 +25,10 @@ require ( github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.15.1 // indirect github.com/goccy/go-json v0.10.2 // indirect + github.com/gomodule/redigo v2.0.0+incompatible // indirect + github.com/gorilla/context v1.1.1 // indirect + github.com/gorilla/securecookie v1.1.1 // indirect + github.com/gorilla/sessions v1.2.1 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect @@ -31,7 +37,7 @@ require ( github.com/leodido/go-urn v1.2.4 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-isatty v0.0.19 // indirect - github.com/mattn/go-sqlite3 v1.14.19 // indirect + github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect diff --git a/go.sum b/go.sum index 0e67c53..9f0d2fa 100644 --- a/go.sum +++ b/go.sum @@ -38,6 +38,8 @@ cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3f dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04= +github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw= github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= github.com/bytedance/sonic v1.10.0 h1:qtNZduETEIWJVIyDl01BeNxur2rW9OwTQ/yBqFRkKEk= @@ -72,6 +74,8 @@ github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= 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/contrib v0.0.0-20221130124618-7e01895a63f2 h1:dyuNlYlG1faymw39NdJddnzJICy6587tiGSVioWhYoE= +github.com/gin-gonic/contrib v0.0.0-20221130124618-7e01895a63f2/go.mod h1:iqneQ2Df3omzIVTkIfn7c1acsVnMGiSLn4XF5Blh3Yg= github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= @@ -114,6 +118,8 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -146,6 +152,13 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.1.1/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w= +github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= +github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= @@ -177,8 +190,8 @@ github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0V github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-sqlite3 v1.14.19 h1:fhGleo2h1p8tVChob4I9HpmVFIAkKGpiukdrgQbWfGI= -github.com/mattn/go-sqlite3 v1.14.19/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= +github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -543,10 +556,10 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 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/sqlite v1.5.4 h1:IqXwXi8M/ZlPzH/947tn5uik3aYQslP9BVveoax0nV0= -gorm.io/driver/sqlite v1.5.4/go.mod h1:qxAuCol+2r6PannQDpOP1FP6ag3mKi4esLnB/jHed+4= -gorm.io/gorm v1.25.5 h1:zR9lOiiYf09VNh5Q1gphfyia1JpiClIWG9hQaxB/mls= -gorm.io/gorm v1.25.5/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= +gorm.io/driver/sqlite v1.5.5 h1:7MDMtUZhV065SilG62E0MquljeArQZNfJnjd9i9gx3E= +gorm.io/driver/sqlite v1.5.5/go.mod h1:6NgQ7sQWAIFsPrJJl1lSNSu2TABh0ZZ/zm5fosATavE= +gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde h1:9DShaph9qhkIYw7QF91I/ynrr4cOO2PZra2PFD7Mfeg= +gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/middleware/sess.go b/middleware/sess.go new file mode 100644 index 0000000..72ff5b4 --- /dev/null +++ b/middleware/sess.go @@ -0,0 +1,19 @@ +package middleware + +import ( + "auth-server/model" + "github.com/gin-gonic/contrib/sessions" + "github.com/gin-gonic/gin" +) + +func SessionAuth() gin.HandlerFunc { + return func(c *gin.Context) { + session := sessions.Default(c) + user := session.Get("user") + if user == nil { + Fail(c, model.ErrNotLogin) + return + } + c.Next() + } +} diff --git a/model/errorcode.go b/model/errorcode.go index 744862d..a897f85 100644 --- a/model/errorcode.go +++ b/model/errorcode.go @@ -39,13 +39,15 @@ func responseErrCode(code int, msg string) ErrorCode { var ( Err = responseErrCode(400, "接口错误") // 通用错误 + ErrNotLogin = responseErrCode(403, "未登陆") // 通用错误 ErrParam = responseErrCode(10001, "参数有误") ErrLonginParam = responseErrCode(10001, "用户名或密码错误") ErrSignParam = responseErrCode(10002, "签名参数有误") ErrAuthToken = responseErrCode(10003, "token错误") ErrGenToken = responseErrCode(10004, "token生成错误") ErrRegisterParam = responseErrCode(10005, "用户名已存在") - ErrAuthCheckTokenFail = responseErrCode(10005, "token鉴权失败") + ErrAuthCheckTokenFail = responseErrCode(10006, "token鉴权失败") + ErrSession = responseErrCode(10007, "session保存失败") ErrDb = responseErrCode(20003, "数据库错误") // ...... diff --git a/router/auth.go b/router/auth.go index 572e81a..8669c62 100644 --- a/router/auth.go +++ b/router/auth.go @@ -3,6 +3,7 @@ package router import "github.com/gin-gonic/gin" func authRouter(router *gin.RouterGroup) { - router.POST("/auth/login", apiAuth.Login) - router.POST("/auth/register", apiAuth.Register) + router.POST("/login", apiAuth.Login) + router.POST("/register", apiAuth.Register) + router.POST("/logout", apiAuth.Logout) } diff --git a/router/init.go b/router/init.go index af077bb..b6013c8 100644 --- a/router/init.go +++ b/router/init.go @@ -4,6 +4,7 @@ import ( "auth-server/api" "auth-server/config" "auth-server/middleware" + "github.com/gin-gonic/contrib/sessions" "strconv" "github.com/gin-gonic/gin" @@ -18,12 +19,22 @@ var ( func InitRouter() { engine := gin.New() engine.Use(gin.Recovery()) + + // session 设置 + store := sessions.NewCookieStore([]byte(config.SessionSecret)) + store.Options(sessions.Options{ + Path: "/", + MaxAge: config.SessionExpire, // 设置超时时间为一个小时 + }) + engine.Use(sessions.Sessions("sid", store)) + // 登陆认证相关路由 - authRouterGroup := engine.Group("/api/v1") + authRouterGroup := engine.Group("/auth") authRouter(authRouterGroup) // 用户登陆 userRouterGroup := engine.Group("/api/v1") - userRouterGroup.Use(middleware.JWT()) + userRouterGroup.Use(middleware.SessionAuth()) + userRouter(userRouterGroup) port := config.ServerPort runParams := config.ServerHost + ":" + strconv.Itoa(port) diff --git a/services/auth.go b/services/auth.go index 90b8d2e..8fdcfbd 100644 --- a/services/auth.go +++ b/services/auth.go @@ -2,8 +2,9 @@ package services import ( "auth-server/common" - "auth-server/config" "auth-server/model" + "github.com/gin-gonic/contrib/sessions" + "github.com/gin-gonic/gin" "github.com/pkg/errors" ) @@ -34,7 +35,7 @@ func (AuthService) Register(user *model.User) (err model.ErrorCode) { return } -func (AuthService) Login(loginUser model.LoginUser) (token string, err model.ErrorCode) { +func (AuthService) Login(loginUser model.LoginUser, c *gin.Context) (err model.ErrorCode) { var user model.User var found bool user, found, err = proxyUser.GetUserByUsername(loginUser.Username) @@ -45,17 +46,27 @@ func (AuthService) Login(loginUser model.LoginUser) (token string, err model.Err err = model.ErrLonginParam.AddErr(UserNotFoundErr) return } - slat := user.Salt - enPassword := common.MD5(slat + loginUser.Password) + salt := user.Salt + enPassword := common.MD5(salt + loginUser.Password) if enPassword != user.Password { err = model.ErrLonginParam return } - var genTokenErr error - token, genTokenErr = common.GenerateToken(loginUser.Username, config.JwtSecret, config.JwtExpire, config.ServerName) - if genTokenErr != nil { - err = model.ErrGenToken.AddErr(genTokenErr) - return + sess := sessions.Default(c) + sess.Set("user", user.ID) + saveErr := sess.Save() + if saveErr != nil { + err = model.ErrSession.AddErr(saveErr) + } + return +} + +func (AuthService) Logout(c *gin.Context) (err model.ErrorCode) { + sess := sessions.Default(c) + sess.Clear() + saveErr := sess.Save() + if saveErr != nil { + err = model.ErrSession.AddErr(saveErr) } return }