210-beego登录退出与过滤器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33781658/article/details/85932488




beego登录退出与过滤器


4个步骤
1.获取
2.校验
3.处理
4.返回

func (this *UserController) HandleLogin(){

//获取数据
username := this.GetString("username")
password := this.GetString("pwd")

//校验数据
if username =="" ||password==""{
	this.Data["err"]="数据输入不完整"
	this.TplName="login.html"
	return
}

//处理数据
o := orm.NewOrm()
var user models.User
user.UserName=username

err := o.Read(&user,"Username")
if err!=nil{
	this.Data["err"]="用户名不存在"
	this.TplName="login.html"
	return
}

if user.Pwd!=pwd{
	this.Data["err"]="密码错误"
	this.TplName="login.html"
	return
}

if user.Active==0{
	this.Data["err"]="用户未激活"
	this.TplName="login.html"
	return
}

//返回数据
this.Redirect("/index",302)

}




我们要用cookie去记住以下用户名
<input type="checkbox" name="remember">

rememebr := this.GetString("remember")
if remember=="on"{
	this.Ctx.SetCookie("username",username,3600)
}else{
	this.Ctx.SetCookie("username",username,-1)
}


在我们的ShowLogin里面
username := this.Ctx.GetCookie("username")
if username!="" {
	this.Data["username"]=username
	this.Data["checked"]="checked"
}else{
	this.Data["username"]=""
	this.Data["checked"]=""
}



然后我们看下登录完整代码

func(this*UserController)HandleLogin(){
   //1.获取数据
   userName := this.GetString("username")
   pwd := this.GetString("pwd")
   check := this.GetString("check")
   if userName==""||pwd == ""{
      this.Data["errmsg"] = "用户名或密码不能为空,请重新登陆!"
      this.TplName = "login.html"
      return
   }
   //2.查询数据
   o:=orm.NewOrm()
   user := models.User{Name:userName}
   err:=o.Read(&user,"Name")
   if err !=nil{
      this.Data["errmsg"] = "用户名或密码错误,请重新登陆!"
      this.TplName = "login.html"
      return
   }
   if user.PassWord != pwd{
      this.Data["errmsg"] = "用户名或密码错误,请重新登陆!"
      this.TplName = "login.html"
      return
   }
   if user.Active != true{
      this.Data["errmsg"] = "该用户没有激活,请县激活!"
      this.TplName = "login.html"
      return
   }
   if check == "on"{
      this.Ctx.SetCookie("username",userName,time.Second * 3600)
   }else {
      this.Ctx.SetCookie("username",userName,-1)
   }
   this.SetSession("userName",userName)
   this.Redirect("/",302)
}




然后我们看一下用户退出
退出非常简单
就是清空session的值就好了
func (this *UserController) Logout(){
	this.DelSession("username")
	this.Redirect("/",302)
}




一些界面是只有登录之后才能访问的
那么我们要做一个登录校验
通过过滤器就可以实现登陆校验

var filterFunc = func(ctx *context.Context){
	username := ctx.Input.Session("username")
	if username==nil{
	ctx.Redirect(302,"/login")
	}
}

然后我们需要在路由里面加入
在router的init函数中加入
beego.InsertFilter("/goods/*",beego.BeforeRouter,filterFunc)


那么所有需要登录才能访问的页面
都需要加上/goods路径



猜你喜欢

转载自blog.csdn.net/qq_33781658/article/details/85932488