1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| package routers
import ( "net/http" "strings"
"github.com/astaxie/beego" "github.com/astaxie/beego/context" "github.com/chuanshuo843/12306_server/controllers" "github.com/chuanshuo843/12306_server/utils" )
func init() { ns := beego.NewNamespace("/v1", beego.NSRouter("/auth/login", &controllers.UserController{}, "Post:Login"), beego.NSRouter("/auth/verifyCode", &controllers.UserController{}, "Get:VerifyCode"), beego.NSRouter("/auth/init", &controllers.UserController{}, "Get:InitLogin"), beego.NSNamespace("/schedule", beego.NSBefore(Auth), beego.NSInclude( &controllers.ScheduleController{}, ), ), beego.NSNamespace("/station", beego.NSBefore(Auth), beego.NSInclude( &controllers.StationController{}, ), ), beego.NSNamespace("/passenger", beego.NSBefore(Auth), beego.NSInclude( &controllers.PassengerController{}, ), ), beego.NSNamespace("/order", beego.NSBefore(Auth), beego.NSInclude( &controllers.OrderController{}, ), ), ) beego.AddNamespace(ns) }
func Auth(ctx *context.Context) { if !ctx.Input.Is("OPTIONS") { authString := ctx.Input.Header("Authorization") if authString == "" { AllowCross(ctx) return } kv := strings.Split(authString, " ") if len(kv) != 2 || kv[0] != "Bearer" { AllowCross(ctx) return } token := kv[1] jwt := utils.InitJwt() if !jwt.Checkd(token) { AllowCross(ctx) return } } }
func AllowCross(ctx *context.Context) { ctx.Output.Header("Cache-Control", "no-store") ctx.Output.Header("Access-Control-Allow-Origin", "*") ctx.Output.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS") ctx.Output.Header("Access-Control-Allow-Headers", "Authorization") ctx.Output.Header("WWW-Authenticate", `Bearer realm="`+beego.AppConfig.String("HostName")+`" error="Authorization" error_description="invalid Authorization"`) http.Error(ctx.ResponseWriter, "Unauthorized", 401) }
|