七叶笔记 » golang编程 » go语言札记-单点登录

go语言札记-单点登录

 //1.判断
var AuthFilter = func(ctx *context.Context) {
	token := ctx.Input.Header("Authorization")
	if token == "" {
		result := controllers.Reponse(4001, "", "require token")
		_ = ctx.Output.JSON(result, true, true)
		return
	}
	if claims, isValid, err := utils.ParaseToken(token); err == nil && isValid {
		var user models.User
		userMod := models.User{}
		err := userMod.Query().Filter("id", claims.UId).One(&user)
		if err != nil {
			ctx.Output.SetStatus(401)
			out := map[string]interface{}{}
			out["msg"] = "err"
			out["code"] = 4001
			_ = ctx.Output.JSON(out, true, true)
			return
		} else {
			if claims.Timestamp == user.Timestamp {
				ctx.Input.SetData("User", user)
				return
			} else {
				result := controllers.Reponse(4002, "", "账号在其它账号登陆了")
				_ = ctx.Output.JSON(result, true, true)
				return
			}
		}
	}
	out := map[string]interface{}{}
	out["msg"] = "token invalid"
	out["code"] = 4001
	_ = ctx.Output.JSON(out, true, true)
}  
 type MyCustomClaims struct {
	UId int64 `json:"uid"`
	jwt.StandardClaims
	Timestamp int64
}

func ParaseToken(authorization string) (*MyCustomClaims, bool, error) {
	token, _ := jwt.ParseWithClaims(authorization, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, nil
		}
		return []byte(beego.AppConfig.String("authKey")), nil
	})
	if  token == nil {
		return nil, false, errors.New("token invalid")
	}
	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		fmt.Println("claims:", claims)
		return claims, true, nil
	}
	return nil, false, errors.New("token invalid")
}

func GenToken(uId int64,timestamp int64) (string, error) {
	expireToken := time.Now().Add(time.Hour * 12).Unix()
	claims := MyCustomClaims{
		uId,
		jwt.StandardClaims{
			NotBefore: int64(time.Now().Unix() - 1000), // 签名生效时间
			ExpiresAt: expireToken,
			Issuer:    "6617.com",
		},
		timestamp,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(beego.AppConfig.String("authKey")))
}
  

相关文章