Пример #1
0
func Handler(response http.ResponseWriter, request *http.Request) {
	fmt.Println(request.Method)
	fmt.Println("Entrou no handler")
	fmt.Println(len(request.Cookies()))
	token, err := request.Cookie("token")
	fmt.Println(token.Value, err)
	data := url.Values{}
	data.Set("access_token", token.Value)
	//req = http.NewRequest("POST", "https://www.googleapis.com/oauth2/v1/tokeninfo", nil)
	resp, err := http.Post("https://www.googleapis.com/oauth2/v1/tokeninfo", "application/x-www-form-urlencoded", bytes.NewBufferString(data.Encode()))
	//req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param="+token)
	//http.
	var retorno ValidaToken
	json.NewDecoder(resp.Body).Decode(&retorno)
	fmt.Println(retorno.Error, retorno.Email)

	switch request.Method {
	case "GET":
		provas := Provas()
		fmt.Println(provas)
		js, _ := json.MarshalIndent(provas, " ", "   ")
		response.Write(js)

	case "POST":
		var prova Prova
		json.NewDecoder(request.Body).Decode(&prova)
		err := Insere(&prova)
		fmt.Println(err)
	}
}
Пример #2
0
func apiAuthenticator(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	logrus.Debugf("%#v", r.Header)
	policyRequest, err := http.NewRequest("GET", CATTLE_URL_API_POLICY, nil)
	if err != nil {
		panic(err)
	}
	policyRequest.Header.Set("Accept", "application/json")
	for _, cookie := range r.Cookies() {
		if cookie.Name != "CSRF" {
			policyRequest.AddCookie(cookie)
		}
	}
	resp, err := http.DefaultClient.Do(policyRequest)
	if err != nil {
		panic(err)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	policies := &Policies{}
	err = json.Unmarshal(body, policies)
	if err != nil {
		panic(err)
	}
	policy := policies.Data[0]
	logrus.Debugf("Policy: \n %#v", policy)
	context := api.GetApiContext(r)
	if context == nil {
		panic(fmt.Errorf("No context found:%v", r.URL.RawPath))
	}
	context.Policy = policy
	w.Write(body)
}
Пример #3
0
func (this HTTPTranslator) BuildRequestDefinitionFromHTTP(req *http.Request) definition.Request {

	res := definition.Request{}
	res.Method = req.Method
	res.Path = req.URL.Path
	res.Headers = make(definition.Values)
	for header, values := range req.Header {
		if header != "Cookie" {
			res.Headers[header] = values
		}
	}

	res.Cookies = make(definition.Cookies)
	for _, cookie := range req.Cookies() {
		res.Cookies[cookie.Name] = cookie.Value
	}

	res.QueryStringParameters = make(definition.Values)
	for name, values := range req.URL.Query() {
		res.QueryStringParameters[name] = values
	}

	body, _ := ioutil.ReadAll(req.Body)
	res.Body = string(body)
	return res
}
Пример #4
0
// newContext returns a new caveat-checking context
// for the client making the given request.
func (h *handler) newContext(req *http.Request, operation string) *context {
	// Determine the current logged-in user, if any.
	var username string
	for _, c := range req.Cookies() {
		if c.Name == cookieUser {
			// TODO could potentially allow several concurrent
			// logins - caveats asking about current user privilege
			// could be satisfied if any of the user names had that
			// privilege.
			username = c.Value
			break
		}
	}
	if username == "" {
		log.Printf("not logged in")
	} else {
		log.Printf("logged in as %q", username)
	}
	return &context{
		handler:      h,
		req:          req,
		declaredUser: username,
		operation:    operation,
	}
}
Пример #5
0
// ServeHTTP handles HTTP requests for the server.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	buf := bytes.Buffer{}
	_, err := buf.ReadFrom(req.Body)
	if err != nil {
		// TODO: log and return JSON-RPC response?
		panic(err)
	}

	headers := Headers{
		Request:  req.Header,
		Cookies:  req.Cookies(),
		Response: make(map[string][]string),
	}

	resp := s.InvokeBytes(headers, buf.Bytes())
	w.Header().Set("Content-Type", s.ser.MimeType())

	for k, v := range headers.Response {
		for _, s := range v {
			w.Header().Add(k, s)
		}
	}

	// TODO: log err?
	_, err = w.Write(resp)
}
Пример #6
0
func (c *Cache) Get(request *http.Request, breakPoints []int64) (info *ImageInfo, err error) {

	cookie := getFoomoMediaClientInfoCookie(request.Cookies(), breakPoints)
	key := cookie.String() + ":" + request.URL.Path
	info, ok := c.Directory[key]
	if ok && time.Now().Unix() > info.Expires {
		log.Println("that image expired - getting a new one", info.Expires, time.Now())
		ok = false
		info = nil
		delete(c.Directory, key)
	}
	if ok == false {
		imageRequest := NewImageRequest(key, request, cookie)
		err := imageRequest.execute(c)
		if err != nil {
			return nil, err
		}
		info = imageRequest.ImageInfo
		if len(info.Etag) > 0 {
			info.Filename = c.Foomo.GetModuleCacheDir("Foomo.Media") + "/img-" + info.Etag
			if fileExists(info.Filename) {
				c.Directory[key] = info
			} else {
				return nil, err
			}
		}
	}
	return info, err
}
Пример #7
0
func getCookies(request http.Request) map[string]interface{} {
	cookies := make(map[string]interface{})
	for _, cookie := range request.Cookies() {
		cookies[cookie.Name] = cookie.Value
	}
	return cookies
}
Пример #8
0
// Add adds a new shorturl
func (view View) Add(w http.ResponseWriter, req *http.Request) {
	url := req.FormValue("url")
	if url == "" {
		http.Redirect(w, req, "/", http.StatusFound)
		return
	}
	host := getIP(req)
	if err := checkAllowed(req, url, host); err != nil {
		data := map[string]interface{}{
			csrf.TemplateTag: csrf.TemplateField(req),
			"Error":          err,
		}
		view.renderTemplate(w, "index", data)
		return
	}
	clientid := getClientID(req.Cookies())
	if clientid == "" {
		http.Error(w, "Failed to add shorturl", http.StatusForbidden)
		return
	}
	s, err := Add(view.DB, url, host, clientid)
	if err != nil {
		log.Printf("Failed to add (%s)", err)
		http.Error(w, "Failed to add short url", http.StatusInternalServerError)
		return
	}
	http.Redirect(w, req, s.PreviewURL(), http.StatusFound)
}
Пример #9
0
func PayPalPaymentExecute(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	pp.Println(r.Header)
	pp.Println(r.Cookies())

	buf := bytes.NewBufferString(fmt.Sprintf("{ \"payer_id\" : \"%s\"}", r.FormValue("PayerID")))
	req, err := http.NewRequest("POST", fmt.Sprintf("https://api.sandbox.paypal.com/v1/payments/payment/%s/execute/", r.FormValue("paymentId")), buf)
	if err != nil {
		log.Fatalln(err)
		renderer.JSON(w, 400, err.Error())
		return
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", fmt.Println("Bearer %s", authToken))

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatalln(err)
		renderer.JSON(w, 400, err.Error())
		return
	}
	defer res.Body.Close()

	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatalln(err)
		renderer.JSON(w, 400, err.Error())
		return
	}

	fmt.Println(string(data))

	http.Redirect(w, r, "/payment/done", 302)
}
Пример #10
0
// HandleWithSession should handle all situations where we don't have an email address
func addComplaintHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	cdb := complaintdb.NewDB(ctx)

	cdb.Debugf("ac_001", "num cookies: %d", len(r.Cookies()))
	for _, c := range r.Cookies() {
		cdb.Debugf("ac_001", "cookie: %s", c)
	}
	cdb.Debugf("ac_001a", "Cf-Connecting-Ip: %s", r.Header.Get("Cf-Connecting-Ip"))
	reqBytes, _ := httputil.DumpRequest(r, true)
	cdb.Debugf("ac_002", "req: %s", reqBytes)

	sesh, _ := GetUserSession(ctx)
	cdb.Debugf("ac_003", "have email")

	complaint := form2Complaint(r)
	//complaint.Timestamp = complaint.Timestamp.AddDate(0,0,-3)
	cdb.Debugf("ac_004", "calling cdb.ComplainByEmailAddress")
	if err := cdb.ComplainByEmailAddress(sesh.Email, &complaint); err != nil {
		cdb.Errorf("cdb.Complain failed: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	cdb.Debugf("ac_900", "all done, about to redirect")
	http.Redirect(w, r, "/", http.StatusFound)
}
Пример #11
0
Файл: web.go Проект: ginashi/web
func GetSecureCookie(r *http.Request, s *Server, name string) (string, bool) {
	for _, cookie := range r.Cookies() {
		if cookie.Name != name {
			continue
		}

		parts := strings.SplitN(cookie.Value, "|", 3)

		val := parts[0]
		timestamp := parts[1]
		sig := parts[2]

		if getCookieSig(s.Config.CookieSecret, []byte(val), timestamp) != sig {
			return "", false
		}

		ts, _ := strconv.ParseInt(timestamp, 0, 64)

		if time.Now().Unix()-31*86400 > ts {
			return "", false
		}

		buf := bytes.NewBufferString(val)
		encoder := base64.NewDecoder(base64.StdEncoding, buf)

		res, _ := ioutil.ReadAll(encoder)
		return string(res), true
	}
	return "", false
}
Пример #12
0
func newRequest(hr *http.Request, hc http.ResponseWriter) *Request {

	remoteAddr, _ := net.ResolveTCPAddr("tcp", hr.RemoteAddr)

	maps := make(map[string]string)
	for _, v := range hr.Cookies() {
		maps[v.Name] = v.Value
	}

	req := Request{
		Method:     hr.Method,
		URL:        hr.URL,
		Proto:      hr.Proto,
		ProtoMajor: hr.ProtoMajor,
		ProtoMinor: hr.ProtoMinor,
		Headers:    hr.Header,
		Body:       hr.Body,
		Close:      hr.Close,
		Host:       hr.Host,
		Referer:    hr.Referer(),
		UserAgent:  hr.UserAgent(),
		FullParams: hr.Form,
		Cookie:     hr.Cookies(),
		Cookies:    maps,
		RemoteAddr: remoteAddr.IP.String(),
		RemotePort: remoteAddr.Port,
	}
	return &req
}
Пример #13
0
//// delete tweet
//func delTweet(ctx context.Context, username string) (*Profile, error) {
//
//}
// check cookie and get Logged-in status
func checkLoggedInStats(req *http.Request) bool {
	log.Infof(appengine.NewContext(req), "COOKIE: %v", req.Cookies())
	if cookie, err := req.Cookie("logged_in"); err == nil {
		return cookie.Value == "true"
	}
	return false
}
Пример #14
0
func (m *Middleware) getPossibleRequestIDs(r *http.Request) []string {
	rv := []string{}
	for _, cookie := range r.Cookies() {
		if !strings.HasPrefix(cookie.Name, "saml_") {
			continue
		}
		log.Printf("getPossibleRequestIDs: cookie: %s", cookie.String())
		token, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) {
			secretBlock, _ := pem.Decode([]byte(m.ServiceProvider.Key))
			return secretBlock.Bytes, nil
		})
		if err != nil || !token.Valid {
			log.Printf("... invalid token %s", err)
			continue
		}
		claims := token.Claims.(jwt.MapClaims)
		rv = append(rv, claims["id"].(string))
	}

	// If IDP initiated requests are allowed, then we can expect an empty response ID.
	if m.AllowIDPInitiated {
		rv = append(rv, "")
	}

	return rv
}
Пример #15
0
func handler(w http.ResponseWriter, r *http.Request) {

	fmt.Fprintf(w, "URL: %s\n", r.URL.Path)
	fmt.Fprintf(w, "Method: %s\n", r.Method)
	fmt.Fprintf(w, "Protocol: %s, Major: %v, Minor: %v\n", r.Proto, r.ProtoMajor, r.ProtoMinor)
	fmt.Fprintf(w, "Host: %s\n", r.Host)
	fmt.Fprintf(w, "Remote Address: %s\n", r.RemoteAddr) // Remote Address that sent this request (IP:port)

	fmt.Fprintf(w, "Headers: %v\n", r.Header)
	fmt.Fprintf(w, "User Agent: %s\n", r.UserAgent()) // As set in the header
	fmt.Fprintf(w, "Referrer: %s\n", r.Referer())     // As set in the header

	// Form data (GET, POST)
	r.ParseForm() // r.Form will be filled by this function
	// r.Form contain GET, POST, PUT paramters all combined
	fmt.Fprintf(w, "URL Parameters: %v\n", r.Form) // Parsed Form data

	// Try this: http://localhost:8080/?test=asdasd&test=qwerty
	// NOTE: The duplicate parameters are appended instead of overwritten to Form..
	// However, FormValue() returns the 1st found value, which is generally preferable
	fmt.Fprintf(w, "Test Parameters: %v, %v\n", r.Form["test"], r.FormValue("test"))

	// TODO: To distinguish GET and POST parameters, @see http://code.google.com/p/go/issues/detail?id=3630

	// Reading cookie
	fmt.Fprintf(w, "All cookies: %v\n", r.Cookies()) // Get all cookies
	testCookie, err := r.Cookie("test")              // Get cookie with the given name. err = ErrNoCookie, if cookie not found
	fmt.Fprintf(w, "Cookie with name test: %v, err = %v, isErrNoCookie=%v\n", testCookie, err, err == http.ErrNoCookie)
}
Пример #16
0
func (s *server) getComics(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	req, err := http.NewRequest("GET", COMIC_ROCKET_COMICS_URL, nil)
	if err != nil {
		http.Error(w, err.Error(), 503)
		return
	}
	req.Header = r.Header
	client := http.Client{}
	client.Jar, _ = cookiejar.New(nil)
	u, _ := url.Parse(COMIC_ROCKET_COMICS_URL)
	client.Jar.SetCookies(u, r.Cookies())
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), 503)
		return
	}

	var comics []*Comic
	if err := json.NewDecoder(resp.Body).Decode(&comics); err != nil {
		http.Error(w, err.Error(), 503)
		return
	}

	if err := s.annotateComics(comics); err != nil {
		http.Error(w, err.Error(), 503)
		return
	}

	json.NewEncoder(w).Encode(comics)
}
Пример #17
0
func getCookie(r *http.Request, name string) string {
	for _, c := range r.Cookies() {
		if c.Name == name {
			return c.Value
		}
	}
	return ""
}
Пример #18
0
func (b *base) getHttpCookie(r *http.Request) map[string]string {
	c := map[string]string{}
	for _, ck := range r.Cookies() {
		c[ck.Name], _ = url.QueryUnescape(ck.Value)
	}

	return c
}
Пример #19
0
func (p *MemoryProvider) getCookieId(r *http.Request) string {
	for _, c := range r.Cookies() {
		if c.Name == p.CookieName {
			return c.Value
		}
	}
	return ""
}
Пример #20
0
// given an http.Request r, returns the username associated with the given
// request, as determined with an extremely unsafe cookie.  Returns an empty
// string if the user is not logged in.
func ParseUsername(r *http.Request) string {
	for _, c := range r.Cookies() {
		if c.Name == "username" {
			return c.Value
		}
	}
	return ""
}
Пример #21
0
func findcookie(r *http.Request, zn string) (int, string) {
	for i, cookie := range r.Cookies() {
		if cookie.Name == zn {
			return i, cookie.Value
		}
	}
	return -1, ""
}
Пример #22
0
func getSessionID(request *http.Request) string {
	for _, c := range request.Cookies() {
		if c.Name == "jsessionid" {
			return c.Value
		}
	}
	return ""
}
Пример #23
0
func pullCookie(r *http.Request) string {
	//get the cookie which has necessary game data
	n := "" //putting the player's name in here
	for _, cookie := range r.Cookies() {
		n = cookie.Name
	}
	return n
}
Пример #24
0
func PaymentDone(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	pp.Println(r.Form)
	pp.Println(r.Header)
	pp.Println(r.Cookies())

	w.Write([]byte("OK"))
}
Пример #25
0
func (interrogator *RequestInterrogator) InterrogateRequest(request *http.Request) map[string]string {
	params := make(map[string]string)

	queryParams := interrogator.interrogateParams(request.URL.Query())
	templateParams := interrogator.interrogatePath(request.URL.Path)
	pageUrl := getPageUrl(request)

	for key, value := range queryParams {
		params["param:"+key] = value
	}

	for key, value := range templateParams {
		params["param:"+key] = value
	}

	for key, value := range request.URL.Query() {
		queryValues := value[0]
		for _, val := range value[1:] {
			queryValues = queryValues + "," + val
		}
		params["query:"+key] = queryValues
	}

	for key, value := range request.Header {
		headerValues := value[0]
		for _, val := range value[1:] {
			headerValues = headerValues + "," + val
		}
		params["header:"+strings.ToLower(key)] = headerValues
	}

	for _, value := range request.Cookies() {
		params["cookie:"+value.Name] = value.Value
	}

	if interrogator.configCdn != nil && interrogator.configCdn.URL != "" {
		params["cdn:url"] = interrogator.configCdn.URL
	}

	params["server:local"] = interrogator.configParams.Servers.Local

	//TODO: Fix Environment being missing
	params["environment"] = "development"

	params["url:href"] = pageUrl

	encodedParams := make(map[string]string)
	for key, value := range params {
		encodedValue, _ := util.EncodeUrl(value)
		encodedParams[key+":encoded"] = encodedValue
	}

	for key, value := range encodedParams {
		params[key] = value
	}

	return params
}
Пример #26
0
func (dispatcher *Dispatcher) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
	// Keeping client's cookie around because we want to re-use its name
	var clientCookie *http.Cookie
	for _, c := range request.Cookies() {
		clientCookie = c
		break
	}
	if clientCookie == nil {
		log.Println("Cookie is not present in the HTTP request")
		dispatcher.terminateConnection(responseWriter, request)
		return
	}

	if request.Method != "POST" {
		log.Printf("unexpected request type: %s", request.Method)
		dispatcher.terminateConnection(responseWriter, request)
		return
	}

	for key, value := range request.Header {
		if strings.Contains(strings.ToLower(key), "x-online-host") {
			log.Printf("X-Online-Host: %s %+v", key, value)
			dispatcher.terminateConnection(responseWriter, request)
			return
		}
	}

	sessionKey, session, err := dispatcher.GetSession(request, clientCookie.Value)
	if err != nil {
		log.Printf("GetSession: %s", err)
		dispatcher.terminateConnection(responseWriter, request)
		return
	}

	sessionCookie := &http.Cookie{Name: clientCookie.Name, Value: sessionKey}

	err = dispatcher.relayPayload(sessionCookie, session, responseWriter, request)
	if err != nil {
		log.Printf("dispatch: %s", err)
		dispatcher.terminateConnection(responseWriter, request)
		dispatcher.CloseSession(sessionKey)
		return
	}

	/*
		NOTE: this code cleans up session resources quickly (when the
		      peer closes its persistent connection) but isn't
		      appropriate for the fronted case since the front doesn't
		      necessarily keep a persistent connection open.

		notify := responseWriter.(http.CloseNotifier).CloseNotify()

		go func() {
			<-notify
			dispatcher.CloseSession(cookie)
		}()
	*/
}
Пример #27
0
func DeleteStartsWith(w http.ResponseWriter, r *http.Request, pre string) {
	for _, cookie := range r.Cookies() {
		if strings.HasPrefix(UrlDec(cookie.Name), pre) {
			cookie.Expires = time.Now()
			cookie.MaxAge = -1
			http.SetCookie(w, cookie)
		}
	}
}
Пример #28
0
func GetStartsWith(r *http.Request, pre string) []Cook {
	var cookies []*http.Cookie
	for _, cookie := range r.Cookies() {
		if strings.HasPrefix(UrlDec(cookie.Name), pre) {
			cookies = append(cookies, cookie)
		}
	}
	return getAll(cookies)
}
Пример #29
0
// XssFullCookies is a wrapper around standard handler (non-filtered output echo)
// but requires the presence of a cookie with value "awesome"
func XssFullCookies(w http.ResponseWriter, r *http.Request) *LabResp {
	for _, ck := range r.Cookies() {
		if strings.Contains(ck.Value, "awesome") {
			return DoLabTestStandard(w, r)
		}
	}
	return &LabResp{Err: errors.New("Sorry your cookies are no good - please put the word awesome into a cookie value and try again."),
		Code: http.StatusForbidden}
}
Пример #30
0
func getCookie(w http.ResponseWriter, r *http.Request) {
	c1, err := r.Cookie("first_cookie")
	if err != nil {
		fmt.Fprintln(w, "Cannot get the first cookie")
	}
	cs := r.Cookies()
	fmt.Fprintln(w, c1)
	fmt.Fprintln(w, cs)
}