Ejemplo n.º 1
0
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
}
Ejemplo n.º 2
0
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
}
Ejemplo n.º 3
0
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)
}
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)
}
Ejemplo n.º 5
0
// Performs validation and combines errors from validation
// with errors from deserialization, then maps both the
// resulting struct and the errors to the context.
func validateAndMap(obj reflect.Value, context martini.Context, errors Errors, ifacePtr ...interface{}) {
	context.Invoke(Validate(obj.Interface()))
	errors = append(errors, getErrors(context)...)
	context.Map(errors)
	context.Map(obj.Elem().Interface())
	if len(ifacePtr) > 0 {
		context.MapTo(obj.Elem().Interface(), ifacePtr[0])
	}
}
Ejemplo n.º 6
0
// Performs validation and combines errors from validation
// with errors from deserialization, then maps both the
// resulting struct and the errors to the context.
func validateAndMap(obj reflect.Value, context martini.Context, errors *base.BindingErrors, ifacePtr ...interface{}) {
	context.Invoke(Validate(obj.Interface()))
	errors.Combine(getErrors(context))
	context.Map(*errors)
	context.Map(obj.Elem().Interface())
	if len(ifacePtr) > 0 {
		context.MapTo(obj.Elem().Interface(), ifacePtr[0])
	}
}
Ejemplo n.º 7
0
Archivo: post.go Proyecto: 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)
}
// 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)
}
Ejemplo n.º 9
0
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)
}
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)
}
Ejemplo n.º 11
0
//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)
}
Ejemplo n.º 12
0
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)
}
Ejemplo n.º 13
0
/*
 * 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)
}
Ejemplo n.º 14
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)
}
Ejemplo n.º 15
0
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)
}
Ejemplo n.º 16
0
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)
}
Ejemplo n.º 17
0
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)
}
Ejemplo n.º 18
0
// 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)
}
Ejemplo n.º 19
0
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)
}
Ejemplo n.º 20
0
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)
}
Ejemplo n.º 21
0
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)
}
Ejemplo n.º 22
0
// Performs validation and combines errors from validation
// with errors from deserialization, then maps both the
// resulting struct and the errors to the context.
func validateAndMap(val reflect.Value, context martini.Context, errors *Errors, ifacePtr ...interface{}) {
	context.Invoke(Validate(val.Interface()))
	context.Map(errors)
	target, _ := normalize(val, context)
	if target == nil {
		panic("binding: wrong return nil value")
	}
	context.Map(target)
	if len(ifacePtr) > 0 {
		for index, _ := range ifacePtr {
			context.MapTo(target, ifacePtr[index])
		}
	}
}
Ejemplo n.º 23
0
//ParseJsonBody is middleware to read the body of the http request, and bind it
//to the request object.
func ParseJsonBody(w http.ResponseWriter, r *http.Request, c martini.Context) {
	body := httpBody(r)

	var f interface{}
	if err := json.Unmarshal(body, &f); err != nil {
		log.Println("Receieved malformed JSON body")
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		w.Write([]byte("{'error':'Malformed JSON'}"))
	} else {
		m := f.(map[string]interface{})
		j := JsonBody(m)
		c.Map(&j)
	}
}
Ejemplo n.º 24
0
func pagination(req *http.Request, c martini.Context) {
	req.ParseForm()
	page, err := strconv.Atoi(req.FormValue("page"))
	if err != nil {
		page = 1
	}
	limit, err := strconv.Atoi(req.FormValue("limit"))
	if err != nil {
		limit = 20
	}
	c.Map(PageInfo{
		page:   page,
		limit:  limit,
		offset: (page - 1) * limit,
	})
}
Ejemplo n.º 25
0
Archivo: db.go Proyecto: klydel/dogfort
/*
Check Authorization token
*/
func AuthenticationMiddleware(req *http.Request, context martini.Context, r render.Render) {
	token := req.Header.Get("Authorization")

	if token == "" {
		r.Error(401)
	}

	uid, err := getUserUidFromToken(token)

	if err != nil {
		r.Error(401)
	} else {
		context.Map(*uid)
		context.Next()
	}
}
Ejemplo n.º 26
0
func ResolveApp(context martini.Context, res http.ResponseWriter, req *http.Request) {
	apiKey := req.Header.Get("API-KEY")

	if apiKey == "" {
		http.Error(res, "bad request", http.StatusBadRequest)
	} else {
		appEngineContext := appengine.NewContext(req)
		app, err := GetAppWithApiKey(apiKey, appEngineContext)

		if err != nil {
			http.Error(res, err.Error(), http.StatusBadRequest)
		} else {
			context.Map(app)
		}
	}
}
Ejemplo n.º 27
0
func AuthFunc(req *http.Request, session webSessions.Session, r render.Render, c martini.Context) bool {
	if strings.HasPrefix(req.RequestURI, "/api") || strings.HasPrefix(req.RequestURI, "/login") {
		return true
	}

	user := session.Get("auth_user")
	if user == nil {
		r.Redirect("/login", 302)
		return true
	}

	session.Set("auth_user", user)
	c.Map(user.(string))
	return true

}
Ejemplo n.º 28
0
func Auth(ctx martini.Context, req *http.Request, r render.Render, session sessions.Session, res http.ResponseWriter, f *fishhub.DBService) {
	db := f.DB.Copy()
	defer db.Close()
	userProfile := &user.User{}
	query := bson.M{"userid": session.Get("userid")}
	err := db.FindOne("users", query, userProfile)

	if err != nil {
		r.JSON(401, map[string]interface{}{
			"message":        "Unauthorized error",
			"classification": "UnauthorizedError",
		})
		return
	}
	ctx.Map(userProfile)
}
Ejemplo n.º 29
0
func EnsureAuth(session sessions.Session, r render.Render, req *http.Request, c martini.Context) {
	id, ok := session.Get("id").(int64)
	if !ok || id == 0 {
		session.AddFlash("warning: You must login first!")
		session.Set("previous_url", req.RequestURI)
		r.Redirect("/signin")
	} else if ok {
		var user models.User
		err := utils.ORM.First(&user, id).Error
		if err != nil {
			r.Error(500)
			return
		}
		c.Map(user)
	}
}
Ejemplo n.º 30
0
func AuthorizationAccountProvider(c appengine.Context, logger *Logger, request *http.Request, render render.Render, martiniContext martini.Context, appx *appx.Datastore) {
	authToken := extractAuthToken(request)

	if authToken == "" {
		render.Status(http.StatusUnauthorized)
		return
	}

	var currentAccount models.Account
	if err := appx.Query(models.Accounts.ByAuthToken(authToken)).Result(&currentAccount); err != nil {
		logger.Errorf("%v", err)
		render.Status(http.StatusUnauthorized)
		return
	}

	martiniContext.Map(&currentAccount)
}