golang实现页面访问权限控制(验证用户是否登陆)

这是对自己最近一个小项目中问题的记录,需求是只有登录的用户才能进入到该页面,所以需要在该页面进行判断用户是否登陆,开发用到了iris框架,这里用到中间件来实现这个功能。

  • 主要思路是:要实现该功能需要设置一下cookie,在登录页面提交的表单中将用户ID保存到cookie中,在受到权限的页面获取用户ID并判断是否为空,若为空则跳转到登录页面进行登录,否则则可以进入到该页面。
    登录相关代码如下:
func (c *UserController) PostLogin() mvc.Response{
	var (
		userName = c.Ctx.FormValue("userName")
		password = c.Ctx.FormValue("password")
	)
	//比对用户名和密码
	user, isOK := c.Service.IsPwdSuccess(userName,password)
	if !isOK{
		fmt.Println("用户名或者密码错误!")
		//如果没有成功就通过mvc.reponse跳转到login
		return mvc.Response{
			Path:"/user/login",
		}
	}
	//设置cookie
	tool.GlobalCookie(c.Ctx,"uid",strconv.FormatInt(user.ID,10))
	c.Session.Set("userID",strconv.FormatInt(user.ID,10))
	return mvc.Response{
		Path:"/product/detail",
	}
}

中间件(验证用户是否登陆)

func AuthConProduct(ctx iris.Context){
	//在user_controller中提交登陆表单的时候设置了cookie,所以在这里直接从上下文获取
	uid := ctx.GetCookie("uid")
	if uid ==""{
		ctx.Application().Logger().Debug("请先登陆!")
		ctx.Redirect("/user/login")
		return
	}
	ctx.Application().Logger().Debug("已登陆!")
	//继续请求上下文
	ctx.Next()
}

记得在main文件中将中间件注册到product中

    //注册路由
	proProduct :=app.Party("/product",middleware.AuthConProduct)
	proPro   := mvc.New(proProduct)//注册到框架上
	//将验证注册到product中
	proProduct.Use(middleware.AuthConProduct)
	//将service以及session绑定到控制器中
	proPro.Register(productService,orderService,sess.Start)
	proPro.Handle(new(controllers2.ProductController))

猜你喜欢

转载自blog.csdn.net/weixin_43867526/article/details/107773475