From ad90aa63da0c26ecda8a3c1fa88d2c53229ab128 Mon Sep 17 00:00:00 2001 From: hiveminded Date: Fri, 1 Sep 2017 12:43:57 +0300 Subject: [PATCH] update to latest iris for longChat-Server --- apiService/api/api.go | 45 ++++++++++---------- apiService/api/auth.go | 71 +++++++++++++++++-------------- apiService/api/group.go | 48 +++++++++------------ apiService/api/user.go | 64 +++++++++++++--------------- apiService/apiServer.go | 6 +-- messageService/message/server.go | 8 ++-- storageService/storage/auth.go | 19 ++++++--- storageService/storage/storage.go | 4 +- 8 files changed, 133 insertions(+), 132 deletions(-) diff --git a/apiService/api/api.go b/apiService/api/api.go index 8097058..e6d2528 100755 --- a/apiService/api/api.go +++ b/apiService/api/api.go @@ -5,19 +5,18 @@ import ( "strings" "time" - "github.com/iris-contrib/sessiondb/redis" - "github.com/iris-contrib/sessiondb/redis/service" "github.com/kataras/iris" - iconfig "github.com/kataras/iris/config" + "github.com/kataras/iris/sessions" + "github.com/kataras/iris/sessions/sessiondb/redis" + "github.com/kataras/iris/sessions/sessiondb/redis/service" + "github.com/longchat/longChat-Server/common/config" "github.com/longchat/longChat-Server/common/consts" "github.com/longchat/longChat-Server/idService/generator" "github.com/longchat/longChat-Server/storageService/storage" ) -func Iint(framework *iris.Framework, idGen *generator.IdGenerator, store *storage.Storage) { - framework.Config.Gzip = true - +func Init(framework *iris.Application, idGen *generator.IdGenerator, store *storage.Storage) { redisAddr, err := config.GetConfigString(consts.RedisAddress) if err != nil { log.Fatalf(consts.ErrGetConfigFailed(consts.RedisAddress, err)) @@ -34,22 +33,24 @@ func Iint(framework *iris.Framework, idGen *generator.IdGenerator, store *storag if err != nil { log.Fatalf(consts.ErrGetConfigFailed(consts.SessionCookieName, err)) } - framework.Config.Sessions = iconfig.Sessions{ - Cookie: cookie, - GcDuration: time.Duration(2) * time.Hour, - } + sess := sessions.New(sessions.Config{ + Cookie: cookie, + Expires: time.Duration(2) * time.Hour, + }) db := redis.New(service.Config{Network: service.DefaultRedisNetwork, - Addr: redisAddr, - Password: redisPsw, - Database: "0", - MaxIdle: 4, - MaxActive: 4, - IdleTimeout: service.DefaultRedisIdleTimeout, - Prefix: redisPrefix, - MaxAgeSeconds: service.DefaultRedisMaxAgeSeconds}) // optionally configure the bridge between your redis server + Addr: redisAddr, + Password: redisPsw, + Database: "0", + MaxIdle: 4, + MaxActive: 4, + IdleTimeout: service.DefaultRedisIdleTimeout, + Prefix: redisPrefix}) - framework.UseSessionDB(db) + sess.UseDatabase(db) + + framework.Use(iris.Gzip) + framework.StaticWeb("/static", staicPath) addrStr, err := config.GetConfigString(consts.LeafMsgServiceAddress) if err != nil { @@ -59,13 +60,13 @@ func Iint(framework *iris.Framework, idGen *generator.IdGenerator, store *storag ua := UserApi{idGen: idGen, store: store, serverAddrs: addrs} ua.RegisterRoute(framework) au := AuthApi{store: store} - au.RegisterRoute(framework) + au.RegisterRoute(framework, sess) ga := GroupApi{idGen: idGen, store: store} - ga.RegisterRoute(framework) + ga.RegisterRoute(framework, sess) staicPath, err := config.GetConfigString(consts.ApiServiceStaticPath) if err != nil { log.Fatalf(consts.ErrGetConfigFailed(consts.ApiServiceAddress, err)) } - framework.Static("/static", staicPath, 1) + } diff --git a/apiService/api/auth.go b/apiService/api/auth.go index 830b92a..09a5ae8 100755 --- a/apiService/api/auth.go +++ b/apiService/api/auth.go @@ -4,10 +4,11 @@ import ( "crypto/sha256" "encoding/hex" "fmt" - "net/http" "time" "github.com/kataras/iris" + "github.com/kataras/iris/sessions" + "github.com/longchat/longChat-Server/apiService/api/dto" "github.com/longchat/longChat-Server/common/config" "github.com/longchat/longChat-Server/common/consts" @@ -20,9 +21,9 @@ type AuthApi struct { store *storage.Storage } -func (au *AuthApi) RegisterRoute(framework *iris.Framework) { - framework.Post("/login", au.login) - framework.Post("/logout", au.login) +func (au *AuthApi) RegisterRoute(framework *iris.Application, sess *sessions.Sessions) { + framework.Post("/login", au.login(sess)) + framework.Post("/logout", au.logout(sess)) } func getHashedPassword(raw string, salt string) string { @@ -39,36 +40,44 @@ func newToken(id int64) (string, error) { return util.NewToken(id, privateToken, time.Hour*12), nil } -func (au *AuthApi) login(c *iris.Context) { - var loginReq dto.LoginReq - err := c.ReadJSON(&loginReq) - if err != nil { - c.JSON(http.StatusBadRequest, dto.PostDataErrRsp("LoginReq")) - return - } - user, err := au.store.GetUserByUserName(loginReq.UserName) - if err != nil { - log.ERROR.Printf("GetUserByUserName(%s) from storage failed!err:=%v\n", loginReq.UserName, err) - c.JSON(http.StatusInternalServerError, dto.InternalErrRsp()) - return - } - if getHashedPassword(loginReq.Password, user.Salt) != user.Password { - c.JSON(http.StatusUnauthorized, dto.PasswordNotMatchErrRsp()) - return - } - c.Session().Set("Id", user.Id) +func (au *AuthApi) login(sess *sessions.Sessions) func(iris.Context) { + return func(c iris.Context) { + var loginReq dto.LoginReq + err := c.ReadJSON(&loginReq) + if err != nil { + c.StatusCode(iris.StatusBadRequest) + c.JSON(dto.PostDataErrRsp("LoginReq")) + return + } + user, err := au.store.GetUserByUserName(loginReq.UserName) + if err != nil { + log.ERROR.Printf("GetUserByUserName(%s) from storage failed!err:=%v\n", loginReq.UserName, err) + c.StatusCode(iris.StatusInternalServerError) + c.JSON(dto.InternalErrRsp()) + return + } + if getHashedPassword(loginReq.Password, user.Salt) != user.Password { + c.StatusCode(iris.StatusUnauthorized) + c.JSON(dto.PasswordNotMatchErrRsp()) + return + } + session := sess.Start(c) + session.Set("Id", user.Id) - var userDto dto.UserInfo - userDto.Id = fmt.Sprintf("%d", user.Id) - userDto.Avatar = user.Avatar - userDto.Introduce = user.Introduce - userDto.NickName = user.NickName + var userDto dto.UserInfo + userDto.Id = fmt.Sprintf("%d", user.Id) + userDto.Avatar = user.Avatar + userDto.Introduce = user.Introduce + userDto.NickName = user.NickName - var rsp dto.LoginRsp - rsp.Data.User = userDto - c.JSON(http.StatusOK, &rsp) + var rsp dto.LoginRsp + rsp.Data.User = userDto + c.JSON(&rsp) + } } -func (au *AuthApi) logout(c *iris.Context) { +func (au *AuthApi) logout(sess *sessions.Sessions) func(iris.Context) { + return func(c iris.Context) { + } } diff --git a/apiService/api/group.go b/apiService/api/group.go index 75fd904..94aa127 100755 --- a/apiService/api/group.go +++ b/apiService/api/group.go @@ -2,9 +2,9 @@ package api import ( "fmt" - "net/http" "github.com/kataras/iris" + "github.com/longchat/longChat-Server/apiService/api/dto" "github.com/longchat/longChat-Server/common/log" "github.com/longchat/longChat-Server/idService/generator" @@ -16,45 +16,34 @@ type GroupApi struct { store *storage.Storage } -func (ga *GroupApi) RegisterRoute(framework *iris.Framework) { +func (ga *GroupApi) RegisterRoute(framework *iris.Application) { users := framework.Party("/groups") users.Get("", ga.getGroupList) - users.Get("/:id", ga.getGroupDetail) - users.Post("/:id/members/:uid", ga.joinGroup) + users.Get("/{id:long}", ga.getGroupDetail) + users.Post("/{id:long}/members/{uid:long}", ga.joinGroup) } -func (ga *GroupApi) joinGroup(c *iris.Context) { - gId, err := c.ParamInt64("id") - if err != nil { - c.JSON(http.StatusBadRequest, dto.ParameterErrRsp("id")) - return - } - uId, err := c.ParamInt64("uid") - if err != nil { - c.JSON(http.StatusBadRequest, dto.ParameterErrRsp("uid")) - return - } - +func (ga *GroupApi) joinGroup(c iris.Context) { + gId, _ := c.Params().GetInt64("id") + uId, _ := c.Params().GetInt64("uid") err = ga.store.AddUserGroup(uId, gId) if err != nil { - c.JSON(http.StatusInternalServerError, dto.InternalErrRsp()) + c.StatusCode(iris.StatusInternalServerError) + c.JSON(dto.InternalErrRsp()) return } rsp := dto.SuccessRsp() - c.JSON(200, &rsp) + c.JSON(&rsp) } -func (ga *GroupApi) getGroupDetail(c *iris.Context) { - gId, err := c.ParamInt64("id") - if err != nil { - c.JSON(http.StatusBadRequest, dto.ParameterErrRsp("id")) - return - } +func (ga *GroupApi) getGroupDetail(c iris.Context) { + gId, _ := c.Params().GetInt64("id") group, err := ga.store.GetGroupById(gId) if err != nil { log.ERROR.Printf("getGroupById(%d) from storage failed!err:=%v\n", gId, err) - c.JSON(http.StatusInternalServerError, dto.InternalErrRsp()) + c.StatusCode(iris.StatusInternalServerError) + c.JSON(dto.InternalErrRsp()) return } users, err := ga.store.GetUsersByIds(group.Members) @@ -78,10 +67,10 @@ func (ga *GroupApi) getGroupDetail(c *iris.Context) { usersDto = append(usersDto, userDto) } rsp.Data.Group.Members = usersDto - c.JSON(200, &rsp) + c.JSON(&rsp) } -func (ga *GroupApi) getGroupList(c *iris.Context) { +func (ga *GroupApi) getGroupList(c iris.Context) { orderIdx, err := c.URLParamInt64("orderidx") if err != nil { orderIdx = 0 @@ -93,7 +82,8 @@ func (ga *GroupApi) getGroupList(c *iris.Context) { groups, err := ga.store.GetGroupsByOrderId(orderIdx, limit) if err != nil { log.ERROR.Printf("GetGroupsByOrderIdx from storage failed!err:=%v\n", err) - c.JSON(http.StatusInternalServerError, dto.InternalErrRsp()) + c.StatusCode(iris.StatusInternalServerError) + c.JSON(dto.InternalErrRsp()) return } groupsDto := make([]dto.Group, limit) @@ -112,5 +102,5 @@ func (ga *GroupApi) getGroupList(c *iris.Context) { BaseRsp: *dto.SuccessRsp(), } rsp.Data.Groups = groupsDto[:len(groups)] - c.JSON(200, &rsp) + c.JSON(&rsp) } diff --git a/apiService/api/user.go b/apiService/api/user.go index 33c86cf..ffe7788 100755 --- a/apiService/api/user.go +++ b/apiService/api/user.go @@ -2,7 +2,6 @@ package api import ( "fmt" - "net/http" "github.com/kataras/iris" "github.com/longchat/longChat-Server/apiService/api/dto" @@ -19,43 +18,37 @@ type UserApi struct { serverAddrs []string } -func (ua *UserApi) RegisterRoute(framework *iris.Framework) { +func (ua *UserApi) RegisterRoute(framework *iris.Application) { users := framework.Party("/users") users.Post("", ua.createUser) - users.Put("/:id", ua.updateInfo) - users.Get("/:id", ua.getInfo) - users.Get("/:id/serveraddr", ua.getserverAddr) + users.Put("/{id:long}", ua.updateInfo) + users.Get("/{id:long}", ua.getInfo) + users.Get("/{id:long}/serveraddr", ua.getserverAddr) } -func (ua *UserApi) getserverAddr(c *iris.Context) { - uid, err := c.ParamInt64("id") - if err != nil { - c.JSON(http.StatusBadRequest, dto.ParameterErrRsp("id")) - return - } +func (ua *UserApi) getserverAddr(c iris.Context) { + uid, _ := c.Params().GetInt64("id") clusterId, err := graph.GetClusterByUserId(uid) if err != nil { log.ERROR.Printf("get user cluster id from graph failed!err:=%v\n", uid, err) - c.JSON(http.StatusInternalServerError, dto.InternalErrRsp()) + c.StatusCode(iris.StatusInternalServerError) + c.JSON(dto.InternalErrRsp()) return } id := clusterId % len(ua.serverAddrs) userRsp := dto.GetUserServerAddrRsp{BaseRsp: *dto.SuccessRsp()} userRsp.Data.Addr = ua.serverAddrs[id] - c.JSON(http.StatusOK, &userRsp) + c.JSON(&userRsp) } -func (ua *UserApi) getInfo(c *iris.Context) { - uid, err := c.ParamInt64("id") - if err != nil { - c.JSON(http.StatusBadRequest, dto.ParameterErrRsp("id")) - return - } +func (ua *UserApi) getInfo(c iris.Context) { + uid, _ := c.Params().GetInt64("id") user, err := ua.store.GetUserById(uid) if err != nil { log.ERROR.Printf("get usser(%d) from storage failed!err:=%v\n", uid, err) - c.JSON(http.StatusInternalServerError, dto.InternalErrRsp()) + c.StatusCode(iris.StatusInternalServerError) + c.JSON(dto.InternalErrRsp()) return } userRsp := dto.GetUserInfoRsp{BaseRsp: *dto.SuccessRsp()} @@ -65,40 +58,40 @@ func (ua *UserApi) getInfo(c *iris.Context) { Avatar: user.Avatar, Introduce: user.Introduce, } - c.JSON(http.StatusOK, &userRsp) + c.JSON(&userRsp) } -func (ua *UserApi) updateInfo(c *iris.Context) { +func (ua *UserApi) updateInfo(c iris.Context) { var infoReq dto.UpdateInfoReq err := c.ReadJSON(&infoReq) if err != nil { - c.JSON(http.StatusBadRequest, dto.PostDataErrRsp("UpdateInfoReq")) - return - } - uid, err := c.ParamInt64("id") - if err != nil { - c.JSON(http.StatusBadRequest, dto.ParameterErrRsp("id")) + c.StatusCode(iris.StatusBadRequest) + c.JSON(dto.PostDataErrRsp("UpdateInfoReq")) return } + uid, _ := c.Params().GetInt64("id") err = ua.store.UpdateUserInfo(uid, infoReq.NickName, infoReq.Avatar, infoReq.Introduce) if err != nil { log.ERROR.Printf("UpdateUserInfo from storage failed!err:=%v\n", err) - c.JSON(http.StatusInternalServerError, dto.InternalErrRsp()) + c.StatusCode(iris.StatusInternalServerError) + c.JSON(dto.InternalErrRsp()) return } - c.JSON(http.StatusOK, dto.SuccessRsp()) + c.JSON(dto.SuccessRsp()) } -func (ua *UserApi) createUser(c *iris.Context) { +func (ua *UserApi) createUser(c iris.Context) { var userReq dto.CreateUserReq err := c.ReadJSON(&userReq) if err != nil { - c.JSON(http.StatusBadRequest, dto.PostDataErrRsp("CreateUserReq")) + c.StatusCode(iris.StatusBadRequest) + c.JSON(dto.PostDataErrRsp("CreateUserReq")) return } id, err := ua.idGen.Generate(generator.GenerateReq_User) if err != nil { - c.JSON(http.StatusInternalServerError, dto.InternalErrRsp()) + c.StatusCode(iris.StatusInternalServerError) + c.JSON(dto.InternalErrRsp()) return } salt := util.RandomString(8) @@ -106,8 +99,9 @@ func (ua *UserApi) createUser(c *iris.Context) { err = ua.store.CreateUser(id, userReq.UserName, hashedPassword, salt, c.RemoteAddr()) if err != nil { log.ERROR.Printf("CreateUser from storage failed!err:=%v\n", err) - c.JSON(http.StatusInternalServerError, dto.InternalErrRsp()) + c.StatusCode(iris.StatusInternalServerError) + c.JSON(dto.InternalErrRsp()) return } - c.JSON(http.StatusOK, dto.SuccessRsp()) + c.JSON(dto.SuccessRsp()) } diff --git a/apiService/apiServer.go b/apiService/apiServer.go index 4cb6da3..764b7f3 100755 --- a/apiService/apiServer.go +++ b/apiService/apiServer.go @@ -58,8 +58,8 @@ func main() { slog.Fatalf("init graph service failed!", err) } defer graph.FinDb() - framework := iris.New() - api.Iint(framework, &idGen, store) - framework.Listen(addr) + framework := iris.New() + api.Init(framework, &idGen, store) + framework.Run(iris.Addr(addr)) } diff --git a/messageService/message/server.go b/messageService/message/server.go index 637b9f5..0196f0e 100755 --- a/messageService/message/server.go +++ b/messageService/message/server.go @@ -124,19 +124,19 @@ func (s *Server) serveLeaf(w http.ResponseWriter, r *http.Request) { w.Write([]byte("invalid session cookie")) return } - rmap, err := store.GetSessionValue(sId) + svalues, err := store.GetSessionValue(sId) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("internal server error")) return } - uid, isok := rmap["Id"] - if !isok { + + userId, err := svalues.GetInt64["Id"] + if err != nil { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte("invalid session")) return } - userId := uid.(int64) user, err := store.GetUserById(userId) if err != nil { w.WriteHeader(http.StatusInternalServerError) diff --git a/storageService/storage/auth.go b/storageService/storage/auth.go index b621a09..4a84b83 100755 --- a/storageService/storage/auth.go +++ b/storageService/storage/auth.go @@ -1,19 +1,24 @@ package storage import ( - "github.com/kataras/iris/utils" + "github.com/kataras/iris/core/memstore" + "github.com/kataras/iris/sessions" + "gopkg.in/redis.v4" ) -func getSessionValue(redisCli *redis.ClusterClient, key string) (map[string]interface{}, error) { +func getSessionValue(redisCli *redis.ClusterClient, key string) (memstore.Store, error) { + var emptyValues memstore.Store + b, err := redisCli.Get(key).Bytes() if err != nil { - return nil, err + return emptyValues, err } - r := make(map[string]interface{}) - err = utils.DeserializeBytes(b, &r) + + r, err := sessions.DecodeRemoteStore(b) // decode the whole value, as a remote store if err != nil { - return nil, err + return emptyValues, err } - return r, nil + + return r.Values, nil } diff --git a/storageService/storage/storage.go b/storageService/storage/storage.go index b19d09f..a242845 100755 --- a/storageService/storage/storage.go +++ b/storageService/storage/storage.go @@ -6,6 +6,8 @@ import ( "strings" "time" + "github.com/kataras/iris/core/memstore" + "github.com/go-xorm/core" "github.com/go-xorm/xorm" "github.com/longchat/longChat-Server/common/config" @@ -270,7 +272,7 @@ func (s *Storage) GetGroupById(id int64) (*schema.Group, error) { return getGroupById(s.getDb(0, id), id) } -func (s *Storage) GetSessionValue(key string) (map[string]interface{}, error) { +func (s *Storage) GetSessionValue(key string) (memstore.Store, error) { return getSessionValue(s.redis, s.sessionPrefix+key) }