前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >beego 前后端分离登录验证

beego 前后端分离登录验证

作者头像
landv
发布2019-07-01 17:54:10
2.2K1
发布2019-07-01 17:54:10
举报
文章被收录于专栏:landvlandv

conf>app.conf 文件添加一下参数

代码语言:javascript
复制
copyrequestbody=true
sessionon =true

routers>router.go 文件添加初始化路由

代码语言:javascript
复制
func init() {
    
    ///api/v1.0/areas
    // beego.Router("/api/v1.0/areas", &controllers.AreaController{},"get:GetArea")
    beego.Router("api/v1.0/areas", &controllers.LAreaControllers{}, "get:GetArea")
    //TODO /api/v1.0/session
    //TODO /api/v1.0/houses/index
    beego.Router("/api/v1.0/session",&controllers.SessionController{},"get:GetSessionData;delete:DeleteSessionData")
    beego.Router("/api/v1.0/sessions",&controllers.SessionController{},"post:Login")
    beego.Router("/api/v1.0/houses/index",&controllers.HouseIndexController{},"get:GetHouseIndex")
    beego.Router("/api/v1.0/users",&controllers.UserController{},"post:Reg")

}

models>recode.go 错误代码编码

代码语言:javascript
复制
package models


const (
    RECODE_OK         = "0"
    RECODE_DBERR      = "4001"
    RECODE_NODATA     = "4002"
    RECODE_DATAEXIST  = "4003"
    RECODE_DATAERR    = "4004"
    RECODE_SESSIONERR = "4101"
    RECODE_LOGINERR   = "4102"
    RECODE_PARAMERR   = "4103"
    RECODE_USERERR    = "4104"
    RECODE_ROLEERR    = "4105"
    RECODE_PWDERR     = "4106"
    RECODE_REQERR     = "4201"
    RECODE_IPERR      = "4202"
    RECODE_THIRDERR   = "4301"
    RECODE_IOERR      = "4302"
    RECODE_SERVERERR  = "4500"
    RECODE_UNKNOWERR  = "4501"
)

var recodeText = map[string]string{
    RECODE_OK:         "成功",
    RECODE_DBERR:      "数据库查询错误",
    RECODE_NODATA:     "无数据",
    RECODE_DATAEXIST:  "数据已存在",
    RECODE_DATAERR:    "数据错误",
    RECODE_SESSIONERR: "用户未登录",
    RECODE_LOGINERR:   "用户登录失败",
    RECODE_PARAMERR:   "参数错误",
    RECODE_USERERR:    "用户不存在或未激活",
    RECODE_ROLEERR:    "用户身份错误",
    RECODE_PWDERR:     "密码错误",
    RECODE_REQERR:     "非法请求或请求次数受限",
    RECODE_IPERR:      "IP受限",
    RECODE_THIRDERR:   "第三方系统错误",
    RECODE_IOERR:      "文件读写错误",
    RECODE_SERVERERR:  "内部错误",
    RECODE_UNKNOWERR:  "未知错误",
}

func RecodeText(code string)string  {
    str,ok := recodeText[code]
    if ok {
        return str
    }
    return RecodeText(RECODE_UNKNOWERR)
}

controllers>User.go 用户注册

代码语言:javascript
复制
package controllers

import (
    "encoding/json"
    "github.com/astaxie/beego"
    "github.com/astaxie/beego/orm"
    "lovehome/models"
)

type UserController struct {
    beego.Controller
}

func (c *UserController) Get() {
    c.Data["Website"] = "beego.me"
    c.Data["Email"] = "astaxie@gmail.com"
    c.TplName = "index.tpl"
}
func (c *UserController) Reg()  {

    resp :=make(map[string]interface{})
    defer c.RetData(resp)

    //TODO 获取前端传过来的json的数据
    json.Unmarshal(c.Ctx.Input.RequestBody,&resp)
    //beego.Info(resp)
    //TODO 封装成结构体
    o := orm.NewOrm()
    user := models.User{}
    user.Mobile = resp["mobile"].(string)
    user.Name = resp["mobile"].(string)
    user.Password_hash = resp["password"].(string)
    id,err :=o.Insert(&user)
    if err != nil{
        resp["errno"]=models.RECODE_NODATA
        resp["errmsg"]=models.RecodeText(models.RECODE_NODATA)
        return
    }
    beego.Info("reg success,id=",id)
    resp["errno"]=models.RECODE_OK
    resp["errmsg"]=models.RecodeText(models.RECODE_OK)
    c.SetSession("name",user.Name)


}

func (c *UserController) RetData(resp map[string]interface{}) {
    c.Data["json"] =resp
    c.ServeJSON()
}

controllers>Session.go 登录

代码语言:javascript
复制
package controllers

import (
    "encoding/json"
    "github.com/astaxie/beego"
    "github.com/astaxie/beego/orm"
    "lovehome/models"
)

type SessionController struct {
    beego.Controller
}

func (c *SessionController) Get() {
    c.Data["Website"] = "beego.me"
    c.Data["Email"] = "astaxie@gmail.com"
    c.TplName = "index.tpl"
}
//TODO 获取Session
func (c *SessionController) GetSessionData()  {
    beego.Info("connect success")
    resp :=make(map[string]interface{})
    defer c.RetData(resp)
    user := models.User{}
    //user.Name="浩秦"

    resp["errno"] = 4001
    resp["errmsg"] = "数据获取失败"
    name := c.GetSession("name")
    if name!=nil {
        user.Name = name.(string)
        resp["errno"] = 0
        resp["mrrmsg"] = "ok"
        resp["data"] = user
    }
}

//TODO 删除对应的Session
func (c *SessionController) DeleteSessionData()  {
    resp := make(map[string]interface{})
    defer c.RetData(resp)
    c.DelSession("name")
    resp["errno"]=0
    resp["errmsg"]="ok"
}
// TODO 登录
func (c *SessionController) Login()  {

    resp := make(map[string]interface{})
    defer c.RetData(resp)

    //得到用户信息获取前端传递过来的json数据
    json.Unmarshal(c.Ctx.Input.RequestBody,&resp)
    beego.Info(&resp)
    //判断是否合法
    if resp["mobile"] == nil || resp["password"] ==nil{
        resp["errno"]=models.RECODE_DATAERR
        resp["errmsg"]=models.RecodeText(models.RECODE_DATAERR)
        return
    }
    //与数据库匹配账号密码是否正确
    o := orm.NewOrm()
    user := models.User{Name:resp["mobile"].(string)}
    moble := resp["mobile"].(string)
    qs := o.QueryTable("user")
    err := qs.Filter("mobile",moble).One(&user)
    if err !=nil {
        resp["errno"]=models.RECODE_DATAERR
        resp["errmsg"]=models.RecodeText(models.RECODE_DATAERR)
        beego.Info("2222name=",resp["mobile"],"========password====",resp["password"])

        return
    }
    if user.Password_hash != resp["password"] {
        resp["errno"]=models.RECODE_DATAERR
        resp["errmsg"]=models.RecodeText(models.RECODE_DATAERR)
        beego.Info("3333name=",resp["mobile"],"========password====",resp["password"])
        return
    }
    //添加Session
    c.SetSession("name",resp["mobile"])
    c.SetSession("mobile",resp["mobile"])
    c.SetSession("user_id",user.Id)
    //返回json数据给前端
    resp["errno"]=models.RECODE_OK
    resp["errmsg"]=models.RecodeText(models.RECODE_OK)


}
func (c *SessionController) RetData(resp map[string]interface{}) {
    c.Data["json"] =resp
    c.ServeJSON()
}

controllers>area.go

代码语言:javascript
复制
package controllers

import (
    "github.com/astaxie/beego"
    "github.com/astaxie/beego/orm"
    "lovehome/models"
)

type LAreaControllers struct {
    beego.Controller
}

func (c *LAreaControllers) Get() {
    c.Data["Website"] = "beego.me"
    c.Data["Email"] = "astaxie@gmail.com"
    c.TplName = "index.tpl"
}
func (c *LAreaControllers) GetArea()  {
    beego.Info("connect success")
    resp :=make(map[string]interface{})
    resp["errno"]=0
    resp["errmsg"]="ok"
    defer c.RetData(resp)

    //TODO 从MySQL里面读取数据
    var areas []models.Area
    o := orm.NewOrm()
    num,err := o.QueryTable("area").All(&areas)
    if err != nil {
        resp["errno"]=4001
        resp["errmsg"]="数据库查询失败"
        return
    }
    if num == 0 {
        resp["errno"]=4002
        resp["errmsg"]="没有查到数据"
    }
    //TODO 打包成json返回给前端
    resp["data"]=areas
    beego.Info("query data sucess,resp=",resp,"num=",num)
}

func (c *LAreaControllers) RetData(resp map[string]interface{}) {
    c.Data["json"] =resp
    c.ServeJSON()
}

main.go beego前后端分离静态页面承载有点费劲,不过也好只是比gin多几句代码而已

代码语言:javascript
复制
package main

import (
    _ "lovehome/routers"
    _ "lovehome/models"
    "github.com/astaxie/beego"

    "github.com/astaxie/beego/context"
    "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){
    orpath := ctx.Request.URL.Path
    beego.Info("request url:",orpath)
    //如果请求url包含api字段,说明指令应该取消静态资源重定向
    if strings.Index(orpath,"api") >= 0{
        return
    }


    http.ServeFile(ctx.ResponseWriter,ctx.Request,"static/html/"+ctx.Request.URL.Path)

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 MySQL
腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档