merge all branch and change project structure

This commit is contained in:
Gordon
2021-11-10 15:24:59 +08:00
91 changed files with 3612 additions and 1225 deletions
+2 -1
View File
@@ -1,8 +1,9 @@
package utils
import (
"github.com/gin-gonic/gin"
"net/http"
"github.com/gin-gonic/gin"
)
func CorsHandler() gin.HandlerFunc {
+7 -16
View File
@@ -13,23 +13,14 @@ func init() {
ServerIP = config.Config.ServerIP
return
}
//fixme Get the ip of the local network card
netInterfaces, err := net.Interfaces()
// see https://gist.github.com/jniltinho/9787946#gistcomment-3019898
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
panic(err)
}
for i := 0; i < len(netInterfaces); i++ {
//Exclude useless network cards by judging the net.flag Up flag
if (netInterfaces[i].Flags & net.FlagUp) != 0 {
address, _ := netInterfaces[i].Addrs()
for _, addr := range address {
if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ServerIP = ipNet.IP.String()
return
}
}
}
}
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
ServerIP = localAddr.IP.String()
}
+67 -107
View File
@@ -4,7 +4,7 @@ import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/db"
"errors"
"github.com/dgrijalva/jwt-go"
"github.com/golang-jwt/jwt/v4"
"time"
)
@@ -19,38 +19,27 @@ var (
type Claims struct {
UID string
Platform string //login platform
jwt.StandardClaims
jwt.RegisteredClaims
}
func BuildClaims(uid, accountAddr, platform string, ttl int64) Claims {
now := time.Now().Unix()
//if ttl=-1 Permanent token
if ttl == -1 {
return Claims{
UID: uid,
Platform: platform,
StandardClaims: jwt.StandardClaims{
ExpiresAt: -1,
IssuedAt: now,
NotBefore: now,
}}
}
func BuildClaims(uid, platform string, ttl int64) Claims {
now := time.Now()
return Claims{
UID: uid,
Platform: platform,
StandardClaims: jwt.StandardClaims{
ExpiresAt: now + ttl, //Expiration time
IssuedAt: now, //Issuing time
NotBefore: now, //Begin Effective time
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, accountAddr string, platform int32) (string, int64, error) {
claims := BuildClaims(userID, accountAddr, PlatformIDToName(platform), config.Config.TokenPolicy.AccessExpire)
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, err
return tokenString, claims.ExpiresAt.Time.Unix(), err
}
func secret() jwt.Keyfunc {
@@ -59,7 +48,7 @@ func secret() jwt.Keyfunc {
}
}
func ParseToken(tokensString string) (claims *Claims, err error) {
func getClaimFromToken(tokensString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokensString, &Claims{}, secret())
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
@@ -75,76 +64,66 @@ func ParseToken(tokensString string) (claims *Claims, err error) {
}
}
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
// 1.check userid and platform class 0 not exists and 1 exists
existsInterface, err := db.DB.ExistsUserIDAndPlatform(claims.UID, Platform2class[claims.Platform])
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)
//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.
if Platform2class[claims.Platform] == "PC" {
existsInterface, err = db.DB.ExistsUserIDAndPlatform(claims.UID, "Mobile")
if err != nil {
return nil, err
}
exists = existsInterface.(int64)
if exists == 1 {
res, err := MakeTheTokenInvalid(*claims, "Mobile")
if err != nil {
return nil, err
}
if res {
return nil, TokenInvalid
}
}
} else {
existsInterface, err = db.DB.ExistsUserIDAndPlatform(claims.UID, "PC")
if err != nil {
return nil, err
}
exists = existsInterface.(int64)
if exists == 1 {
res, err := MakeTheTokenInvalid(*claims, "PC")
if err != nil {
return nil, err
}
if res {
return nil, TokenInvalid
}
}
}
if exists == 1 {
res, err := MakeTheTokenInvalid(*claims, Platform2class[claims.Platform])
if err != nil {
return nil, err
}
if res {
return nil, TokenInvalid
}
exists = existsInterface.(int64)
if exists == 1 {
res, err := MakeTheTokenInvalid(claims, platform)
if err != nil {
return nil, err
}
} else if config.Config.MultiLoginPolicy.MobileAndPCTerminalAccessButOtherTerminalKickEachOther {
if exists == 1 {
res, err := MakeTheTokenInvalid(*claims, Platform2class[claims.Platform])
if err != nil {
return nil, err
}
if res {
return nil, TokenInvalid
}
if res {
return nil, TokenInvalid
}
}
return claims, nil
}
return nil, TokenUnknown
// 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) {
func MakeTheTokenInvalid(currentClaims *Claims, platformClass string) (bool, error) {
storedRedisTokenInterface, err := db.DB.GetPlatformToken(currentClaims.UID, platformClass)
if err != nil {
return false, err
@@ -154,40 +133,21 @@ func MakeTheTokenInvalid(currentClaims Claims, platformClass string) (bool, erro
return false, err
}
//if issue time less than redis token then make this token invalid
if currentClaims.IssuedAt < storedRedisPlatformClaims.IssuedAt {
if currentClaims.IssuedAt.Time.Unix() < storedRedisPlatformClaims.IssuedAt.Time.Unix() {
return true, TokenInvalid
}
return false, nil
}
func ParseRedisInterfaceToken(redisToken interface{}) (*Claims, error) {
token, err := jwt.ParseWithClaims(string(redisToken.([]uint8)), &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, TokenInvalid
}
}
}
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
return claims, nil
}
return nil, err
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 {
if err != nil || claims.UID != uid {
return false
} else if claims.UID != uid {
return false
} else {
return true
}
return true
}
+5
View File
@@ -106,6 +106,11 @@ func MapToJsonString(param map[string]interface{}) string {
dataString := string(dataType)
return dataString
}
func MapIntToJsonString(param map[string]int32) string {
dataType, _ := json.Marshal(param)
dataString := string(dataType)
return dataString
}
func JsonStringToMap(str string) (tempMap map[string]interface{}) {
_ = json.Unmarshal([]byte(str), &tempMap)
return tempMap
+4
View File
@@ -37,6 +37,7 @@ func IsContain(target string, List []string) bool {
return false
}
func InterfaceArrayToStringArray(data []interface{}) (i []string) {
for _, param := range data {
i = append(i, param.(string))
@@ -62,3 +63,6 @@ func GetMsgID(sendID string) string {
func int64ToString(i int64) string {
return strconv.FormatInt(i, 10)
}
func Int64ToString(i int64) string {
return strconv.FormatInt(i, 10)
}