Skip to content

Commit

Permalink
token (#59)
Browse files Browse the repository at this point in the history
* fix/searchUserInfo

Signed-off-by: hanzhixiao <[email protected]>

* fix search normal user

Signed-off-by: hanzhixiao <[email protected]>

* feat token

Signed-off-by: hanzhixiao <[email protected]>

---------

Signed-off-by: hanzhixiao <[email protected]>
  • Loading branch information
hanzhixiao committed Jul 27, 2023
1 parent 165a726 commit 875665e
Show file tree
Hide file tree
Showing 22 changed files with 844 additions and 428 deletions.
9 changes: 7 additions & 2 deletions config/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ log:
# isJson: false
# withStack: false

#secret: "openIM123"
secret: openIM123
#tokenPolicy:
# expire: 86400

Expand Down Expand Up @@ -96,4 +96,9 @@ adminList:
imAdmin: openIMAdmin


openIMUrl: "http://127.0.0.1:10002"
openIMUrl: "http://127.0.0.1:10002"

redis:
address: [ 127.0.0.1:16379 ]
username:
password: openIM123
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ require (
require (
github.com/OpenIMSDK/protocol v0.0.1
github.com/OpenIMSDK/tools v0.0.5
github.com/redis/go-redis/v9 v9.0.5
)

require (
Expand All @@ -41,8 +42,10 @@ require (
github.com/aliyun/credentials-go v1.1.2 // indirect
github.com/bwmarrin/snowflake v0.3.0 // indirect
github.com/bytedance/sonic v1.9.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/clbanning/mxj/v2 v2.5.6 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
Expand Down
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,15 @@ github.com/alibabacloud-go/tea-xml v1.1.2/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCE
github.com/aliyun/credentials-go v1.1.2 h1:qU1vwGIBb3UJ8BwunHDRFtAhS6jnQLnde/yk0+Ih2GY=
github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw=
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/bsm/ginkgo/v2 v2.7.0 h1:ItPMPH90RbmZJt5GtkcNvIRuGEdwlBItdNVoyzaNQao=
github.com/bsm/gomega v1.26.0 h1:LhQm+AFcgV2M0WyKroMASzAzCAJVpAxQXv4SaI9a69Y=
github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE=
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
Expand All @@ -50,6 +54,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
Expand Down Expand Up @@ -143,6 +149,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.0.5 h1:CuQcn5HIEeK7BgElubPP8CGtE0KakrnbBSTLjathl5o=
github.com/redis/go-redis/v9 v9.0.5/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
Expand Down
18 changes: 10 additions & 8 deletions internal/api/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package api
import (
"github.com/OpenIMSDK/chat/pkg/common/apicall"
"github.com/OpenIMSDK/chat/pkg/common/apistruct"
"github.com/OpenIMSDK/chat/pkg/common/config"
"github.com/OpenIMSDK/chat/pkg/common/mctx"
"github.com/OpenIMSDK/chat/pkg/proto/admin"
"github.com/OpenIMSDK/chat/pkg/proto/chat"
Expand Down Expand Up @@ -61,7 +62,8 @@ func (o *AdminApi) AdminLogin(c *gin.Context) {
apiresp.GinError(c, err)
return
}
imToken, err := o.imApiCaller.UserToken(c, loginResp.AdminUserID, constant.AdminPlatformID)
imAdminUserID := config.GetIMAdmin(loginResp.AdminUserID)
imToken, err := o.imApiCaller.UserToken(c, imAdminUserID, constant.AdminPlatformID)
if err != nil {
apiresp.GinError(c, err)
return
Expand All @@ -72,7 +74,7 @@ func (o *AdminApi) AdminLogin(c *gin.Context) {
return
}
resp.ImToken = imToken
resp.ImUserID = loginResp.AdminUserID
resp.ImUserID = imAdminUserID
log.ZInfo(c, "AdminLogin api", "resp", resp)
apiresp.GinSuccess(c, resp)
}
Expand Down Expand Up @@ -115,12 +117,12 @@ func (o *AdminApi) AddDefaultGroup(c *gin.Context) {
apiresp.GinError(c, err)
return
}
token, err := o.imApiCaller.AdminToken(c)
imToken, err := o.imApiCaller.UserToken(c, config.GetIMAdmin(mctx.GetOpUserID(c)), constant.AdminPlatformID)
if err != nil {
apiresp.GinError(c, err)
return
}
groups, err := o.imApiCaller.FindGroupInfo(mctx.WithApiToken(c, token), req.GroupIDs)
groups, err := o.imApiCaller.FindGroupInfo(mctx.WithApiToken(c, imToken), req.GroupIDs)
if err != nil {
apiresp.GinError(c, err)
return
Expand Down Expand Up @@ -167,12 +169,12 @@ func (o *AdminApi) SearchDefaultGroup(c *gin.Context) {
Groups: make([]*sdkws.GroupInfo, 0, len(searchResp.GroupIDs)),
}
if len(searchResp.GroupIDs) > 0 {
token, err := o.imApiCaller.AdminToken(c)
imToken, err := o.imApiCaller.UserToken(c, config.GetIMAdmin(mctx.GetOpUserID(c)), constant.AdminPlatformID)
if err != nil {
apiresp.GinError(c, err)
return
}
groups, err := o.imApiCaller.FindGroupInfo(mctx.WithApiToken(c, token), searchResp.GroupIDs)
groups, err := o.imApiCaller.FindGroupInfo(mctx.WithApiToken(c, imToken), searchResp.GroupIDs)
if err != nil {
apiresp.GinError(c, err)
return
Expand Down Expand Up @@ -256,12 +258,12 @@ func (o *AdminApi) BlockUser(c *gin.Context) {
apiresp.GinError(c, err)
return
}
token, err := o.imApiCaller.UserToken(c, mctx.GetOpUserID(c), constant.AdminPlatformID)
imToken, err := o.imApiCaller.UserToken(c, config.GetIMAdmin(mctx.GetOpUserID(c)), constant.AdminPlatformID)
if err != nil {
apiresp.GinError(c, err)
return
}
err = o.imApiCaller.ForceOffLine(mctx.WithApiToken(c, token), req.UserID)
err = o.imApiCaller.ForceOffLine(mctx.WithApiToken(c, imToken), req.UserID)
if err != nil {
apiresp.GinError(c, err)
return
Expand Down
30 changes: 22 additions & 8 deletions internal/api/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,18 @@ func (o *ChatApi) RegisterUser(c *gin.Context) {
apiresp.GinError(c, err)
return
}
token, err := o.imApiCaller.AdminToken(c)
imToken, err := o.imApiCaller.ImAdminTokenWithDefaultAdmin(c)
if err != nil {
apiresp.GinError(c, err)
return
}
ctx := mctx.WithApiToken(mctx.WithAdminUser(c), token)
if resp, err := o.adminClient.FindDefaultFriend(ctx, &admin.FindDefaultFriendReq{}); err == nil {
_ = o.imApiCaller.ImportFriend(ctx, respRegisterUser.UserID, resp.UserIDs)
apiCtx := mctx.WithApiToken(c, imToken)
rpcCtx := mctx.WithAdminUser(c)
if resp, err := o.adminClient.FindDefaultFriend(rpcCtx, &admin.FindDefaultFriendReq{}); err == nil {
_ = o.imApiCaller.ImportFriend(apiCtx, respRegisterUser.UserID, resp.UserIDs)
}
if resp, err := o.adminClient.FindDefaultGroup(ctx, &admin.FindDefaultGroupReq{}); err != nil {
_ = o.imApiCaller.InviteToGroup(c, respRegisterUser.UserID, resp.GroupIDs)
if resp, err := o.adminClient.FindDefaultGroup(rpcCtx, &admin.FindDefaultGroupReq{}); err == nil {
_ = o.imApiCaller.InviteToGroup(apiCtx, respRegisterUser.UserID, resp.GroupIDs)
}
if req.AutoLogin {
resp.ImToken, err = o.imApiCaller.UserToken(c, respRegisterUser.UserID, req.Platform)
Expand Down Expand Up @@ -198,7 +199,20 @@ func (o *ChatApi) UpdateUserInfo(c *gin.Context) {
apiresp.GinError(c, err)
return
}
token, err := o.imApiCaller.AdminToken(c)
opUserType, err := mctx.GetUserType(c)
if err != nil {
apiresp.GinError(c, err)
return
}
var imToken string
if opUserType == constant2.NormalUser {
imToken, err = o.imApiCaller.ImAdminTokenWithDefaultAdmin(c)
} else if opUserType == constant2.AdminUser {
imToken, err = o.imApiCaller.UserToken(c, config.GetIMAdmin(mctx.GetOpUserID(c)), constant.AdminPlatformID)
} else {
apiresp.GinError(c, errs.ErrArgs.Wrap("opUserType unknown"))
return
}
if err != nil {
apiresp.GinError(c, err)
return
Expand All @@ -217,7 +231,7 @@ func (o *ChatApi) UpdateUserInfo(c *gin.Context) {
} else {
faceURL = respUpdate.FaceUrl
}
err = o.imApiCaller.UpdateUserInfo(mctx.WithApiToken(c, token), req.UserID, nickName, faceURL)
err = o.imApiCaller.UpdateUserInfo(mctx.WithApiToken(c, imToken), req.UserID, nickName, faceURL)
if err != nil {
apiresp.GinError(c, err)
return
Expand Down
72 changes: 57 additions & 15 deletions internal/api/mw.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@
package api

import (
"strconv"

"github.com/OpenIMSDK/chat/pkg/common/constant"
constant2 "github.com/OpenIMSDK/protocol/constant"
"github.com/OpenIMSDK/tools/apiresp"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
"strconv"

"github.com/OpenIMSDK/chat/pkg/common/constant"
"github.com/OpenIMSDK/chat/pkg/proto/admin"
)

Expand All @@ -34,61 +35,102 @@ type MW struct {
client admin.AdminClient
}

func (o *MW) parseToken(c *gin.Context) (string, int32, error) {
func (o *MW) parseToken(c *gin.Context) (string, int32, string, error) {
token := c.GetHeader("token")
if token == "" {
return "", 0, errs.ErrArgs.Wrap("token is empty")
return "", 0, "", errs.ErrArgs.Wrap("token is empty")
}
resp, err := o.client.ParseToken(c, &admin.ParseTokenReq{Token: token})
if err != nil {
return "", 0, err
return "", 0, "", err
}
return resp.UserID, resp.UserType, nil
return resp.UserID, resp.UserType, token, nil
}

func (o *MW) parseTokenType(c *gin.Context, userType int32) (string, error) {
userID, t, err := o.parseToken(c)
func (o *MW) parseTokenType(c *gin.Context, userType int32) (string, string, error) {
userID, t, token, err := o.parseToken(c)
if err != nil {
return "", err
return "", "", err
}
if t != userType {
return "", errs.ErrArgs.Wrap("token type error")
return "", "", errs.ErrArgs.Wrap("token type error")
}
return userID, nil
return userID, token, nil
}

func (o *MW) isValidToken(c *gin.Context, userID string, token string) error {
resp, err := o.client.GetUserToken(c, &admin.GetUserTokenReq{UserID: userID})
m := resp.TokensMap
if err != nil {
log.ZWarn(c, "cache get token error", errs.ErrTokenNotExist.Wrap())
return err
}
if len(m) == 0 {
log.ZWarn(c, "cache do not exist token error", errs.ErrTokenNotExist.Wrap())
return errs.ErrTokenNotExist.Wrap()
}
if v, ok := m[token]; ok {
switch v {
case constant2.NormalToken:
case constant2.KickedToken:
log.ZWarn(c, "cache kicked token error", errs.ErrTokenKicked.Wrap())
return errs.ErrTokenKicked.Wrap()
default:
log.ZWarn(c, "cache unknown token error", errs.ErrTokenUnknown.Wrap())
return err
}
} else {
return errs.ErrTokenNotExist.Wrap()
}
return nil
}
func (o *MW) setToken(c *gin.Context, userID string, userType int32) {
c.Set(constant.RpcOpUserID, userID)
c.Set(constant.RpcOpUserType, []string{strconv.Itoa(int(userType))})
c.Set(constant.RpcCustomHeader, []string{constant.RpcOpUserType})
}

func (o *MW) CheckToken(c *gin.Context) {
userID, userType, err := o.parseToken(c)
userID, userType, token, err := o.parseToken(c)
if err != nil {
c.Abort()
apiresp.GinError(c, err)
return
}
if err := o.isValidToken(c, userID, token); err != nil {
c.Abort()
apiresp.GinError(c, err)
return
}
o.setToken(c, userID, userType)
}

func (o *MW) CheckAdmin(c *gin.Context) {
userID, err := o.parseTokenType(c, constant.AdminUser)
userID, token, err := o.parseTokenType(c, constant.AdminUser)
if err != nil {
c.Abort()
apiresp.GinError(c, err)
return
}
if err := o.isValidToken(c, userID, token); err != nil {
c.Abort()
apiresp.GinError(c, err)
return
}
o.setToken(c, userID, constant.AdminUser)
}

func (o *MW) CheckUser(c *gin.Context) {
userID, err := o.parseTokenType(c, constant.NormalUser)
userID, token, err := o.parseTokenType(c, constant.NormalUser)
if err != nil {
c.Abort()
apiresp.GinError(c, err)
return
}
if err := o.isValidToken(c, userID, token); err != nil {
c.Abort()
apiresp.GinError(c, err)
return
}
o.setToken(c, userID, constant.NormalUser)
}
9 changes: 7 additions & 2 deletions internal/rpc/admin/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package admin

import (
"context"
"github.com/OpenIMSDK/chat/pkg/common/db/cache"
"github.com/OpenIMSDK/tools/discoveryregistry"
"github.com/OpenIMSDK/tools/mcontext"
"google.golang.org/grpc"
Expand Down Expand Up @@ -51,15 +52,19 @@ func Start(discov discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
if err := db.AutoMigrate(tables...); err != nil {
return err
}
if err := database.NewAdminDatabase(db).InitAdmin(context.Background()); err != nil {
rdb, err := cache.NewRedis()
if err != nil {
return err
}
if err := database.NewAdminDatabase(db, rdb).InitAdmin(context.Background()); err != nil {
return err
}
if err := discov.CreateRpcRootNodes([]string{config.Config.RpcRegisterName.OpenImAdminName, config.Config.RpcRegisterName.OpenImChatName}); err != nil {
panic(err)
}

admin.RegisterAdminServer(server, &adminServer{
Database: database.NewAdminDatabase(db),
Database: database.NewAdminDatabase(db, rdb),
Chat: chat.NewChatClient(discov),
})
return nil
Expand Down
Loading

0 comments on commit 875665e

Please sign in to comment.