验证access token
()
| 201 | |
| 202 | // 验证access token |
| 203 | func (this *BaseController) Prepare() { |
| 204 | //在微信小程序中:网络请求的 referer 是不可以设置的,格式固定为 https://servicewechat.com/{appid}/{version}/page-frame.html,其中 {appid} 为小程序的 appid,{version} 为小程序的版本号,版本号为 0 表示为开发版。 |
| 205 | appId := strings.ToLower(beego.AppConfig.DefaultString("appid", "")) |
| 206 | limitReferer := beego.AppConfig.DefaultBool("limitReferer", false) |
| 207 | if appId != "" && limitReferer && beego.AppConfig.String("runmode") != "dev" { // 限定请求的微信小程序的appid |
| 208 | prefix := fmt.Sprintf("https://servicewechat.com/%v/", appId) |
| 209 | if !strings.HasPrefix(strings.ToLower(this.Ctx.Request.Referer()), prefix) { |
| 210 | this.Response(http.StatusNotFound, "not found") |
| 211 | } |
| 212 | } |
| 213 | this.Token = this.Ctx.Request.Header.Get("Authorization") |
| 214 | this.Version = this.Ctx.Request.Header.Get("x-version") |
| 215 | |
| 216 | if !models.AllowVisitor && this.isLogin() == 0 { // 不允许游客访问,则除了部分涉及登录的API外,一律提示先登录 |
| 217 | allowAPIs := map[string]bool{ |
| 218 | beego.URLFor("CommonController.Login"): true, |
| 219 | beego.URLFor("CommonController.LoginByWechat"): true, |
| 220 | //beego.URLFor("CommonController.LoginBindWechat"): true, // 这个接口属于绑定信息的,属于注册接口。 |
| 221 | } |
| 222 | if _, ok := allowAPIs[this.Ctx.Request.URL.Path]; !ok { |
| 223 | this.Response(http.StatusBadRequest, messageMustLogin) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | if !models.AllowRegister { // 如果不允许注册,则不允许用户访问注册相关的接口,其他接口可以访问 |
| 228 | denyAPIs := map[string]bool{ |
| 229 | beego.URLFor("CommonController.LoginBindWechat"): true, // 这个接口属于绑定信息的,属于注册接口。 |
| 230 | beego.URLFor("CommonController.Register"): true, // 这个接口属于绑定信息的,属于注册接口。 |
| 231 | } |
| 232 | if _, ok := denyAPIs[this.Ctx.Request.URL.Path]; ok { |
| 233 | this.Response(http.StatusBadRequest, messageForbidRegister) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | } |
| 238 | |
| 239 | func (this *BaseController) isLogin() (uid int) { |
| 240 | return models.NewAuth().GetByToken(this.Token).Uid |