コード例 #1
0
ファイル: web.go プロジェクト: BurntSushi/lcmweb
func recovery(
	c martini.Context,
	req *http.Request,
	ren render.Render,
	dec formDecoder,
) {
	defer func() {
		if r := recover(); r != nil {
			switch err := r.(type) {
			case jsonError:
				handleJsonError(err, ren)
			case authError:
				authenticate(err, dec, ren, req)
			case userError:
				ren.HTML(200, "error", m{
					"Message": formatMessage(err.Error()),
				})
			case csql.Error:
				ren.HTML(200, "error", m{
					"Message": formatMessage(err.Error()),
				})
			default:
				panic(r)
			}
		}
	}()
	c.Next()
}
コード例 #2
0
ファイル: web.go プロジェクト: BurntSushi/lcmweb
func webAuth(
	lg *log.Logger,
	c martini.Context,
	routes martini.Routes,
	params martini.Params,
	r *http.Request,
	w http.ResponseWriter,
	s *sessions.Session,
	ren render.Render,
	dec formDecoder,
	mdec multiDecoder,
) {
	userId := sessGet(s, sessionUserId)
	if len(userId) == 0 {
		panic(ae(""))
	}
	state := &web{
		lg: lg, c: c, routes: routes, params: params,
		r: r, w: w, s: s, ren: ren,
		decode: dec, multiDecode: mdec,
		user: findUserById(userId),
	}
	ren.Template().Funcs(template.FuncMap{
		"url": state.url,
	})
	c.Map(state)
}
コード例 #3
0
ファイル: middleware.go プロジェクト: ninnemana/API
func mapCart(c martini.Context, res http.ResponseWriter, r *http.Request) error {
	qs := r.URL.Query()
	var shopId string
	if qsId := qs.Get("shop"); qsId != "" {
		shopId = qsId
	} else if formId := r.FormValue("shop"); formId != "" {
		shopId = formId
	} else if headerId := r.Header.Get("shop"); headerId != "" {
		shopId = headerId
	}

	if shopId == "" {
		return fmt.Errorf("error: %s", "you must provide a shop identifier")
	}
	if !bson.IsObjectIdHex(shopId) {
		return fmt.Errorf("error: %s", "invalid shop identifier")
	}
	shop := cart.Shop{
		Id: bson.ObjectIdHex(shopId),
	}

	if shop.Id.Hex() == "" {
		return fmt.Errorf("error: %s", "invalid shop identifier")
	}

	if err := shop.Get(); err != nil {
		return err
	}
	if shop.Id.Hex() == "" {
		return fmt.Errorf("error: %s", "invalid shop identifier")
	}

	c.Map(&shop)
	return nil
}
コード例 #4
0
ファイル: middleware.go プロジェクト: ninnemana/API
func mapCartAccount(c martini.Context, res http.ResponseWriter, r *http.Request) error {

	auth := r.Header.Get("Authorization")
	token := strings.Replace(auth, "Bearer ", "", 1)

	cust, err := cart.AuthenticateAccount(token)
	if err != nil {
		return err
	}

	shop := cart.Shop{
		Id: cust.ShopId,
	}

	if shop.Id.Hex() == "" {
		return fmt.Errorf("error: %s", "invalid shop identifier")
	}

	if err := shop.Get(); err != nil {
		return err
	}
	if shop.Id.Hex() == "" {
		return fmt.Errorf("error: %s", "invalid shop identifier")
	}

	c.Map(&shop)
	c.Map(token)
	return nil
}
コード例 #5
0
ファイル: encoder.go プロジェクト: jcgarciam/go-wasab
// MapEncoder intercepts the request's URL, detects the requested format,
// and injects the correct encoder dependency for this request. It rewrites
// the URL to remove the format extension, so that routes can be defined
// without it.
func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) {
	// Get the format extension
	matches := rxExt.FindStringSubmatch(r.URL.Path)
	ft := ".json"
	if len(matches) > 1 {
		// Rewrite the URL without the format extension
		l := len(r.URL.Path) - len(matches[1])
		if strings.HasSuffix(r.URL.Path, "/") {
			l--
		}
		r.URL.Path = r.URL.Path[:l]
		ft = matches[1]
	}

	log.Println(r.URL.Path)

	// Inject the requested encoder
	switch ft {
	case ".xml":
		//c.MapTo(&xmlEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/xml")
	case ".text":
		//c.MapTo(&textEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	default:
		c.MapTo(&jsonEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/json")
	}
}
コード例 #6
0
func RequestLocationProvider(gaeContext appengine.Context, mContext martini.Context, request *http.Request) {
	locationCode := request.Header.Get("X-AppEngine-Country")

	location := locationFromCode(locationCode)

	gaeContext.Infof("Using location code: %v", location)
	mContext.Map(location)
}
コード例 #7
0
// AppengineContextProvider provides an injectable and namespaced
// instance of appengine.Context
func AppengineContextProvider(c martini.Context, req *http.Request) {
	gae := appengine.NewContext(req)
	namespace := appengine.ModuleName(gae)
	context, err := appengine.Namespace(gae, namespace)
	if err != nil {
		panic(err)
	}
	c.Map(context)
}
コード例 #8
0
ファイル: routes.go プロジェクト: danihodovic/backend-test
//Simple auth handler based on a global key. This may have to be rewritten...
func authHandler(r *http.Request, ctx martini.Context, ren render.Render) {
	log.Println(r.Header)
	if r.Header.Get("Authorization") != APIKey {
		ren.Text(http.StatusUnauthorized, "Invalid authorization")
		return
	}
	//Call the next handler
	ctx.Next()
}
コード例 #9
0
ファイル: post.go プロジェクト: jf/gwp
func Retrieve(c martini.Context, params martini.Params, r render.Render) {
	id, _ := strconv.Atoi(params["id"])
	post, err := retrieve(id)
	if err != nil {
		r.Error(404)
		return
	}
	c.Map(post)
}
コード例 #10
0
ファイル: auth.go プロジェクト: payallmoney/sharego
func Auth(session sessions.Session, c martini.Context, r render.Render) {
	v := session.Get("userid")
	fmt.Println(v)
	if v == nil {
		r.Redirect("/login")
	} else {
		c.Next()
	}
}
コード例 #11
0
ファイル: github.go プロジェクト: nquinlan/contribot
func gitHubAuthMiddleware(req *http.Request, res http.ResponseWriter, r render.Render, c martini.Context) {
	// Verify origin is GH
	template := make(map[string]string)
	template["contactUrl"] = os.Getenv("CONTACT_URL")
	template["contactValue"] = os.Getenv("CONTACT_VALUE")
	template["message"] = "There was an authenticating your account."
	err := req.ParseForm()
	if err != nil {
		log.Println(err)
		r.HTML(http.StatusBadRequest, "error", template)
		return
	}
	if len(req.Form["code"]) != 1 {
		r.HTML(http.StatusUnauthorized, "error", template)
		return
	}
	// If legit, attempt to get token
	payload := make(map[string]string)
	payload["client_id"] = os.Getenv("GITHUB_CLIENT_ID")
	payload["client_secret"] = os.Getenv("GITHUB_CLIENT_SECRET")
	payload["code"] = req.Form["code"][0]
	body, _ := json.Marshal(payload)
	ghReq, _ := http.NewRequest("POST", "https://github.com/login/oauth/access_token", bytes.NewReader(body))
	ghReq.Header.Add("Content-Type", acceptHeader)
	ghReq.Header.Add("Accept", acceptHeader)
	ghReq.Header.Add("User-Agent", userAgent)
	ghRes, err := http.DefaultClient.Do(ghReq)

	// check status code
	if err != nil {
		log.Println(err)
		r.HTML(http.StatusServiceUnavailable, "error", template)
		return
	}
	ghPayload, err := ioutil.ReadAll(ghRes.Body)
	if err != nil {
		log.Println(err)
		r.HTML(http.StatusInternalServerError, "error", template)
		return
	}
	var ghJSON map[string]interface{}
	err = json.Unmarshal(ghPayload, &ghJSON)
	if err != nil {
		log.Println(err)
		r.HTML(http.StatusInternalServerError, "error", template)
		return
	}
	token, ok := ghJSON["access_token"].(string)
	if !ok {
		r.HTML(http.StatusOK, "error", template)
		return
	}
	c.Map(token)
	c.Next()
	http.Redirect(res, req, "/award", http.StatusFound)
}
コード例 #12
0
ファイル: main.go プロジェクト: geoah/42minutes-server-api
func Authenticate(w http.ResponseWriter, r *http.Request, c martini.Context, enc encoder.Encoder) {
	db := GetDbSession()
	token := r.Header.Get("X-API-TOKEN")
	user := User{}
	err := db.SelectOne(&user, "select * from users where token=?", token)
	if err != nil {
		http.Error(w, "Auth Error", http.StatusUnauthorized)
	}
	c.Map(user)
}
コード例 #13
0
ファイル: oauth2.go プロジェクト: hoysoft/JexGO
func logoutHandle(f *Config, c martini.Context, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	s.Delete(keyToken)
	path := fmt.Sprintf("%s?client_id=%s&client_secret=%s", f.Endpoint.LogoutURL, f.ClientID, f.ClientSecret)
	utils.HttpGetString(path)
	//	fmt.Println("oauth logout result:",string(str))
	f.ClientID = ""
	f.ClientSecret = ""
	c.Invoke(Logout)
	http.Redirect(w, r, "/", 302)
}
コード例 #14
0
ファイル: server.go プロジェクト: kvannotten/projects
//The authorize middleware will search the session for a username
//if it doesnt find it, it will redirect to login
func authorize(w http.ResponseWriter, r *http.Request, session sessions.Session, c martini.Context) {
	username := session.Get("username")
	if username == nil {
		http.Redirect(w, r, "/login", http.StatusFound)
	}
	//if we found the user, let's create a new user struct and map it into the request context
	user := &User{}
	user.Username = username.(string)
	c.Map(user)
}
コード例 #15
0
ファイル: graceful.go プロジェクト: jonaz/magicmirror
func (c *ConnectionLimit) Handler(ctx martini.Context, rw http.ResponseWriter) { // {{{
	if atomic.AddInt32(&c.numConnections, 1) > c.limit {
		http.Error(rw, "maximum connections exceeded", http.StatusServiceUnavailable)
		atomic.AddInt32(&c.numConnections, -1)
		return
	}

	ctx.Next()
	atomic.AddInt32(&c.numConnections, -1)
} // }}}
コード例 #16
0
func ExternalServiceAuthorizationProvider(ds *appx.Datastore, martiniContext martini.Context, account *models.Account) {
	authorization := &models.ExternalServiceAuthorization{}
	authorization.SetParentKey(account.Key())

	if err := ds.Load(authorization); err != nil {
		panic(err)
	}

	martiniContext.Map(authorization)
}
コード例 #17
0
// ContentMiddleware is a Martini handler which specifies the proper
// serialization (XML/JSON) depending on the "Content-Type" header
// presented.
func ContentMiddleware(c martini.Context, w http.ResponseWriter, r *http.Request) {
	switch r.Header.Get("Content-Type") {
	case "application/xml":
		c.MapTo(encoder.XmlEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/xml; charset=utf-8")
	default:
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	}
}
コード例 #18
0
ファイル: auth.go プロジェクト: serash/YunYun
/*
 * Web functions
 */
func RequireLogin(rw http.ResponseWriter, req *http.Request, s sessions.Session,
	db_ *mgo.Database, c martini.Context) {
	user, err := db.GetUserById(bson.ObjectIdHex(s.Get("userId").(string)), db_)
	if err != nil {
		fmt.Println(err)
		http.Redirect(rw, req, PAGE_LOGIN, http.StatusFound)
		return
	}
	c.Map(user)
}
コード例 #19
0
// Middleware ...
func Middleware(ctx martini.Context, r *http.Request, w http.ResponseWriter) {
	sessionID := ensureCookie(r, w)
	session := sessionStore.Get(sessionID)

	ctx.Map(session)

	ctx.Next()

	sessionStore.Set(session)
}
コード例 #20
0
ファイル: rest_api.go プロジェクト: ngaut/tyrant
func filter(req *http.Request, c martini.Context) {
	req.ParseForm()
	m := make(FilterInfo)
	for k, v := range req.Form {
		if strings.HasPrefix(k, "f_") {
			field := strings.Split(k, "f_")[1]
			m[field] = v[0]
		}
	}
	c.Map(m)
}
コード例 #21
0
ファイル: main.go プロジェクト: jovon/cf_martini_api
func RequireLogin(rw http.ResponseWriter, req *http.Request,
	s sessions.Session, db *sql.DB, c martini.Context) {
	user := &User{}
	err := db.QueryRow("select name, email from users where id=?", s.Get("userId")).Scan(&user.Name, &user.Email)

	if err != nil {
		http.Redirect(rw, req, "/login", http.StatusFound)
		return
	}

	c.Map(user)
}
コード例 #22
0
ファイル: server.go プロジェクト: ukitazume/bunkai
func RequireLogin(ren render.Render, req *http.Request, s sessions.Session, dbmap *gorp.DbMap, c martini.Context) {

	var usr User
	err := dbmap.SelectOne(&usr, "SELECT * from users WHERE id = $1", s.Get("userId"))

	if err != nil {
		ren.JSON(http.StatusForbidden, nil)
		return
	}

	c.Map(usr)
}
コード例 #23
0
func AppengineContextProvider(c martini.Context, request *http.Request) {
	gae := appengine.NewContext(request)
	namespace := appengine.ModuleName(gae)

	context, err := appengine.Namespace(gae, namespace)

	if err != nil {
		panic(fmt.Sprintf("Could not create GAE context: %v", err))
	}

	c.MapTo(context, (*appengine.Context)(nil))
}
コード例 #24
0
ファイル: middleware.go プロジェクト: PandoCloud/pando-cloud
// get device identifier
func CheckDeviceIdentifier(context martini.Context, params martini.Params, req *http.Request, r render.Render) {
	identifier := params["identifier"]

	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceByIdentifier", identifier, device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
		return
	}

	context.Map(device)
}
コード例 #25
0
ファイル: webcmd.go プロジェクト: cfstras/cfmedias
func mapArgs(c martini.Context, params martini.Params, r *http.Request,
	w http.ResponseWriter) {
	if err := r.ParseForm(); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintln(w, "bad request:", err)
		return
	}

	var ctx core.CommandContext
	ctx.Cmd = params["cmd"]
	ctx.Args = core.ArgMap(r.Form)
	c.Map(&ctx)
}
コード例 #26
0
ファイル: binding.go プロジェクト: jenchik/binding
func callNormalizeBinding(val reflect.Value, context martini.Context) (interface{}, error) {
	obj := val.Interface()
	if m := val.MethodByName("NormalizeBinding"); m.IsValid() {
		results, err := context.Invoke(m.Interface())
		if err != nil {
			return nil, err
		}
		if len(results) > 0 {
			obj = results[0].Interface()
		}
	}
	return obj, nil
}
コード例 #27
0
ファイル: register.go プロジェクト: ts25504/MuShare
func Register(db *gorm.DB, c martini.Context, body *user.Account, rw http.ResponseWriter) {
	if db == nil {
		panic("db is not exist")
	}
	account := Account{DB: db}
	res := account.Register(body)
	if res.Status == http.StatusOK {
		c.Map(res.Body)
		c.Next()
	}

	Response(res, rw)
}
コード例 #28
0
ファイル: web.go プロジェクト: BurntSushi/lcmweb
func jsonResp(c martini.Context) {
	defer func() {
		if r := recover(); r != nil {
			if err, ok := r.(error); ok {
				if _, ok := err.(jsonError); ok {
					panic(r)
				} else {
					panic(jsonError{err})
				}
			}
		}
	}()
	c.Next()
}
コード例 #29
0
ファイル: main.go プロジェクト: qapi/goblog-playground
func RequireLogin(s sessions.Session, db *sql.DB, c martini.Context, ren render.Render, returnUrl string) {
	user := &User{}
	err := db.QueryRow("select name, email from appuser where id=$1", s.Get("userId")).Scan(&user.Name, &user.Email)

	s.Set("returnUrl", returnUrl)

	if err != nil {
		ren.Redirect("/login")
		return
	}

	//map user to the context
	c.Map(user)
}
コード例 #30
0
ファイル: encoding.go プロジェクト: ninnemana/API
func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) {
	accept := r.Header.Get("Accept")
	if accept == "*/*" {
		accept = r.Header.Get("Content-Type")
	}
	matches := rxAccept.FindStringSubmatch(accept)

	dt := "json"
	if len(matches) == 1 {
		dt = matches[0]
	}
	switch dt {
	case "xml":

		c.MapTo(XmlEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/xml")
	case "plain":
		c.MapTo(TextEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "text/plain")
	case "html":
		c.MapTo(TextEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "text/html")
	default:
		c.MapTo(JsonEncoder{}, (*Encoder)(nil))
		w.Header().Set("Content-Type", "application/json")
	}
}