Beego学习——实现用户登录登出

简介: Beego学习——实现用户登录登出

controller包

  user.go

import (
  "demo03.cn/models"
  "encoding/json"
  "fmt"
  "github.com/astaxie/beego"
  "github.com/astaxie/beego/orm"
)
type UserController struct {
  beego.Controller
}
func (c *UserController) Reg()  {
  resp :=make(map[string]interface{})
  defer c.RetData(resp)
  //获取前端传过来的json的数据
  _ = json.Unmarshal(c.Ctx.Input.RequestBody,&resp)
  //封装成结构体
  o := orm.NewOrm()
  user := models.User{}
  user.Name = resp["name"].(string)
  user.Password = resp["password"].(string)
  id,err :=o.Insert(&user)
  if err != nil{
    resp["errmsg"]="注册失败"
    return
  }
  resp["errmsg"]=fmt.Sprintf("注册成功,id:%d",id)
  c.SetSession("name",user.Name)
}
// 格式化数据 返回json格式
func (c *UserController) RetData(resp map[string]interface{}) {
  c.Data["json"] =resp
  c.ServeJSON()
}

session.go

controller session.go

import (
  "demo03.cn/models"
  "encoding/json"
  "github.com/astaxie/beego"
  "github.com/astaxie/beego/logs"
  "github.com/astaxie/beego/orm"
)
type SessionController struct {
  beego.Controller
}
//TODO 获取Session
func (c *SessionController) GetSessionData()  {
  logs.Info("connect success")
  resp :=make(map[string]interface{})
  defer c.RetData(resp)
  user := models.User{}
  session := c.GetSession("name")
  if session!=nil {
    user.Name = session.(string)
    resp["msg"] = "获取成功"
    resp["data"] = user
  }else {
    resp["msg"] = "获取失败"
    logs.Info(user)
  }
}
//删除对应的Session
func (c *SessionController) DeleteSessionData()  {
  resp := make(map[string]interface{})
  defer c.RetData(resp)
  c.DelSession("name")
  resp["msg"]="删除成功"
}
// TODO 登录
func (c *SessionController) Login()  {
  resp := make(map[string]interface{})
  defer c.RetData(resp)
  //得到用户信息获取前端传递过来的json数据
  _ = json.Unmarshal(c.Ctx.Input.RequestBody,&resp)
  logs.Info(&resp)
  //判断是否合法
  if resp["name"] == nil || resp["password"] ==nil{
    resp["msg"]="用户名和密码不可以为空!"
    return
  }
  //与数据库匹配账号密码是否正确
  o := orm.NewOrm()
  user := models.User{Name:resp["name"].(string)}
  name := resp["name"].(string)
  qs := o.QueryTable("user")
  err := qs.Filter("name",name).One(&user)
  if err !=nil {
    resp["msg"]="数据错误"
    logs.Info("2222name=",resp["name"],"password:",resp["password"])
    return
  }
  if user.Password != resp["password"] {
    resp["msg"]="用户名或密码错误"
    logs.Info("3333name=",resp["name"],"password:",resp["password"])
    return
  }
  //添加Session
  c.SetSession("name",resp["name"])
  c.SetSession("user_id",user.Id)
  //返回json数据给前端
  resp["msg"]="登录成功"
}
func (c *SessionController) RetData(resp map[string]interface{}) {
  c.Data["json"] =resp
  c.ServeJSON()
}

models包

  userModel.go

import (
  "github.com/astaxie/beego/orm"
  _ "github.com/go-sql-driver/mysql"
)
type User struct {
  Id       int    `json:"id"`
  Name string `json:"name"`
  Password string `json:"password"`
}
func init() {
  // 映射model数据
  orm.RegisterModel(new(User))
}

router包

  router.go

func init() {
  beego.Router("/user/session",&controllers.SessionController{},"get:GetSessionData;delete:DeleteSessionData")
  beego.Router("/user/sessions",&controllers.SessionController{},"post:Login")
  beego.Router("/user/users",&controllers.UserController{},"post:Reg")
}

main.go

import (
  _ "demo03.cn/routers"
  "github.com/astaxie/beego"
  "github.com/astaxie/beego/context"
  "github.com/astaxie/beego/logs"
  "github.com/astaxie/beego/orm"
  "net/http"
  "strings"
)
//
func main() {
  ignoreStaticPath()
  beego.Run()
}
func ignoreStaticPath()  {
  beego.InsertFilter("/",beego.BeforeRouter,TransparentStatic)
  beego.InsertFilter("/*",beego.BeforeRouter,TransparentStatic)
}
func TransparentStatic(ctx *context.Context){
  // 获取请求的url
  orpath := ctx.Request.URL.Path
  logs.Info("request url:",orpath)
  //如果请求url包含api字段,说明指令应该取消静态资源重定向
  if strings.Index(orpath,"user") >= 0{
    return
  }
  // 静态资源重定向
  //http.ServeFile(ctx.ResponseWriter,ctx.Request,"static/html"+ctx.Request.URL.Path)
  http.ServeFile(ctx.ResponseWriter,ctx.Request,"static/img/img")
}
func init() {
  // 设置数据库基本信息,相当于连接数据库
  _ = orm.RegisterDataBase("default", "mysql", beego.AppConfig.String("dataSource"), 30)
  // 生成表
  _ = orm.RunSyncdb("default", false, true)
}
相关文章
|
4月前
|
SQL 数据安全/隐私保护
带token的多用户登录(注册直接粗暴解决)
带token的多用户登录(注册直接粗暴解决)
带token的多用户登录(注册直接粗暴解决)
|
4月前
|
存储 前端开发
通过session实现用户的登录与登出功能
通过session实现用户的登录与登出功能
50 0
|
9月前
|
安全 搜索推荐 Java
SpringSecurity-8-自动登录和注销功能实现
当我们在登录某一个网站的时候,我们会使用账号密码进行登录,但是我们不想每一次关闭浏览器,我们不想每一次重新输入账号和密码,贴合用户的登录体验,给用户带来方便,我们使用自动登录功能,将登录信息保存在浏览器的cookie中,这样用户在下次访问的时候,自动实现校验并新建登录状态。但是这样也会给用户带来信息泄露的危险。
93 0
|
11月前
|
安全 数据安全/隐私保护 Python
用户登录程序需求
用户登录程序需求
59 0
jira学习案例43-用useAsync获取用户信息
jira学习案例43-用useAsync获取用户信息
58 0
jira学习案例43-用useAsync获取用户信息
|
Java 数据安全/隐私保护 容器
【JavaWeb】案例:用户登录、用户自动登录
本期主要介绍案例:用户登录、用户自动登录
228 0
【JavaWeb】案例:用户登录、用户自动登录
|
存储 JSON 中间件
8. 为Lamb编写用户登录接口(带token)
上篇我们给Lamb引入了flask_sqlalchemy,接着我们就编写我们第一个接口---登录
121 0
8. 为Lamb编写用户登录接口(带token)
|
PHP
【laravel项目】@2 账号密码登录验证(1)
【laravel项目】@2 账号密码登录验证
62 0
【laravel项目】@2 账号密码登录验证(1)
|
PHP
【laravel项目】@2 账号密码登录验证(2)
【laravel项目】@2 账号密码登录验证
60 0
【laravel项目】@2 账号密码登录验证(2)
|
PHP
【laravel】在使用Auth认证时,登录后直接进入home,不登录会直接跳转到login
【laravel】在使用Auth认证时,登录后直接进入home,不登录会直接跳转到login
239 0
【laravel】在使用Auth认证时,登录后直接进入home,不登录会直接跳转到login