multi terminal kick eachOther

pull/103/head
Gordon 3 years ago
parent 912ec51315
commit e7e3b6dd15

@ -130,10 +130,7 @@ manager:
secret: tuoyun
multiloginpolicy:
onlyOneTerminalAccess: false
mobileAndPCTerminalAccessButOtherTerminalKickEachOther: true
allTerminalAccess: false
multiloginpolicy: 1
#token config
tokenpolicy:

@ -3,9 +3,9 @@ package apiChat
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbMsg "Open_IM/pkg/proto/chat"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
"net/http"
@ -27,8 +27,8 @@ func UserGetSeq(c *gin.Context) {
}
token := c.Request.Header.Get("token")
if !utils.VerifyToken(token, params.SendID) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err"})
if ok, err := token_verify.VerifyToken(token, params.SendID); !ok {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err" + err.Error()})
return
}
pbData := pbMsg.GetMaxAndMinSeqReq{}

@ -3,9 +3,9 @@ package apiChat
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
"Open_IM/pkg/proto/chat"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
"net/http"
@ -30,8 +30,8 @@ func UserPullMsg(c *gin.Context) {
}
token := c.Request.Header.Get("token")
if !utils.VerifyToken(token, params.SendID) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err"})
if ok, err := token_verify.VerifyToken(token, params.SendID); !ok {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err" + err.Error()})
return
}
pbData := pbChat.PullMessageReq{}
@ -86,8 +86,8 @@ func UserPullMsgBySeqList(c *gin.Context) {
}
token := c.Request.Header.Get("token")
if !utils.VerifyToken(token, params.SendID) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err"})
if ok, err := token_verify.VerifyToken(token, params.SendID); !ok {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err" + err.Error()})
return
}
pbData := pbChat.PullMessageBySeqListReq{}

@ -3,9 +3,9 @@ package group
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
"Open_IM/pkg/proto/group"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
"net/http"
@ -56,7 +56,7 @@ func GetGroupApplicationList(c *gin.Context) {
pbData := newUserRegisterReq(&params)
token := c.Request.Header.Get("token")
if claims, err := utils.ParseToken(token); err != nil {
if claims, err := token_verify.ParseToken(token); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err"})
return
} else {

@ -3,9 +3,9 @@ package group
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
"Open_IM/pkg/proto/group"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
"net/http"
@ -63,7 +63,7 @@ func ApplicationGroupResponse(c *gin.Context) {
pbData := newGroupApplicationResponse(&params)
token := c.Request.Header.Get("token")
if claims, err := utils.ParseToken(token); err != nil {
if claims, err := token_verify.ParseToken(token); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err"})
return
} else {

@ -3,9 +3,9 @@ package group
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
"Open_IM/pkg/proto/group"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
"net/http"
@ -41,7 +41,7 @@ func TransferGroupOwner(c *gin.Context) {
pbData := newTransferGroupOwnerReq(&params)
token := c.Request.Header.Get("token")
if claims, err := utils.ParseToken(token); err != nil {
if claims, err := token_verify.ParseToken(token); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err"})
return
} else {

@ -10,6 +10,7 @@ import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbChat "Open_IM/pkg/proto/chat"
"Open_IM/pkg/utils"
@ -125,7 +126,7 @@ func ManagementSendMsg(c *gin.Context) {
}
token := c.Request.Header.Get("token")
claims, err := utils.ParseToken(token)
claims, err := token_verify.ParseToken(token)
if err != nil {
log.NewError(params.OperationID, "parse token failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "parse token failed", "sendTime": 0, "MsgID": ""})

@ -2,6 +2,7 @@ package apiThird
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
log2 "Open_IM/pkg/common/log"
"github.com/gin-gonic/gin"
sts "github.com/tencentyun/qcloud-cos-sts-sdk/go"
@ -70,7 +71,7 @@ func TencentCloudStorageCredential(c *gin.Context) {
if err != nil {
log2.Error(c.Request.Header.Get("token"), c.PostForm("optionID"), "api TencentUpLoadCredential cli.GetCredential err = %s", err.Error())
c.JSON(http.StatusOK, gin.H{
"errCode": config.ErrTencentCredential.ErrCode,
"errCode": constant.ErrTencentCredential.ErrCode,
"errMsg": err.Error(),
"bucket": "",
"region": "",

@ -30,7 +30,7 @@ func (ws *WServer) msgParse(conn *UserConn, binaryMsg []byte) {
dec := gob.NewDecoder(b)
err := dec.Decode(&m)
if err != nil {
log.ErrorByKv("ws json Unmarshal err", "", "err", err.Error())
log.ErrorByKv("ws Decode err", "", "err", err.Error())
ws.sendErrMsg(conn, 200, err.Error(), constant.WSDataError, "", "")
err = conn.Close()
if err != nil {

@ -103,14 +103,14 @@ func (r *RPCServer) MsgToUser(_ context.Context, in *pbRelay.MsgToUserReq) (*pbR
temp := &pbRelay.SingleMsgToUser{
ResultCode: resultCode,
RecvID: UIDAndPID[0],
RecvPlatFormID: utils.PlatformNameToID(UIDAndPID[1]),
RecvPlatFormID: constant.PlatformNameToID(UIDAndPID[1]),
}
resp = append(resp, temp)
} else {
temp := &pbRelay.SingleMsgToUser{
ResultCode: -1,
RecvID: UIDAndPID[0],
RecvPlatFormID: utils.PlatformNameToID(UIDAndPID[1]),
RecvPlatFormID: constant.PlatformNameToID(UIDAndPID[1]),
}
resp = append(resp, temp)
}
@ -127,7 +127,7 @@ func sendMsgToUser(conn *UserConn, bMsg []byte, in *pbRelay.MsgToUserReq, RecvPl
err := ws.writeMsg(conn, websocket.BinaryMessage, bMsg)
if err != nil {
log.ErrorByKv("PushMsgToUser is failed By Ws", "", "Addr", conn.RemoteAddr().String(),
"error", err, "senderPlatform", utils.PlatformIDToName(in.PlatformID), "recvPlatform", RecvPlatForm, "args", in.String(), "recvID", RecvID)
"error", err, "senderPlatform", constant.PlatformIDToName(in.PlatformID), "recvPlatform", RecvPlatForm, "args", in.String(), "recvID", RecvID)
ResultCode = -2
return ResultCode
} else {
@ -138,8 +138,8 @@ func sendMsgToUser(conn *UserConn, bMsg []byte, in *pbRelay.MsgToUserReq, RecvPl
}
func genUidPlatformArray(uid string) (array []string) {
for i := 1; i <= utils.LinuxPlatformID; i++ {
array = append(array, uid+" "+utils.PlatformIDToName(int32(i)))
for i := 1; i <= constant.LinuxPlatformID; i++ {
array = append(array, uid+" "+constant.PlatformIDToName(int32(i)))
}
return array
}

@ -2,8 +2,13 @@ package gate
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/utils"
"bytes"
"encoding/gob"
"github.com/gorilla/websocket"
"net/http"
"sync"
@ -53,10 +58,10 @@ func (ws *WServer) wsHandler(w http.ResponseWriter, r *http.Request) {
} else {
//Connection mapping relationship,
//userID+" "+platformID->conn
SendID := query["sendID"][0] + " " + utils.PlatformIDToName(int32(utils.StringToInt64(query["platformID"][0])))
//Initialize a lock for each user
newConn := &UserConn{conn, new(sync.Mutex)}
ws.addUserConn(SendID, newConn)
ws.addUserConn(query["sendID"][0], int32(utils.StringToInt64(query["platformID"][0])), newConn, query["token"][0])
go ws.readMsg(newConn)
}
}
@ -86,20 +91,66 @@ func (ws *WServer) writeMsg(conn *UserConn, a int, msg []byte) error {
return conn.WriteMessage(a, msg)
}
func (ws *WServer) addUserConn(uid string, conn *UserConn) {
rwLock.Lock()
defer rwLock.Unlock()
if oldConn, ok := ws.wsUserToConn[uid]; ok {
err := oldConn.Close()
delete(ws.wsConnToUser, oldConn)
if err != nil {
log.ErrorByKv("close err", "", "uid", uid, "conn", conn)
func (ws *WServer) MultiTerminalLoginChecker(uid string, platformID int32, newConn *UserConn, token string) {
switch config.Config.MultiLoginPolicy {
case constant.AllLoginButSameTermKick:
if oldConn, ok := ws.wsUserToConn[genMapKey(uid, platformID)]; ok {
ws.sendKickMsg(oldConn, newConn)
m, err := db.DB.GetTokenMapByUidPid(uid, utils.Int32ToString(platformID))
if err != nil {
log.NewError("", "get token from redis err", err.Error())
return
}
if m == nil {
log.NewError("", "get token from redis err", "m is nil")
return
}
for k, _ := range m {
if k != token {
m[k] = constant.KickedToken
}
}
err = db.DB.SetTokenMapByUidPid(uid, utils.Int32ToString(platformID), m)
if err != nil {
log.NewError("", "SetTokenMapByUidPid err", err.Error())
return
}
err = oldConn.Close()
delete(ws.wsConnToUser, oldConn)
if err != nil {
log.NewError("", "conn close err", err.Error())
}
}
} else {
log.InfoByKv("this user is first login", "", "uid", uid)
case constant.SingleTerminalLogin:
case constant.WebAndOther:
}
}
func (ws *WServer) sendKickMsg(oldConn, newConn *UserConn) {
mReply := Resp{
ReqIdentifier: constant.WSKickOnlineMsg,
ErrCode: constant.ErrTokenInvalid.ErrCode,
ErrMsg: constant.ErrTokenInvalid.ErrMsg,
}
ws.wsConnToUser[conn] = uid
ws.wsUserToConn[uid] = conn
var b bytes.Buffer
enc := gob.NewEncoder(&b)
err := enc.Encode(mReply)
if err != nil {
log.NewError(mReply.OperationID, mReply.ReqIdentifier, mReply.ErrCode, mReply.ErrMsg, "Encode Msg error", oldConn.RemoteAddr().String(), newConn.RemoteAddr().String(), err.Error())
return
}
err = ws.writeMsg(oldConn, websocket.BinaryMessage, b.Bytes())
if err != nil {
log.NewError(mReply.OperationID, mReply.ReqIdentifier, mReply.ErrCode, mReply.ErrMsg, "WS WriteMsg error", oldConn.RemoteAddr().String(), newConn.RemoteAddr().String(), err.Error())
}
}
func (ws *WServer) addUserConn(uid string, platformID int32, conn *UserConn, token string) {
key := genMapKey(uid, platformID)
rwLock.Lock()
defer rwLock.Unlock()
ws.MultiTerminalLoginChecker(uid, platformID, conn, token)
ws.wsConnToUser[conn] = key
ws.wsUserToConn[key] = conn
log.WarnByKv("WS Add operation", "", "wsUser added", ws.wsUserToConn, "uid", uid, "online_num", len(ws.wsUserToConn))
}
@ -146,10 +197,11 @@ func (ws *WServer) headerCheck(w http.ResponseWriter, r *http.Request) bool {
status := http.StatusUnauthorized
query := r.URL.Query()
if len(query["token"]) != 0 && len(query["sendID"]) != 0 && len(query["platformID"]) != 0 {
if !utils.VerifyToken(query["token"][0], query["sendID"][0]) {
if ok, err := token_verify.VerifyToken(query["token"][0], query["sendID"][0]); !ok {
e := err.(*constant.ErrInfo)
log.ErrorByKv("Token verify failed", "", "query", query)
w.Header().Set("Sec-Websocket-Version", "13")
http.Error(w, http.StatusText(status), status)
http.Error(w, e.ErrMsg, int(e.ErrCode))
return false
} else {
log.InfoByKv("Connection Authentication Success", "", "token", query["token"][0], "userID", query["sendID"][0])
@ -163,3 +215,6 @@ func (ws *WServer) headerCheck(w http.ResponseWriter, r *http.Request) bool {
}
}
func genMapKey(uid string, platformID int32) string {
return uid + " " + constant.PlatformIDToName(platformID)
}

@ -1,7 +1,7 @@
package requestBody
import (
"Open_IM/pkg/utils"
"Open_IM/pkg/common/constant"
"errors"
)
@ -53,9 +53,9 @@ func (p *Platform) Set(os string) error {
}
func (p *Platform) SetPlatform(platform string) error {
switch platform {
case utils.AndroidPlatformStr:
case constant.AndroidPlatformStr:
return p.SetAndroid()
case utils.IOSPlatformStr:
case constant.IOSPlatformStr:
return p.SetIOS()
default:
return errors.New("platform err")

@ -8,9 +8,9 @@ package logic
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/kafka"
"Open_IM/pkg/common/log"
"Open_IM/pkg/utils"
)
var (
@ -24,7 +24,7 @@ func Init(rpcPort int) {
log.NewPrivateLog(config.Config.ModuleName.PushName)
rpcServer.Init(rpcPort)
pushCh.Init()
pushTerminal = []int32{utils.IOSPlatformID, utils.AndroidPlatformID}
pushTerminal = []int32{constant.IOSPlatformID, constant.AndroidPlatformID}
}
func init() {
producer = kafka.NewKafkaProducer(config.Config.Kafka.Ws2mschat.Addr, config.Config.Kafka.Ws2mschat.Topic)

@ -97,7 +97,7 @@ func MsgToUser(sendPbData *pbRelay.MsgToUserReq, OfflineInfo, Options string) {
default:
content = constant.ContentType2PushContent[constant.Common]
}
pushResult, err := push.JGAccountListPush(UIDList, content, jsonCustomContent, utils.PlatformIDToName(t))
pushResult, err := push.JGAccountListPush(UIDList, content, jsonCustomContent, constant.PlatformIDToName(t))
if err != nil {
log.NewError(sendPbData.OperationID, "offline push error", sendPbData.String(), err.Error(), t)
} else {

@ -3,8 +3,8 @@ package auth
import (
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbAuth "Open_IM/pkg/proto/auth"
"Open_IM/pkg/utils"
"context"
)
@ -18,7 +18,7 @@ func (rpc *rpcAuth) UserToken(_ context.Context, pb *pbAuth.UserTokenReq) (*pbAu
}
log.Info("", "", "rpc user_token call..., im_mysql_model.AppServerFindFromUserByUserID")
tokens, expTime, err := utils.CreateToken(pb.UID, pb.Platform)
tokens, expTime, err := token_verify.CreateToken(pb.UID, pb.Platform)
if err != nil {
log.Error("", "", "rpc user_token call..., utils.CreateToken fail [uid: %s] [err: %s]", pb.UID, err.Error())
return &pbAuth.UserTokenResp{ErrCode: 500, ErrMsg: err.Error()}, err

@ -2,8 +2,10 @@ package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
@ -12,10 +14,10 @@ import (
func (s *friendServer) AddBlacklist(ctx context.Context, req *pbFriend.AddBlacklistReq) (*pbFriend.CommonResp, error) {
log.Info(req.Token, req.OperationID, "rpc add blacklist is server,args=%s", req.String())
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
isMagagerFlag := 0
@ -29,7 +31,7 @@ func (s *friendServer) AddBlacklist(ctx context.Context, req *pbFriend.AddBlackl
err = im_mysql_model.InsertInToUserBlackList(claims.UID, req.Uid)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,Failed to add blacklist", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrMysql.ErrCode, ErrorMsg: config.ErrMysql.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrMysql.ErrCode, ErrorMsg: constant.ErrMysql.ErrMsg}, nil
}
log.Info(req.Token, req.OperationID, "rpc add blacklist success return,uid=%s", req.Uid)
return &pbFriend.CommonResp{}, nil
@ -38,7 +40,7 @@ func (s *friendServer) AddBlacklist(ctx context.Context, req *pbFriend.AddBlackl
err = im_mysql_model.InsertInToUserBlackList(req.OwnerUid, req.Uid)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,Failed to add blacklist", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrMysql.ErrCode, ErrorMsg: config.ErrMysql.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrMysql.ErrCode, ErrorMsg: constant.ErrMysql.ErrMsg}, nil
}
log.Info(req.Token, req.OperationID, "rpc add blacklist success return,uid=%s", req.Uid)
return &pbFriend.CommonResp{}, nil

@ -7,6 +7,7 @@ import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbChat "Open_IM/pkg/proto/chat"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
@ -16,22 +17,22 @@ import (
func (s *friendServer) AddFriend(ctx context.Context, req *pbFriend.AddFriendReq) (*pbFriend.CommonResp, error) {
log.Info(req.Token, req.OperationID, "rpc add friend is server,userid=%s", req.Uid)
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
//Cannot add non-existent users
if _, err = im_mysql_model.FindUserByUID(req.Uid); err != nil {
log.Error(req.Token, req.OperationID, "this user not exists,cant not add friend")
return &pbFriend.CommonResp{ErrorCode: config.ErrAddFriend.ErrCode, ErrorMsg: config.ErrSearchUserInfo.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrAddFriend.ErrCode, ErrorMsg: constant.ErrSearchUserInfo.ErrMsg}, nil
}
//Establish a latest relationship in the friend request table
err = im_mysql_model.ReplaceIntoFriendReq(claims.UID, req.Uid, constant.ApplicationFriendFlag, req.ReqMessage)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,create friend request record failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrAddFriend.ErrCode, ErrorMsg: config.ErrAddFriend.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrAddFriend.ErrCode, ErrorMsg: constant.ErrAddFriend.ErrMsg}, nil
}
log.Info(req.Token, req.OperationID, "rpc add friend is success return,uid=%s", req.Uid)
//Push message when add friend successfully
@ -57,23 +58,23 @@ func (s *friendServer) ImportFriend(ctx context.Context, req *pbFriend.ImportFri
var resp pbFriend.ImportFriendResp
var c pbFriend.CommonResp
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.NewError(req.OperationID, "parse token failed", err.Error())
c.ErrorCode = config.ErrAddFriend.ErrCode
c.ErrorMsg = config.ErrParseToken.ErrMsg
c.ErrorCode = constant.ErrAddFriend.ErrCode
c.ErrorMsg = constant.ErrParseToken.ErrMsg
return &pbFriend.ImportFriendResp{CommonResp: &c, FailedUidList: req.UidList}, nil
}
if !utils.IsContain(claims.UID, config.Config.Manager.AppManagerUid) {
log.NewError(req.OperationID, "not manager uid", claims.UID)
c.ErrorCode = config.ErrAddFriend.ErrCode
c.ErrorCode = constant.ErrAddFriend.ErrCode
c.ErrorMsg = "not authorized"
return &pbFriend.ImportFriendResp{CommonResp: &c, FailedUidList: req.UidList}, nil
}
if _, err = im_mysql_model.FindUserByUID(req.OwnerUid); err != nil {
log.NewError(req.OperationID, "this user not exists,cant not add friend", req.OwnerUid)
c.ErrorCode = config.ErrAddFriend.ErrCode
c.ErrorCode = constant.ErrAddFriend.ErrCode
c.ErrorMsg = "this user not exists,cant not add friend"
return &pbFriend.ImportFriendResp{CommonResp: &c, FailedUidList: req.UidList}, nil
}

@ -3,10 +3,10 @@ package friend
import (
"Open_IM/internal/push/content_struct"
"Open_IM/internal/push/logic"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbChat "Open_IM/pkg/proto/chat"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
@ -16,21 +16,21 @@ import (
func (s *friendServer) AddFriendResponse(ctx context.Context, req *pbFriend.AddFriendResponseReq) (*pbFriend.CommonResp, error) {
log.Info(req.Token, req.OperationID, "rpc add friend response is server,args=%s", req.String())
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
//Check there application before agreeing or refuse to a friend's application
if _, err = im_mysql_model.FindFriendApplyFromFriendReqByUid(req.Uid, claims.UID); err != nil {
log.Error(req.Token, req.OperationID, "No such application record")
return &pbFriend.CommonResp{ErrorCode: config.ErrAgreeToAddFriend.ErrCode, ErrorMsg: config.ErrAgreeToAddFriend.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrAgreeToAddFriend.ErrCode, ErrorMsg: constant.ErrAgreeToAddFriend.ErrMsg}, nil
}
//Change friend request status flag
err = im_mysql_model.UpdateFriendRelationshipToFriendReq(req.Uid, claims.UID, req.Flag)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,update friend request table failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrMysql.ErrCode, ErrorMsg: config.ErrAgreeToAddFriend.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrMysql.ErrCode, ErrorMsg: constant.ErrAgreeToAddFriend.ErrMsg}, nil
}
log.Info(req.Token, req.OperationID, "rpc add friend response success return,userid=%s,flag=%d", req.Uid, req.Flag)
//Change the status of the friend request form

@ -1,26 +1,26 @@
package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
)
func (s *friendServer) DeleteFriend(ctx context.Context, req *pbFriend.DeleteFriendReq) (*pbFriend.CommonResp, error) {
log.Info(req.Token, req.OperationID, "rpc delete friend is server,args=%s", req.String())
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
err = im_mysql_model.DeleteSingleFriendInfo(claims.UID, req.Uid)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,delete friend failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrMysql.ErrCode, ErrorMsg: config.ErrMysql.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrMysql.ErrCode, ErrorMsg: constant.ErrMysql.ErrMsg}, nil
}
log.Info(req.Token, req.OperationID, "rpc delete friend success return")
return &pbFriend.CommonResp{}, nil

@ -1,11 +1,11 @@
package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
)
@ -16,15 +16,15 @@ func (s *friendServer) GetBlacklist(ctx context.Context, req *pbFriend.GetBlackl
comment string
)
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.GetBlacklistResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.GetBlacklistResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
blackListInfo, err := im_mysql_model.GetBlackListByUID(claims.UID)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s get blacklist failed", err.Error())
return &pbFriend.GetBlacklistResp{ErrorCode: config.ErrGetBlackList.ErrCode, ErrorMsg: config.ErrGetBlackList.ErrMsg}, nil
return &pbFriend.GetBlacklistResp{ErrorCode: constant.ErrGetBlackList.ErrCode, ErrorMsg: constant.ErrGetBlackList.ErrMsg}, nil
}
for _, blackUser := range blackListInfo {
var blackUserInfo pbFriend.UserInfo

@ -5,6 +5,7 @@ import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
@ -71,10 +72,10 @@ func (s *friendServer) GetFriendsInfo(ctx context.Context, req *pbFriend.GetFrie
comment string
)
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.GetFriendInfoResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.GetFriendInfoResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
friendShip, err := im_mysql_model.FindFriendRelationshipFromFriend(claims.UID, req.Uid)
if err == nil {
@ -84,7 +85,7 @@ func (s *friendServer) GetFriendsInfo(ctx context.Context, req *pbFriend.GetFrie
friendUserInfo, err := im_mysql_model.FindUserByUID(req.Uid)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,no this user", err.Error())
return &pbFriend.GetFriendInfoResp{ErrorCode: config.ErrSearchUserInfo.ErrCode, ErrorMsg: config.ErrSearchUserInfo.ErrMsg}, nil
return &pbFriend.GetFriendInfoResp{ErrorCode: constant.ErrSearchUserInfo.ErrCode, ErrorMsg: constant.ErrSearchUserInfo.ErrMsg}, nil
}
err = im_mysql_model.FindRelationshipFromBlackList(claims.UID, req.Uid)
if err == nil {

@ -1,11 +1,11 @@
package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
"fmt"
"strconv"
@ -15,16 +15,16 @@ func (s *friendServer) GetFriendApplyList(ctx context.Context, req *pbFriend.Get
log.Info(req.Token, req.OperationID, "rpc get friend apply list is server,args=%s", req.String())
var appleUserList []*pbFriend.ApplyUserInfo
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.GetFriendApplyResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.GetFriendApplyResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
// Find the current user friend applications received
ApplyUsersInfo, err := im_mysql_model.FindFriendsApplyFromFriendReq(claims.UID)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,search applyInfo failed", err.Error())
return &pbFriend.GetFriendApplyResp{ErrorCode: config.ErrMysql.ErrCode, ErrorMsg: config.ErrMysql.ErrMsg}, nil
return &pbFriend.GetFriendApplyResp{ErrorCode: constant.ErrMysql.ErrCode, ErrorMsg: constant.ErrMysql.ErrMsg}, nil
}
for _, applyUserInfo := range ApplyUsersInfo {
var userInfo pbFriend.ApplyUserInfo
@ -57,16 +57,16 @@ func (s *friendServer) GetSelfApplyList(ctx context.Context, req *pbFriend.GetFr
log.Info(req.Token, req.OperationID, "rpc get self apply list is server,args=%s", req.String())
var selfApplyOtherUserList []*pbFriend.ApplyUserInfo
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.GetFriendApplyResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.GetFriendApplyResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
// Find the self add other userinfo
usersInfo, err := im_mysql_model.FindSelfApplyFromFriendReq(claims.UID)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,search self to other user Info failed", err.Error())
return &pbFriend.GetFriendApplyResp{ErrorCode: config.ErrMysql.ErrCode, ErrorMsg: config.ErrMysql.ErrMsg}, nil
return &pbFriend.GetFriendApplyResp{ErrorCode: constant.ErrMysql.ErrCode, ErrorMsg: constant.ErrMysql.ErrMsg}, nil
}
for _, selfApplyOtherUserInfo := range usersInfo {
var userInfo pbFriend.ApplyUserInfo

@ -1,12 +1,11 @@
package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
)
@ -14,15 +13,15 @@ func (s *friendServer) GetFriendList(ctx context.Context, req *pbFriend.GetFrien
log.Info(req.Token, req.OperationID, "rpc get friend list is server,args=%s", req.String())
var userInfoList []*pbFriend.UserInfo
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.GetFriendListResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.GetFriendListResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
friends, err := im_mysql_model.FindUserInfoFromFriend(claims.UID)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s search friendInfo failed", err.Error())
return &pbFriend.GetFriendListResp{ErrorCode: config.ErrSearchUserInfo.ErrCode, ErrorMsg: config.ErrSearchUserInfo.ErrMsg}, nil
return &pbFriend.GetFriendListResp{ErrorCode: constant.ErrSearchUserInfo.ErrCode, ErrorMsg: constant.ErrSearchUserInfo.ErrMsg}, nil
}
for _, friendUser := range friends {
var friendUserInfo pbFriend.UserInfo

@ -1,12 +1,11 @@
package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
"fmt"
)
@ -14,10 +13,10 @@ import (
func (s *friendServer) IsFriend(ctx context.Context, req *pbFriend.IsFriendReq) (*pbFriend.IsFriendResp, error) {
log.InfoByArgs("rpc is friend is server,args=%s", req.String())
var isFriend int32
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.IsFriendResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.IsFriendResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
_, err = im_mysql_model.FindFriendRelationshipFromFriend(claims.UID, req.ReceiveUid)
if err == nil {

@ -1,26 +1,26 @@
package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
)
func (s *friendServer) RemoveBlacklist(ctx context.Context, req *pbFriend.RemoveBlacklistReq) (*pbFriend.CommonResp, error) {
log.Info(req.Token, req.OperationID, "rpc remove blacklist is server,userid=%s", req.Uid)
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
err = im_mysql_model.RemoveBlackList(claims.UID, req.Uid)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,remove blacklist failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrMysql.ErrCode, ErrorMsg: config.ErrMysql.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrMysql.ErrCode, ErrorMsg: constant.ErrMysql.ErrMsg}, nil
}
log.Info(req.Token, req.OperationID, "rpc remove blacklist success return,userid=%s", req.Uid)
return &pbFriend.CommonResp{}, nil

@ -1,26 +1,26 @@
package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
)
func (s *friendServer) SetFriendComment(ctx context.Context, req *pbFriend.SetFriendCommentReq) (*pbFriend.CommonResp, error) {
log.Info(req.Token, req.OperationID, "rpc set friend comment is server,params=%s", req.String())
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
err = im_mysql_model.UpdateFriendComment(claims.UID, req.Uid, req.Comment)
if err != nil {
log.Error(req.Token, req.OperationID, "set friend comment failed,err=%s", err.Error())
return &pbFriend.CommonResp{ErrorCode: config.ErrSetFriendComment.ErrCode, ErrorMsg: config.ErrSetFriendComment.ErrMsg}, nil
return &pbFriend.CommonResp{ErrorCode: constant.ErrSetFriendComment.ErrCode, ErrorMsg: constant.ErrSetFriendComment.ErrMsg}, nil
}
log.Info(req.Token, req.OperationID, "rpc set friend comment is success return")
return &pbFriend.CommonResp{}, nil

@ -8,6 +8,7 @@ import (
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbChat "Open_IM/pkg/proto/chat"
pbGroup "Open_IM/pkg/proto/group"
@ -73,17 +74,17 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
groupId string
)
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.CreateGroupResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.CreateGroupResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
//Time stamp + MD5 to generate group chat id
groupId = utils.Md5(strconv.FormatInt(time.Now().UnixNano(), 10))
err = im_mysql_model.InsertIntoGroup(groupId, req.GroupName, req.Introduction, req.Notification, req.FaceUrl, req.Ex)
if err != nil {
log.ErrorByKv("create group chat failed", req.OperationID, "err=%s", err.Error())
return &pbGroup.CreateGroupResp{ErrorCode: config.ErrCreateGroup.ErrCode, ErrorMsg: config.ErrCreateGroup.ErrMsg}, nil
return &pbGroup.CreateGroupResp{ErrorCode: constant.ErrCreateGroup.ErrCode, ErrorMsg: constant.ErrCreateGroup.ErrMsg}, nil
}
isMagagerFlag := 0
@ -98,18 +99,18 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
us, err := im_mysql_model.FindUserByUID(claims.UID)
if err != nil {
log.Error("", req.OperationID, "find userInfo failed", err.Error())
return &pbGroup.CreateGroupResp{ErrorCode: config.ErrCreateGroup.ErrCode, ErrorMsg: config.ErrCreateGroup.ErrMsg}, nil
return &pbGroup.CreateGroupResp{ErrorCode: constant.ErrCreateGroup.ErrCode, ErrorMsg: constant.ErrCreateGroup.ErrMsg}, nil
}
err = im_mysql_model.InsertIntoGroupMember(groupId, claims.UID, us.Name, us.Icon, constant.GroupOwner)
if err != nil {
log.Error("", req.OperationID, "create group chat failed,err=%s", err.Error())
return &pbGroup.CreateGroupResp{ErrorCode: config.ErrCreateGroup.ErrCode, ErrorMsg: config.ErrCreateGroup.ErrMsg}, nil
return &pbGroup.CreateGroupResp{ErrorCode: constant.ErrCreateGroup.ErrCode, ErrorMsg: constant.ErrCreateGroup.ErrMsg}, nil
}
err = db.DB.AddGroupMember(groupId, claims.UID)
if err != nil {
log.Error("", "", "create mongo group member failed, db.DB.AddGroupMember fail [err: %s]", err.Error())
return &pbGroup.CreateGroupResp{ErrorCode: config.ErrCreateGroup.ErrCode, ErrorMsg: config.ErrCreateGroup.ErrMsg}, nil
return &pbGroup.CreateGroupResp{ErrorCode: constant.ErrCreateGroup.ErrCode, ErrorMsg: constant.ErrCreateGroup.ErrMsg}, nil
}
}

@ -1,21 +1,21 @@
package group
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbGroup "Open_IM/pkg/proto/group"
"Open_IM/pkg/utils"
"context"
)
func (s *groupServer) GetGroupsInfo(ctx context.Context, req *pbGroup.GetGroupsInfoReq) (*pbGroup.GetGroupsInfoResp, error) {
log.Info(req.Token, req.OperationID, "rpc get group info is server,args=%s", req.String())
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.GetGroupsInfoResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.GetGroupsInfoResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
log.Info("", req.OperationID, "args:", req.GroupIDList, claims.UID)
groupsInfoList := make([]*pbGroup.GroupInfo, 0)

@ -6,6 +6,7 @@ import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/token_verify"
pbChat "Open_IM/pkg/proto/chat"
"encoding/json"
@ -19,17 +20,17 @@ import (
)
func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJoinedGroupListReq) (*pbGroup.GetJoinedGroupListResp, error) {
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.GetJoinedGroupListResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.GetJoinedGroupListResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
log.Info(claims.UID, req.OperationID, "recv req: ", req.String())
joinedGroupList, err := imdb.GetJoinedGroupIdListByMemberId(claims.UID)
if err != nil {
log.Error(claims.UID, req.OperationID, "GetJoinedGroupIdListByMemberId failed, err: ", err.Error())
return &pbGroup.GetJoinedGroupListResp{ErrorCode: config.ErrParam.ErrCode, ErrorMsg: config.ErrParam.ErrMsg}, nil
return &pbGroup.GetJoinedGroupListResp{ErrorCode: constant.ErrParam.ErrCode, ErrorMsg: constant.ErrParam.ErrMsg}, nil
}
var resp pbGroup.GetJoinedGroupListResp
@ -57,23 +58,23 @@ func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJo
}
func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.InviteUserToGroupReq) (*pbGroup.InviteUserToGroupResp, error) {
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.InviteUserToGroupResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.InviteUserToGroupResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
log.Info(claims.UID, req.OperationID, "recv req: ", req.String())
// if !imdb.IsExistGroupMember(req.GroupID, claims.UID) && claims.UID != config.Config.AppManagerUid
if !imdb.IsExistGroupMember(req.GroupID, claims.UID) && !utils.IsContain(claims.UID, config.Config.Manager.AppManagerUid) {
log.Error(req.Token, req.OperationID, "err= invite user not in group")
return &pbGroup.InviteUserToGroupResp{ErrorCode: config.ErrAccess.ErrCode, ErrorMsg: config.ErrAccess.ErrMsg}, nil
return &pbGroup.InviteUserToGroupResp{ErrorCode: constant.ErrAccess.ErrCode, ErrorMsg: constant.ErrAccess.ErrMsg}, nil
}
groupInfoFromMysql, err := imdb.FindGroupInfoByGroupId(req.GroupID)
if err != nil || groupInfoFromMysql == nil {
log.NewError(req.OperationID, "get group info error", req.GroupID, req.UidList)
return &pbGroup.InviteUserToGroupResp{ErrorCode: config.ErrAccess.ErrCode, ErrorMsg: config.ErrAccess.ErrMsg}, nil
return &pbGroup.InviteUserToGroupResp{ErrorCode: constant.ErrAccess.ErrCode, ErrorMsg: constant.ErrAccess.ErrMsg}, nil
}
//
@ -175,7 +176,7 @@ func (s *groupServer) GetGroupAllMember(ctx context.Context, req *pbGroup.GetGro
resp.ErrorCode = 0
memberList, err := imdb.FindGroupMemberListByGroupId(req.GroupID)
if err != nil {
resp.ErrorCode = config.ErrDb.ErrCode
resp.ErrorCode = constant.ErrDb.ErrCode
resp.ErrorMsg = err.Error()
log.NewError(req.OperationID, "FindGroupMemberListByGroupId failed,", err.Error(), req.GroupID)
return &resp, nil
@ -196,10 +197,10 @@ func (s *groupServer) GetGroupAllMember(ctx context.Context, req *pbGroup.GetGro
}
func (s *groupServer) GetGroupMemberList(ctx context.Context, req *pbGroup.GetGroupMemberListReq) (*pbGroup.GetGroupMemberListResp, error) {
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.GetGroupMemberListResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.GetGroupMemberListResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
// log.Info(claims.UID, req.OperationID, "recv req: ", req.String())
fmt.Println("req: ", req.GroupID)
@ -207,7 +208,7 @@ func (s *groupServer) GetGroupMemberList(ctx context.Context, req *pbGroup.GetGr
resp.ErrorCode = 0
memberList, err := imdb.GetGroupMemberByGroupId(req.GroupID, req.Filter, req.NextSeq, 30)
if err != nil {
resp.ErrorCode = config.ErrDb.ErrCode
resp.ErrorCode = constant.ErrDb.ErrCode
resp.ErrorMsg = err.Error()
log.Error(claims.UID, req.OperationID, "GetGroupMemberByGroupId failed, ", err.Error(), "params: ", req.GroupID, req.Filter, req.NextSeq)
return &resp, nil
@ -256,17 +257,17 @@ func (c *kickGroupMemberApiReq) ContentToString() string {
}
func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGroupMemberReq) (*pbGroup.KickGroupMemberResp, error) {
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.KickGroupMemberResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.KickGroupMemberResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
log.Info(claims.UID, req.OperationID, "recv req: ", req.String())
ownerList, err := imdb.GetOwnerManagerByGroupId(req.GroupID)
if err != nil {
log.Error(claims.UID, req.OperationID, req.GroupID, "GetOwnerManagerByGroupId, ", err.Error())
return &pbGroup.KickGroupMemberResp{ErrorCode: config.ErrParam.ErrCode, ErrorMsg: config.ErrParam.ErrMsg}, nil
return &pbGroup.KickGroupMemberResp{ErrorCode: constant.ErrParam.ErrCode, ErrorMsg: constant.ErrParam.ErrMsg}, nil
}
//op is group owner?
var flag = 0
@ -285,12 +286,12 @@ func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGrou
if flag != 1 {
log.Error(claims.UID, req.OperationID, "no access kick")
return &pbGroup.KickGroupMemberResp{ErrorCode: config.ErrAccess.ErrCode, ErrorMsg: config.ErrAccess.ErrMsg}, nil
return &pbGroup.KickGroupMemberResp{ErrorCode: constant.ErrAccess.ErrCode, ErrorMsg: constant.ErrAccess.ErrMsg}, nil
}
if len(req.UidListInfo) == 0 {
log.Error(claims.UID, req.OperationID, "kick list 0")
return &pbGroup.KickGroupMemberResp{ErrorCode: config.ErrParam.ErrCode, ErrorMsg: config.ErrParam.ErrMsg}, nil
return &pbGroup.KickGroupMemberResp{ErrorCode: constant.ErrParam.ErrCode, ErrorMsg: constant.ErrParam.ErrMsg}, nil
}
//remove
var resp pbGroup.KickGroupMemberResp
@ -362,10 +363,10 @@ func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGrou
}
func (s *groupServer) GetGroupMembersInfo(ctx context.Context, req *pbGroup.GetGroupMembersInfoReq) (*pbGroup.GetGroupMembersInfoResp, error) {
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.GetGroupMembersInfoResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.GetGroupMembersInfoResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
log.InfoByKv(claims.UID, req.OperationID, "param: ", req.MemberList)
var resp pbGroup.GetGroupMembersInfoResp

@ -1,26 +1,26 @@
package group
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbGroup "Open_IM/pkg/proto/group"
"Open_IM/pkg/utils"
"context"
)
func (s *groupServer) JoinGroup(ctx context.Context, req *pbGroup.JoinGroupReq) (*pbGroup.CommonResp, error) {
log.Info(req.Token, req.OperationID, "rpc join group is server,args=%s", req.String())
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
applicationUserInfo, err := im_mysql_model.FindUserByUID(claims.UID)
if err != nil {
log.Error(req.Token, req.OperationID, "No this user,err=%s", err.Error())
return &pbGroup.CommonResp{ErrorCode: config.ErrSearchUserInfo.ErrCode, ErrorMsg: config.ErrSearchUserInfo.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrSearchUserInfo.ErrCode, ErrorMsg: constant.ErrSearchUserInfo.ErrMsg}, nil
}
_, err = im_mysql_model.FindGroupRequestUserInfoByGroupIDAndUid(req.GroupID, claims.UID)
@ -32,7 +32,7 @@ func (s *groupServer) JoinGroup(ctx context.Context, req *pbGroup.JoinGroupReq)
if err = im_mysql_model.InsertIntoGroupRequest(req.GroupID, claims.UID, "0", req.Message, applicationUserInfo.Name, applicationUserInfo.Icon); err != nil {
log.Error(req.Token, req.OperationID, "Insert into group request failed,er=%s", err.Error())
return &pbGroup.CommonResp{ErrorCode: config.ErrJoinGroupApplication.ErrCode, ErrorMsg: config.ErrJoinGroupApplication.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrJoinGroupApplication.ErrCode, ErrorMsg: constant.ErrJoinGroupApplication.ErrMsg}, nil
}
////Find the the group owner
//groupCreatorInfo, err := im_mysql_model.FindGroupMemberListByGroupIdAndFilterInfo(req.GroupID, constant.GroupCreator)

@ -1,41 +1,41 @@
package group
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbGroup "Open_IM/pkg/proto/group"
"Open_IM/pkg/utils"
"context"
)
func (s *groupServer) QuitGroup(ctx context.Context, req *pbGroup.QuitGroupReq) (*pbGroup.CommonResp, error) {
log.InfoByArgs("rpc quit group is server,args:", req.String())
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
log.InfoByKv("args:", req.OperationID, req.GetGroupID(), claims.UID)
//Check to see whether there is a user in the group.
_, err = im_mysql_model.FindGroupMemberInfoByGroupIdAndUserId(req.GroupID, claims.UID)
if err != nil {
log.Error(req.Token, req.OperationID, "no such group or you are not in the group,err=%s", err.Error(), req.OperationID, req.GroupID, claims.UID)
return &pbGroup.CommonResp{ErrorCode: config.ErrQuitGroup.ErrCode, ErrorMsg: config.ErrQuitGroup.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrQuitGroup.ErrCode, ErrorMsg: constant.ErrQuitGroup.ErrMsg}, nil
}
//After the user's verification is successful, user will quit the group chat.
err = im_mysql_model.DeleteGroupMemberByGroupIdAndUserId(req.GroupID, claims.UID)
if err != nil {
log.ErrorByArgs("this user exit the group failed,err=%s", err.Error(), req.OperationID, req.GroupID, claims.UID)
return &pbGroup.CommonResp{ErrorCode: config.ErrQuitGroup.ErrCode, ErrorMsg: config.ErrQuitGroup.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrQuitGroup.ErrCode, ErrorMsg: constant.ErrQuitGroup.ErrMsg}, nil
}
err = db.DB.DelGroupMember(req.GroupID, claims.UID)
if err != nil {
log.Error("", "", "delete mongo group member failed, db.DB.DelGroupMember fail [err: %s]", err.Error())
return &pbGroup.CommonResp{ErrorCode: config.ErrQuitGroup.ErrCode, ErrorMsg: config.ErrQuitGroup.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrQuitGroup.ErrCode, ErrorMsg: constant.ErrQuitGroup.ErrMsg}, nil
}
////Push message when quit group chat
//jsonInfo, _ := json.Marshal(req)

@ -1,12 +1,11 @@
package group
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbGroup "Open_IM/pkg/proto/group"
"Open_IM/pkg/utils"
"context"
)
@ -14,22 +13,22 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
log.Info(req.Token, req.OperationID, "rpc set group info is server,args=%s", req.String())
//Parse token, to find current user information
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbGroup.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: config.ErrParseToken.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: constant.ErrParseToken.ErrMsg}, nil
}
groupUserInfo, err := im_mysql_model.FindGroupMemberInfoByGroupIdAndUserId(req.GroupID, claims.UID)
if err != nil {
log.Error("", req.OperationID, "your are not in the group,can not change this group info,err=%s", err.Error())
return &pbGroup.CommonResp{ErrorCode: config.ErrSetGroupInfo.ErrCode, ErrorMsg: config.ErrSetGroupInfo.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrSetGroupInfo.ErrCode, ErrorMsg: constant.ErrSetGroupInfo.ErrMsg}, nil
}
if groupUserInfo.AdministratorLevel == constant.OrdinaryMember {
return &pbGroup.CommonResp{ErrorCode: config.ErrSetGroupInfo.ErrCode, ErrorMsg: config.ErrAccess.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrSetGroupInfo.ErrCode, ErrorMsg: constant.ErrAccess.ErrMsg}, nil
}
//only administrators can set group information
if err = im_mysql_model.SetGroupInfo(req.GroupID, req.GroupName, req.Introduction, req.Notification, req.FaceUrl, ""); err != nil {
return &pbGroup.CommonResp{ErrorCode: config.ErrSetGroupInfo.ErrCode, ErrorMsg: config.ErrSetGroupInfo.ErrMsg}, nil
return &pbGroup.CommonResp{ErrorCode: constant.ErrSetGroupInfo.ErrCode, ErrorMsg: constant.ErrSetGroupInfo.ErrMsg}, nil
}
////Push message when set group info
//jsonInfo, _ := json.Marshal(req)

@ -8,8 +8,10 @@ package user
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
@ -19,10 +21,10 @@ func (s *userServer) DeleteUsers(_ context.Context, req *pbUser.DeleteUsersReq)
log.InfoByKv("rpc DeleteUsers arrived server", req.OperationID, "args", req.String())
var resp pbUser.DeleteUsersResp
var common pbUser.CommonResp
c, err := utils.ParseToken(req.Token)
c, err := token_verify.ParseToken(req.Token)
if err != nil {
log.ErrorByKv("parse token failed", req.OperationID, "err", err.Error())
return &pbUser.DeleteUsersResp{CommonResp: &pbUser.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: err.Error()}, FailedUidList: req.DeleteUidList}, nil
return &pbUser.DeleteUsersResp{CommonResp: &pbUser.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: err.Error()}, FailedUidList: req.DeleteUidList}, nil
}
if !utils.IsContain(c.UID, config.Config.Manager.AppManagerUid) {
log.ErrorByKv(" Authentication failed", req.OperationID, "args", c)
@ -43,10 +45,10 @@ func (s *userServer) DeleteUsers(_ context.Context, req *pbUser.DeleteUsersReq)
func (s *userServer) GetAllUsersUid(_ context.Context, req *pbUser.GetAllUsersUidReq) (*pbUser.GetAllUsersUidResp, error) {
log.InfoByKv("rpc GetAllUsersUid arrived server", req.OperationID, "args", req.String())
c, err := utils.ParseToken(req.Token)
c, err := token_verify.ParseToken(req.Token)
if err != nil {
log.InfoByKv("parse token failed", req.OperationID, "err", err.Error())
return &pbUser.GetAllUsersUidResp{CommonResp: &pbUser.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: err.Error()}}, nil
return &pbUser.GetAllUsersUidResp{CommonResp: &pbUser.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: err.Error()}}, nil
}
if !utils.IsContain(c.UID, config.Config.Manager.AppManagerUid) {
log.ErrorByKv(" Authentication failed", req.OperationID, "args", c)
@ -55,7 +57,7 @@ func (s *userServer) GetAllUsersUid(_ context.Context, req *pbUser.GetAllUsersUi
uidList, err := im_mysql_model.SelectAllUID()
if err != nil {
log.ErrorByKv("db get failed", req.OperationID, "err", err.Error())
return &pbUser.GetAllUsersUidResp{CommonResp: &pbUser.CommonResp{ErrorCode: config.ErrMysql.ErrCode, ErrorMsg: err.Error()}}, nil
return &pbUser.GetAllUsersUidResp{CommonResp: &pbUser.CommonResp{ErrorCode: constant.ErrMysql.ErrCode, ErrorMsg: err.Error()}}, nil
} else {
return &pbUser.GetAllUsersUidResp{CommonResp: &pbUser.CommonResp{ErrorCode: 0, ErrorMsg: ""}, UidList: uidList}, nil
}

@ -6,6 +6,7 @@ import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbChat "Open_IM/pkg/proto/chat"
pbFriend "Open_IM/pkg/proto/friend"
@ -17,10 +18,10 @@ import (
func (s *userServer) UpdateUserInfo(ctx context.Context, req *pbUser.UpdateUserInfoReq) (*pbUser.CommonResp, error) {
log.Info(req.Token, req.OperationID, "rpc modify user is server,args=%s", req.String())
claims, err := utils.ParseToken(req.Token)
claims, err := token_verify.ParseToken(req.Token)
if err != nil {
log.Error(req.Token, req.OperationID, "err=%s,parse token failed", err.Error())
return &pbUser.CommonResp{ErrorCode: config.ErrParseToken.ErrCode, ErrorMsg: err.Error()}, nil
return &pbUser.CommonResp{ErrorCode: constant.ErrParseToken.ErrCode, ErrorMsg: err.Error()}, nil
}
ownerUid := ""
@ -34,7 +35,7 @@ func (s *userServer) UpdateUserInfo(ctx context.Context, req *pbUser.UpdateUserI
err = im_mysql_model.UpDateUserInfo(ownerUid, req.Name, req.Icon, req.Mobile, req.Birth, req.Email, req.Ex, req.Gender)
if err != nil {
log.Error(req.Token, req.OperationID, "update user some attribute failed,err=%s", err.Error())
return &pbUser.CommonResp{ErrorCode: config.ErrModifyUserInfo.ErrCode, ErrorMsg: config.ErrModifyUserInfo.ErrMsg}, nil
return &pbUser.CommonResp{ErrorCode: constant.ErrModifyUserInfo.ErrCode, ErrorMsg: constant.ErrModifyUserInfo.ErrMsg}, nil
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
client := pbFriend.NewFriendClient(etcdConn)

@ -2,7 +2,8 @@ package utils
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/utils"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/token_verify"
"testing"
"time"
@ -13,7 +14,7 @@ func Test_BuildClaims(t *testing.T) {
uid := "1"
platform := "PC"
ttl := int64(-1)
claim := utils.BuildClaims(uid, platform, ttl)
claim := token_verify.BuildClaims(uid, platform, ttl)
now := time.Now().Unix()
assert.Equal(t, claim.UID, uid, "uid should equal")
@ -25,7 +26,7 @@ func Test_BuildClaims(t *testing.T) {
ttl = int64(60)
now = time.Now().Unix()
claim = utils.BuildClaims(uid, platform, ttl)
claim = token_verify.BuildClaims(uid, platform, ttl)
// time difference within 1s
assert.Equal(t, claim.RegisteredClaims.ExpiresAt, int64(60)+now, "StandardClaims.ExpiresAt should be equal")
assert.Equal(t, claim.RegisteredClaims.IssuedAt, now, "StandardClaims.IssuedAt should be equal")
@ -37,7 +38,7 @@ func Test_CreateToken(t *testing.T) {
platform := int32(1)
now := time.Now().Unix()
tokenString, expiresAt, err := utils.CreateToken(uid, platform)
tokenString, expiresAt, err := token_verify.CreateToken(uid, platform)
assert.NotEmpty(t, tokenString)
assert.Equal(t, expiresAt, 604800+now)
@ -47,35 +48,35 @@ func Test_CreateToken(t *testing.T) {
func Test_VerifyToken(t *testing.T) {
uid := "1"
platform := int32(1)
tokenString, _, _ := utils.CreateToken(uid, platform)
result := utils.VerifyToken(tokenString, uid)
tokenString, _, _ := token_verify.CreateToken(uid, platform)
result, _ := token_verify.VerifyToken(tokenString, uid)
assert.True(t, result)
result = utils.VerifyToken(tokenString, "2")
result, _ = token_verify.VerifyToken(tokenString, "2")
assert.False(t, result)
}
func Test_ParseRedisInterfaceToken(t *testing.T) {
uid := "1"
platform := int32(1)
tokenString, _, _ := utils.CreateToken(uid, platform)
tokenString, _, _ := token_verify.CreateToken(uid, platform)
claims, err := utils.ParseRedisInterfaceToken([]uint8(tokenString))
claims, err := token_verify.ParseRedisInterfaceToken([]uint8(tokenString))
assert.Nil(t, err)
assert.Equal(t, claims.UID, uid)
// timeout
config.Config.TokenPolicy.AccessExpire = -80
tokenString, _, _ = utils.CreateToken(uid, platform)
claims, err = utils.ParseRedisInterfaceToken([]uint8(tokenString))
assert.Equal(t, err, utils.TokenExpired)
tokenString, _, _ = token_verify.CreateToken(uid, platform)
claims, err = token_verify.ParseRedisInterfaceToken([]uint8(tokenString))
assert.Equal(t, err, constant.TokenExpired)
assert.Nil(t, claims)
}
func Test_ParseToken(t *testing.T) {
uid := "1"
platform := int32(1)
tokenString, _, _ := utils.CreateToken(uid, platform)
claims, err := utils.ParseToken(tokenString)
tokenString, _, _ := token_verify.CreateToken(uid, platform)
claims, err := token_verify.ParseToken(tokenString)
if err == nil {
assert.Equal(t, claims.UID, uid)
}

@ -1,46 +1,46 @@
package utils
import (
"Open_IM/pkg/utils"
"Open_IM/pkg/common/constant"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_PlatformIDToName(t *testing.T) {
assert.Equal(t, utils.PlatformIDToName(1), "IOS")
assert.Equal(t, utils.PlatformIDToName(2), "Android")
assert.Equal(t, utils.PlatformIDToName(3), "Windows")
assert.Equal(t, utils.PlatformIDToName(4), "OSX")
assert.Equal(t, utils.PlatformIDToName(5), "Web")
assert.Equal(t, utils.PlatformIDToName(6), "MiniWeb")
assert.Equal(t, utils.PlatformIDToName(7), "Linux")
assert.Equal(t, utils.PlatformIDToName(0), "")
assert.Equal(t, constant.PlatformIDToName(1), "IOS")
assert.Equal(t, constant.PlatformIDToName(2), "Android")
assert.Equal(t, constant.PlatformIDToName(3), "Windows")
assert.Equal(t, constant.PlatformIDToName(4), "OSX")
assert.Equal(t, constant.PlatformIDToName(5), "Web")
assert.Equal(t, constant.PlatformIDToName(6), "MiniWeb")
assert.Equal(t, constant.PlatformIDToName(7), "Linux")
assert.Equal(t, constant.PlatformIDToName(0), "")
}
func Test_PlatformNameToID(t *testing.T) {
assert.Equal(t, utils.PlatformNameToID("IOS"), int32(1))
assert.Equal(t, utils.PlatformNameToID("Android"), int32(2))
assert.Equal(t, utils.PlatformNameToID("Windows"), int32(3))
assert.Equal(t, utils.PlatformNameToID("OSX"), int32(4))
assert.Equal(t, utils.PlatformNameToID("Web"), int32(5))
assert.Equal(t, utils.PlatformNameToID("MiniWeb"), int32(6))
assert.Equal(t, utils.PlatformNameToID("Linux"), int32(7))
assert.Equal(t, utils.PlatformNameToID("UnknownDevice"), int32(0))
assert.Equal(t, utils.PlatformNameToID(""), int32(0))
assert.Equal(t, constant.PlatformNameToID("IOS"), int32(1))
assert.Equal(t, constant.PlatformNameToID("Android"), int32(2))
assert.Equal(t, constant.PlatformNameToID("Windows"), int32(3))
assert.Equal(t, constant.PlatformNameToID("OSX"), int32(4))
assert.Equal(t, constant.PlatformNameToID("Web"), int32(5))
assert.Equal(t, constant.PlatformNameToID("MiniWeb"), int32(6))
assert.Equal(t, constant.PlatformNameToID("Linux"), int32(7))
assert.Equal(t, constant.PlatformNameToID("UnknownDevice"), int32(0))
assert.Equal(t, constant.PlatformNameToID(""), int32(0))
}
func Test_PlatformNameToClass(t *testing.T) {
assert.Equal(t, utils.PlatformNameToClass("IOS"), "Mobile")
assert.Equal(t, utils.PlatformNameToClass("Android"), "Mobile")
assert.Equal(t, utils.PlatformNameToClass("OSX"), "PC")
assert.Equal(t, utils.PlatformNameToClass("Windows"), "PC")
assert.Equal(t, utils.PlatformNameToClass("Web"), "PC")
assert.Equal(t, utils.PlatformNameToClass("MiniWeb"), "Mobile")
assert.Equal(t, utils.PlatformNameToClass("Linux"), "PC")
assert.Equal(t, utils.PlatformNameToClass("UnknownDevice"), "")
assert.Equal(t, utils.PlatformNameToClass(""), "")
assert.Equal(t, constant.PlatformNameToClass("IOS"), "Mobile")
assert.Equal(t, constant.PlatformNameToClass("Android"), "Mobile")
assert.Equal(t, constant.PlatformNameToClass("OSX"), "PC")
assert.Equal(t, constant.PlatformNameToClass("Windows"), "PC")
assert.Equal(t, constant.PlatformNameToClass("Web"), "PC")
assert.Equal(t, constant.PlatformNameToClass("MiniWeb"), "Mobile")
assert.Equal(t, constant.PlatformNameToClass("Linux"), "PC")
assert.Equal(t, constant.PlatformNameToClass("UnknownDevice"), "")
assert.Equal(t, constant.PlatformNameToClass(""), "")
}

@ -145,12 +145,8 @@ type config struct {
}
}
Secret string `yaml:"secret"`
MultiLoginPolicy struct {
OnlyOneTerminalAccess bool `yaml:"onlyOneTerminalAccess"`
MobileAndPCTerminalAccessButOtherTerminalKickEachOther bool `yaml:"mobileAndPCTerminalAccessButOtherTerminalKickEachOther"`
AllTerminalAccess bool `yaml:"allTerminalAccess"`
}
TokenPolicy struct {
MultiLoginPolicy int `yaml:"multiloginpolicy"`
TokenPolicy struct {
AccessSecret string `yaml:"accessSecret"`
AccessExpire int64 `yaml:"accessExpire"`
}

@ -22,6 +22,7 @@ const (
WSSendMsg = 1003
WSPullMsgBySeqList = 1004
WSPushMsg = 2001
WSKickOnlineMsg = 2002
WSDataError = 3001
///ContentType
@ -70,6 +71,21 @@ const (
//SessionType
SingleChatType = 1
GroupChatType = 2
//token
NormalToken = 0
InValidToken = 1
KickedToken = 2
ExpiredToken = 3
//MultiTerminalLogin
//全端登录,但是同端互斥
AllLoginButSameTermKick = 1
//所有端中只能有一端能够登录
SingleTerminalLogin = 2
//web端可以同时在线其他端只能有一端登录
WebAndOther = 3
//Pc端互斥移动端互斥但是web端可以同时在线
PcMobileAndWeb = 4
)
var ContentType2PushContent = map[int64]string{

@ -1,4 +1,6 @@
package config
package constant
import "errors"
// key = errCode, string = errMsg
type ErrInfo struct {
@ -20,8 +22,6 @@ var (
ErrorUserRegister = ErrInfo{600, "User registration failed"}
ErrAccountExists = ErrInfo{601, "The account is already registered and cannot be registered again"}
ErrUserPassword = ErrInfo{602, "User password error"}
ErrTokenIncorrect = ErrInfo{603, "Invalid token"}
ErrTokenExpired = ErrInfo{604, "Expired token"}
ErrRefreshToken = ErrInfo{605, "Failed to refresh token"}
ErrAddFriend = ErrInfo{606, "Failed to add friends"}
ErrAgreeToAddFriend = ErrInfo{607, "Failed to agree application"}
@ -40,9 +40,26 @@ var (
ErrJoinGroupApplication = ErrInfo{620, "Failed to apply to join the group"}
ErrQuitGroup = ErrInfo{621, "Failed to quit the group"}
ErrSetGroupInfo = ErrInfo{622, "Failed to set group info"}
ErrParam = ErrInfo{ErrCode: 700, ErrMsg: "param failed"}
ErrParam = ErrInfo{700, "param failed"}
ErrTokenExpired = ErrInfo{701, TokenExpired.Error()}
ErrTokenInvalid = ErrInfo{702, TokenInvalid.Error()}
ErrTokenMalformed = ErrInfo{703, TokenMalformed.Error()}
ErrTokenNotValidYet = ErrInfo{704, TokenNotValidYet.Error()}
ErrTokenUnknown = ErrInfo{705, TokenUnknown.Error()}
ErrAccess = ErrInfo{ErrCode: 800, ErrMsg: "no permission"}
ErrDb = ErrInfo{ErrCode: 900, ErrMsg: "db failed"}
)
var (
TokenExpired = errors.New("token is timed out, please log in again")
TokenInvalid = errors.New("token has been invalidated")
TokenNotValidYet = errors.New("token not active yet")
TokenMalformed = errors.New("that's not even a token")
TokenUnknown = errors.New("couldn't handle this token")
)
func (e *ErrInfo) Error() string {
return e.ErrMsg
}

@ -1,4 +1,4 @@
package utils
package constant
// fixme 1<--->IOS 2<--->Android 3<--->Windows
//fixme 4<--->OSX 5<--->Web 6<--->MiniWeb 7<--->Linux
@ -48,10 +48,10 @@ var PlatformName2ID = map[string]int32{
var Platform2class = map[string]string{
IOSPlatformStr: TerminalMobile,
AndroidPlatformStr: TerminalMobile,
MiniWebPlatformStr: TerminalMobile,
MiniWebPlatformStr: WebPlatformStr,
WebPlatformStr: WebPlatformStr,
WindowsPlatformStr: TerminalPC,
OSXPlatformStr: TerminalPC,
WebPlatformStr: TerminalPC,
LinuxPlatformStr: TerminalPC,
}

@ -2,6 +2,7 @@ package db
import (
log2 "Open_IM/pkg/common/log"
"Open_IM/pkg/utils"
"github.com/garyburd/redigo/redis"
)
@ -10,6 +11,7 @@ const (
appleDeviceToken = "DEVICE_TOKEN"
lastGetSeq = "LAST_GET_SEQ"
userMinSeq = "REDIS_USER_MIN_SEQ:"
uidPidToken = "UID_PID_TOKEN:"
)
func (d *DataBases) Exec(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
@ -71,36 +73,39 @@ func (d *DataBases) DelAppleDeviceToken(accountAddress string) (err error) {
return err
}
//Record the last time the user actively pulled the value of Seq
func (d *DataBases) SetLastGetSeq(uid string) (err error) {
key := lastGetSeq + uid
_, err = d.Exec("SET", key)
return err
//Store userid and platform class to redis
func (d *DataBases) AddTokenFlag(userID string, platformID int32, token string, flag int) error {
key := uidPidToken + userID + ":" + utils.Int32ToString(platformID)
m, err := redis.IntMap(d.Exec("GET", key))
if err != nil && err != redis.ErrNil {
return err
}
if err == redis.ErrNil {
m = make(map[string]int, 5)
}
m[token] = flag
_, err1 := d.Exec("SET", key, m)
return err1
}
//Get the value of the user's last active pull Seq
func (d *DataBases) GetLastGetSeq(uid string) (int64, error) {
key := lastGetSeq + uid
return redis.Int64(d.Exec("GET", key))
func (d *DataBases) GetTokenMapByUidPid(userID, platformID string) (map[string]int, error) {
key := uidPidToken + userID + ":" + platformID
return redis.IntMap(d.Exec("GET", key))
}
//Store userid and platform class to redis
func (d *DataBases) SetUserIDAndPlatform(userID, platformClass, value string, ttl int64) error {
key := userID + platformClass
_, err := d.Exec("SET", key, value, "EX", ttl)
func (d *DataBases) SetTokenMapByUidPid(userID, platformID string, m map[string]int) error {
key := uidPidToken + userID + ":" + platformID
_, err := d.Exec("SET", key, m)
return err
}
//Check exists userid and platform class from redis
func (d *DataBases) ExistsUserIDAndPlatform(userID, platformClass string) (interface{}, error) {
func (d *DataBases) ExistsUserIDAndPlatform(userID, platformClass string) (int64, error) {
key := userID + platformClass
exists, err := d.Exec("EXISTS", key)
return exists, err
return redis.Int64(d.Exec("EXISTS", key))
}
//Get platform class Token
func (d *DataBases) GetPlatformToken(userID, platformClass string) (interface{}, error) {
func (d *DataBases) GetPlatformToken(userID, platformClass string) (string, error) {
key := userID + platformClass
token, err := d.Exec("GET", key)
return token, err
return redis.String(d.Exec("GET", key))
}

@ -1,73 +1,73 @@
package multi_terminal_login
import (
"Open_IM/internal/push/content_struct"
"Open_IM/internal/push/logic"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
pbChat "Open_IM/pkg/proto/chat"
"Open_IM/pkg/utils"
)
func MultiTerminalLoginChecker(uid, token string, platformID int32) error {
// 1.check userid and platform class 0 not exists and 1 exists
existsInterface, err := db.DB.ExistsUserIDAndPlatform(uid, utils.PlatformNameToClass(utils.PlatformIDToName(platformID)))
if err != nil {
return err
}
exists := existsInterface.(int64)
//get config multi login policy
if config.Config.MultiLoginPolicy.OnlyOneTerminalAccess {
//OnlyOneTerminalAccess policy need to check all terminal
if utils.PlatformNameToClass(utils.PlatformIDToName(platformID)) == "PC" {
existsInterface, err = db.DB.ExistsUserIDAndPlatform(uid, "Mobile")
if err != nil {
return err
}
} else {
existsInterface, err = db.DB.ExistsUserIDAndPlatform(uid, "PC")
if err != nil {
return err
}
}
exists = existsInterface.(int64)
if exists == 1 {
err := db.DB.SetUserIDAndPlatform(uid, utils.PlatformNameToClass(utils.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire)
if err != nil {
return err
}
PushMessageToTheTerminal(uid, platformID)
return nil
}
} else if config.Config.MultiLoginPolicy.MobileAndPCTerminalAccessButOtherTerminalKickEachOther {
// common terminal need to kick eich other
if exists == 1 {
err := db.DB.SetUserIDAndPlatform(uid, utils.PlatformNameToClass(utils.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire)
if err != nil {
return err
}
PushMessageToTheTerminal(uid, platformID)
return nil
}
}
err = db.DB.SetUserIDAndPlatform(uid, utils.PlatformNameToClass(utils.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire)
if err != nil {
return err
}
PushMessageToTheTerminal(uid, platformID)
return nil
}
func PushMessageToTheTerminal(uid string, platform int32) {
logic.SendMsgByWS(&pbChat.WSToMsgSvrChatMsg{
SendID: uid,
RecvID: uid,
Content: content_struct.NewContentStructString(1, "", "Your account is already logged on other terminal,please confirm"),
SendTime: utils.GetCurrentTimestampBySecond(),
MsgFrom: constant.SysMsgType,
ContentType: constant.KickOnlineTip,
PlatformID: platform,
})
}
//
//import (
// "Open_IM/internal/push/content_struct"
// "Open_IM/internal/push/logic"
// "Open_IM/pkg/common/config"
// "Open_IM/pkg/common/constant"
// "Open_IM/pkg/common/db"
// pbChat "Open_IM/pkg/proto/chat"
// "Open_IM/pkg/utils"
//)
//
//const DayOfSecond = 24*60*60
//func MultiTerminalLoginChecker(uid, token string, platformID int32) error {
// // 1.check userid and platform class 0 not exists and 1 exists
// exists, err := db.DB.ExistsUserIDAndPlatform(uid, constant.PlatformNameToClass(constant.PlatformIDToName(platformID)))
// if err != nil {
// return err
// }
// //get config multi login policy
// if config.Config.MultiLoginPolicy {
// //OnlyOneTerminalAccess policy need to check all terminal
// if constant.PlatformNameToClass(constant.PlatformIDToName(platformID)) == "PC" {
// exists, err = db.DB.ExistsUserIDAndPlatform(uid, "Mobile")
// if err != nil {
// return err
// }
// } else {
// exists, err = db.DB.ExistsUserIDAndPlatform(uid, "PC")
// if err != nil {
// return err
// }
// }
// if exists == 1 {
// err := db.DB.SetUserIDAndPlatform(uid, constant.PlatformNameToClass(constant.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire*DayOfSecond)
// if err != nil {
// return err
// }
// PushMessageToTheTerminal(uid, platformID)
// return nil
// }
// } else if config.Config.MultiLoginPolicy.MobileAndPCTerminalAccessButOtherTerminalKickEachOther {
// // common terminal need to kick eich other
// if exists == 1 {
// err := db.DB.SetUserIDAndPlatform(uid, constant.PlatformNameToClass(constant.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire*DayOfSecond)
// if err != nil {
// return err
// }
// PushMessageToTheTerminal(uid, platformID)
// return nil
// }
// }
// err = db.DB.SetUserIDAndPlatform(uid, constant.PlatformNameToClass(constant.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire*DayOfSecond)
// if err != nil {
// return err
// }
// PushMessageToTheTerminal(uid, platformID)
// return nil
//}
////
////func PushMessageToTheTerminal(uid string, platform int32) {
////
//// logic.SendMsgByWS(&pbChat.WSToMsgSvrChatMsg{
//// SendID: uid,
//// RecvID: uid,
//// Content: content_struct.NewContentStructString(1, "", "Your account is already logged on other terminal,please confirm"),
//// SendTime: utils.GetCurrentTimestampBySecond(),
//// MsgFrom: constant.SysMsgType,
//// ContentType: constant.KickOnlineTip,
//// PlatformID: platform,
//// })
////}

@ -0,0 +1,144 @@
package token_verify
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
commonDB "Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
"github.com/golang-jwt/jwt/v4"
"time"
)
//var (
// TokenExpired = errors.New("token is timed out, please log in again")
// TokenInvalid = errors.New("token has been invalidated")
// TokenNotValidYet = errors.New("token not active yet")
// TokenMalformed = errors.New("that's not even a token")
// TokenUnknown = errors.New("couldn't handle this token")
//)
type Claims struct {
UID string
Platform string //login platform
jwt.RegisteredClaims
}
func BuildClaims(uid, platform string, ttl int64) Claims {
now := time.Now()
return Claims{
UID: uid,
Platform: platform,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(ttl*24) * time.Hour)), //Expiration time
IssuedAt: jwt.NewNumericDate(now), //Issuing time
NotBefore: jwt.NewNumericDate(now), //Begin Effective time
}}
}
func CreateToken(userID string, platformID int32) (string, int64, error) {
claims := BuildClaims(userID, constant.PlatformIDToName(platformID), config.Config.TokenPolicy.AccessExpire)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(config.Config.TokenPolicy.AccessSecret))
if err != nil {
return "", 0, err
}
err = commonDB.DB.AddTokenFlag(userID, platformID, tokenString, constant.NormalToken)
if err != nil {
return "", 0, err
}
return tokenString, claims.ExpiresAt.Time.Unix(), err
}
func secret() jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
return []byte(config.Config.TokenPolicy.AccessSecret), nil
}
}
func getClaimFromToken(tokensString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokensString, &Claims{}, secret())
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, &constant.ErrTokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
return nil, &constant.ErrTokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, &constant.ErrTokenNotValidYet
} else {
return nil, &constant.ErrTokenUnknown
}
} else {
return nil, &constant.ErrTokenNotValidYet
}
} else {
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
return claims, nil
}
return nil, &constant.ErrTokenNotValidYet
}
}
func ParseToken(tokensString string) (claims *Claims, err error) {
//根据token的算法本身做出的有效性检验
claims, err = getClaimFromToken(tokensString)
if err != nil {
log.NewError("", "token validate err", err.Error())
return nil, err
}
//根据redis做出的有效性检验
m, err := commonDB.DB.GetTokenMapByUidPid(claims.UID, claims.Platform)
if err != nil {
log.NewError("", "get token from redis err", err.Error())
return nil, &constant.ErrTokenInvalid
}
if m == nil {
log.NewError("", "get token from redis err", "m is nil")
return nil, &constant.ErrTokenInvalid
}
if v, ok := m[tokensString]; ok {
switch v {
case constant.NormalToken:
return claims, nil
case constant.InValidToken:
return nil, &constant.ErrTokenInvalid
case constant.KickedToken:
return nil, &constant.ErrTokenInvalid
case constant.ExpiredToken:
return nil, &constant.ErrTokenExpired
}
}
return nil, err
}
//func MakeTheTokenInvalid(currentClaims *Claims, platformClass string) (bool, error) {
// storedRedisTokenInterface, err := db.DB.GetPlatformToken(currentClaims.UID, platformClass)
// if err != nil {
// return false, err
// }
// storedRedisPlatformClaims, err := ParseRedisInterfaceToken(storedRedisTokenInterface)
// if err != nil {
// return false, err
// }
// //if issue time less than redis token then make this token invalid
// if currentClaims.IssuedAt.Time.Unix() < storedRedisPlatformClaims.IssuedAt.Time.Unix() {
// return true, constant.TokenInvalid
// }
// return false, nil
//}
func ParseRedisInterfaceToken(redisToken interface{}) (*Claims, error) {
return getClaimFromToken(string(redisToken.([]uint8)))
}
//Validation token, false means failure, true means successful verification
func VerifyToken(token, uid string) (bool, error) {
claims, err := ParseToken(token)
if err != nil {
return false, err
}
if claims.UID != uid {
return false, &constant.ErrTokenUnknown
}
return true, nil
}

@ -1,153 +0,0 @@
package utils
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/db"
"errors"
"github.com/golang-jwt/jwt/v4"
"time"
)
var (
TokenExpired = errors.New("token is timed out, please log in again")
TokenInvalid = errors.New("token has been invalidated")
TokenNotValidYet = errors.New("token not active yet")
TokenMalformed = errors.New("that's not even a token")
TokenUnknown = errors.New("couldn't handle this token")
)
type Claims struct {
UID string
Platform string //login platform
jwt.RegisteredClaims
}
func BuildClaims(uid, platform string, ttl int64) Claims {
now := time.Now()
return Claims{
UID: uid,
Platform: platform,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(ttl*24) * time.Hour)), //Expiration time
IssuedAt: jwt.NewNumericDate(now), //Issuing time
NotBefore: jwt.NewNumericDate(now), //Begin Effective time
}}
}
func CreateToken(userID string, platform int32) (string, int64, error) {
claims := BuildClaims(userID, PlatformIDToName(platform), config.Config.TokenPolicy.AccessExpire)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(config.Config.TokenPolicy.AccessSecret))
return tokenString, claims.ExpiresAt.Time.Unix(), err
}
func secret() jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
return []byte(config.Config.TokenPolicy.AccessSecret), nil
}
}
func getClaimFromToken(tokensString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokensString, &Claims{}, secret())
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, TokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
return nil, TokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, TokenNotValidYet
} else {
return nil, TokenUnknown
}
}
}
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
return claims, nil
}
return nil, err
}
func ParseToken(tokensString string) (claims *Claims, err error) {
claims, err = getClaimFromToken(tokensString)
if err != nil {
return nil, err
}
// 1.check userid and platform class 0 not exists and 1 exists
existsInterface, err := db.DB.ExistsUserIDAndPlatform(claims.UID, Platform2class[claims.Platform])
if err != nil {
return nil, err
}
exists := existsInterface.(int64)
//get config multi login policy
if config.Config.MultiLoginPolicy.OnlyOneTerminalAccess {
//OnlyOneTerminalAccess policy need to check all terminal
//When only one end is allowed to log in, there is a situation that needs to be paid attention to. After PC login,
//mobile login should check two platform times. One of them is less than the redis storage time, which is the invalid token.
platform := "PC"
if Platform2class[claims.Platform] == "PC" {
platform = "Mobile"
}
existsInterface, err = db.DB.ExistsUserIDAndPlatform(claims.UID, platform)
if err != nil {
return nil, err
}
exists = existsInterface.(int64)
if exists == 1 {
res, err := MakeTheTokenInvalid(claims, platform)
if err != nil {
return nil, err
}
if res {
return nil, TokenInvalid
}
}
}
// config.Config.MultiLoginPolicy.MobileAndPCTerminalAccessButOtherTerminalKickEachOther == true
// or PC/Mobile validate success
// final check
if exists == 1 {
res, err := MakeTheTokenInvalid(claims, Platform2class[claims.Platform])
if err != nil {
return nil, err
}
if res {
return nil, TokenInvalid
}
}
return claims, nil
}
func MakeTheTokenInvalid(currentClaims *Claims, platformClass string) (bool, error) {
storedRedisTokenInterface, err := db.DB.GetPlatformToken(currentClaims.UID, platformClass)
if err != nil {
return false, err
}
storedRedisPlatformClaims, err := ParseRedisInterfaceToken(storedRedisTokenInterface)
if err != nil {
return false, err
}
//if issue time less than redis token then make this token invalid
if currentClaims.IssuedAt.Time.Unix() < storedRedisPlatformClaims.IssuedAt.Time.Unix() {
return true, TokenInvalid
}
return false, nil
}
func ParseRedisInterfaceToken(redisToken interface{}) (*Claims, error) {
return getClaimFromToken(string(redisToken.([]uint8)))
}
//Validation token, false means failure, true means successful verification
func VerifyToken(token, uid string) bool {
claims, err := ParseToken(token)
if err != nil || claims.UID != uid {
return false
}
return true
}

@ -24,6 +24,9 @@ func StringToInt64(i string) int64 {
j, _ := strconv.ParseInt(i, 10, 64)
return j
}
func Int32ToString(i int32) string {
return strconv.FormatInt(int64(i), 10)
}
//judge a string whether in the string list
func IsContain(target string, List []string) bool {

Loading…
Cancel
Save