Selaa lähdekoodia

token generate session

abiao 4 vuotta sitten
vanhempi
commit
e02b9c1cd2

+ 64 - 45
go/gopath/src/fohow.com/apps/init.go

@@ -16,6 +16,7 @@ import (
 	"fohow.com/apps/models/user_model"
 	// "fohow.com/libs/tool"
 	// "fohow.com/libs/wx_mp"
+	"fohow.com/libs/tool"
 )
 
 const (
@@ -372,7 +373,7 @@ func checkWxUserLogin(ctx *context.Context) {
 	// TODO : 整个项目也应该更加适合采用 token 机制
 	beego.BeeLogger.Info("check wx_user login")
 	if !isWxClient(ctx) {
-		return
+		//return
 	}
 	wxUserId, ok := ctx.Input.Session(SessionWxUserKey).(int64)
 	if ok {
@@ -403,44 +404,59 @@ func checkWxUserLogin(ctx *context.Context) {
 			return
 
 		} else {
-			errCode := &ErrCode{
-				Code:     UserNeedLogin[0],
-				Msg:      UserNeedLogin[1],
-				Redirect: "",
-				Data:     nil,
+			// app 带token登录,需检测 token 是否合法
+			var inputToken string
+			beego.BeeLogger.Warn("request authorizationData : %s", ctx.Request.Header.Get("Authorization"))
+
+			requestAuthordata := ctx.Request.Header.Get("Authorization")
+			if len(requestAuthordata) > 0 {
+				authorizationData := strings.SplitN(ctx.Request.Header.Get("Authorization"), " ", 2)
+				if len(authorizationData) != 2 {
+					errCode := &ErrCode{
+						Code:     UserNeedLogin[0],
+						Msg:      UserNeedLogin[1],
+						Redirect: "",
+						Data:     nil,
+					}
+					//换成userNeedLogin
+					ctx.Output.SetStatus(403)
+					ctx.Output.JSON(errCode, true, true)
+				}
+				inputToken = authorizationData[1]
+				err, tel := tool.CheckToken(inputToken)
+				user := user_model.GetByTel(tel, false)
+				wxUser := user_model.GetWxUserByUserId(user.Id, true)
+
+				if err != nil || (user == nil) || (wxUser == nil) {
+					// 验证 Token 无效
+					errCode := &ErrCode{
+						Code:     UserNeedLogin[0],
+						Msg:      UserNeedLogin[1],
+						Redirect: "",
+						Data:     nil,
+					}
+					ctx.Output.SetStatus(403)
+					ctx.Output.JSON(errCode, true, true)
+
+				} else {
+					ctx.Output.Session(SessionUserKey, wxUser.UserId)
+					ctx.Output.Session(SessionWxUserKey, wxUser.Id)
+				}
+
+			} else {
+				errCode := &ErrCode{
+					Code:     UserNeedLogin[0],
+					Msg:      UserNeedLogin[1],
+					Redirect: "",
+					Data:     nil,
+				}
+				ctx.Output.SetStatus(401)
+				ctx.Output.JSON(errCode, true, true)
+				return
 			}
-			ctx.Output.SetStatus(401)
-			ctx.Output.JSON(errCode, true, true)
-			return
 
 		}
 
-		// } else {
-		// // FIXME : 这里 IsAjax 判断是否有问题? 微信来的应该属于api请求
-		// beego.BeeLogger.Debug("WEIXIN user not login", ctx.Input)
-
-		// errCode := &ErrCode{
-		// 	Code:     UserNeedLogin[0], // FIXME : 这里应该 是 WxUserNeedLogin, 因为前端编码用了UserNeedLogin,以后一起修改
-		// 	Msg:      UserNeedLogin[1],
-		// 	Redirect: "",
-		// 	Data:     nil,
-		// }
-		// ctx.Output.SetStatus(401)
-		// ctx.Output.JSON(errCode, true, true)
-		// return
-
-		// beego.BeeLogger.Warn("this is not a ajax request!")
-		// 微信用户自动登录
-		// if isWxClient(ctx) {
-		// 	// beego.BeeLogger.Warn("---------------%s", ctx.Input.Site())
-		// 	url := fmt.Sprintf("%s/login/mp?cb=%s%s",
-		// 		beego.AppConfig.String("ApiHost"),
-		// 		ctx.Input.Site(), ctx.Input.URI())
-		// 	// beego.BeeLogger.Warn("auto login mp cb url=%s", url)
-		// 	ctx.Redirect(302, url)
-		// 	return
-		// }
-		// }
 	}
 }
 
@@ -504,7 +520,7 @@ func CheckIsInvokeFromRailsAdmin(ctx *context.Context) {
 func (self *BaseController) Prepare() {
 	beego.BeeLogger.Info("invote controller Prepare func")
 	needChkWxUserLogin := true
-	needChkUserLogin := true
+	//needChkUserLogin := true
 	// needChkWxUserSubscribe := false
 	_, actionName := self.GetControllerAndAction()
 
@@ -516,21 +532,24 @@ func (self *BaseController) Prepare() {
 			}
 		}
 	}
-	if len(self.ExceptCheckUserLoginAction) > 0 {
-		for _, an := range self.ExceptCheckUserLoginAction {
-			if strings.ToLower(an) == "*" || strings.ToLower(an) == strings.ToLower(actionName) {
-				needChkUserLogin = false
-				break
+	/*
+		// FIXME : userId 与 wxUserId已统一
+		if len(self.ExceptCheckUserLoginAction) > 0 {
+			for _, an := range self.ExceptCheckUserLoginAction {
+				if strings.ToLower(an) == "*" || strings.ToLower(an) == strings.ToLower(actionName) {
+					needChkUserLogin = false
+					break
+				}
 			}
 		}
-	}
+		if needChkUserLogin {
+			checkUserLogin(self.Ctx)
+		}
+	*/
 
 	if needChkWxUserLogin {
 		checkWxUserLogin(self.Ctx)
 	}
-	if needChkUserLogin {
-		checkUserLogin(self.Ctx)
-	}
 
 }
 

BIN
go/gopath/src/fohow.com/fohowmall.com


+ 13 - 5
go/gopath/src/fohow.com/libs/tool/token.go

@@ -20,15 +20,23 @@ func CreateToken(Phone string) string {
 	return tokenString
 }
 
-func CheckToken(tokenString string) string {
+func CheckToken(tokenString string) (err error, phone string) {
 	Phone := ""
-	token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
+	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
 		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
 			return nil, fmt.Errorf("Unexpected signing method")
 		}
 		return []byte(beego.AppConfig.String("TokenSecrets")), nil
 	})
-	claims, _ := token.Claims.(jwt.MapClaims)
-	Phone = claims["phone"].(string)
-	return Phone
+	//beego.BeeLogger.Warn("token--%v",token)
+	//beego.BeeLogger.Warn("err--%v",err)
+
+	if err != nil {
+		beego.BeeLogger.Warn("err--%v", err)
+		return err, Phone
+	} else {
+		claims, _ := token.Claims.(jwt.MapClaims)
+		Phone = claims["phone"].(string)
+	}
+	return nil, Phone
 }