Exemple #1
0
func handleDeleteForm(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	_, kind := path.Split(r.URL.Path)
	key := DefaultMaster.delegator.(DelegatorBroadcaster).KeyFromForm(r.Form)
	ser := DefaultMaster.delegator.Delegate(kind)
	keys := ser.Keys()
	n := ser.Init()
	for _, v := range keys {
		if v != key {
			n = n.Insert(ser.At(v))
		}
	}
	ser.All(n)
	s := ser.At(key).(SerialSender)
	DefaultMaster.Delete(s)
	out := bytes.NewBufferString("")
	host := s.Host()
	if host != "" {
		DefaultMaster.save(out, s)
		http.Post("http://"+host+DefaultMaster.deletePattern+kind, "application/octet-stream", out)
	} else {
		bc := DefaultMaster.delegator.(DelegatorBroadcaster)
		for _, h := range bc.Hosts() {
			out = bytes.NewBufferString("")
			DefaultMaster.save(out, s)
			http.Post("http://"+h+DefaultMaster.deletePattern+kind, "application/octet-stream", out)
		}
	}
	DefaultMaster.Logger.Printf("%v erfolgreich gelöscht", s.Log())
	redir := "http://" + r.Host + r.FormValue("Redir")
	w.SetHeader("Location", redir)
	w.WriteHeader(302)
}
Exemple #2
0
func handleVerify(conn http.ResponseWriter, req *http.Request) {
	if !(req.Method == "POST" && req.URL.Path == "/camli/sig/verify") {
		httputil.BadRequestError(conn, "Inconfigured handler.")
		return
	}

	req.ParseForm()
	sjson := req.FormValue("sjson")
	if sjson == "" {
		httputil.BadRequestError(conn, "Missing sjson parameter.")
		return
	}

	m := make(map[string]interface{})

	vreq := jsonsign.NewVerificationRequest(sjson, pubKeyFetcher)
	if vreq.Verify() {
		m["signatureValid"] = 1
		m["verifiedData"] = vreq.PayloadMap
	} else {
		errStr := vreq.Err.String()
		m["signatureValid"] = 0
		m["errorMessage"] = errStr
	}

	conn.WriteHeader(http.StatusOK) // no HTTP response code fun, error info in JSON
	httputil.ReturnJson(conn, m)
}
Exemple #3
0
func handleReplaceForm(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	_, kind := path.Split(r.URL.Path)
	ser := DefaultMaster.delegator.Delegate(kind).(SerializerFormParser)
	s := ser.NewFromForm(r.Form)
	if s == nil {
		r.Form = nil
		w.SetHeader("Location", r.Referer)
		w.WriteHeader(302)
		return
	}
	ser.Replace(s)
	DefaultMaster.Save(s)
	out := bytes.NewBufferString("")
	host := s.Host()
	if host != "" {
		DefaultMaster.save(out, s)
		http.Post("http://"+host+DefaultMaster.replacePattern+kind, "application/octet-stream", out)
	} else {
		bc := DefaultMaster.delegator.(DelegatorBroadcaster)
		for _, h := range bc.Hosts() {
			out = bytes.NewBufferString("")
			DefaultMaster.save(out, s)
			http.Post("http://"+h+DefaultMaster.replacePattern+kind, "application/octet-stream", out)
		}
	}
	DefaultMaster.Logger.Printf("%v erfolgreich modifiziert", s.Log())
	redir := "http://" + r.Host + r.FormValue("Redir")
	w.SetHeader("Location", redir)
	w.WriteHeader(302)
}
Exemple #4
0
func join(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	r.ParseForm()
	// TODO check table arg
	state, err := joinTable(c, r.Form["table"][0], u.String())
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	var b []byte
	b, err = json.Marshal(state)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "%s", b)
}
Exemple #5
0
// Returns a map of all of the oauth_* (including signature) parameters for the
// given request, and the signature base string used to generate the signature.
func (s *HmacSha1Signer) GetOAuthParams(request *http.Request, clientConfig *ClientConfig, userConfig *UserConfig, nonce string, timestamp string) (map[string]string, string) {
	request.ParseForm()
	oauthParams := map[string]string{
		"oauth_consumer_key":     clientConfig.ConsumerKey,
		"oauth_nonce":            nonce,
		"oauth_signature_method": "HMAC-SHA1",
		"oauth_timestamp":        timestamp,
		"oauth_version":          "1.0",
	}
	tokenKey, tokenSecret := userConfig.GetToken()
	if tokenKey != "" {
		oauthParams["oauth_token"] = tokenKey
	}
	signingParams := map[string]string{}
	for key, value := range oauthParams {
		signingParams[key] = value
	}
	for key, value := range request.URL.Query() {
		//TODO: Support multiple parameters with the same name.
		signingParams[key] = value[0]
	}
	for key, value := range request.Form {
		//TODO: Support multiple parameters with the same name.
		signingParams[key] = value[0]
	}
	signingUrl := fmt.Sprintf("%v://%v%v", request.URL.Scheme, request.URL.RawAuthority, request.URL.Path)
	signatureParts := []string{
		request.Method,
		url.QueryEscape(signingUrl),
		s.encodeParameters(signingParams)}
	signatureBase := strings.Join(signatureParts, "&")
	oauthParams["oauth_signature"] = s.GetSignature(clientConfig.ConsumerSecret, tokenSecret, signatureBase)
	return oauthParams, signatureBase
}
Exemple #6
0
func handleCreate(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		return
	}

	r.ParseForm()
	url := r.FormValue("url")
	title := r.FormValue("title")
	tagString := r.FormValue("tags")
	if url == "" {
		output(c, w, "create")
		return
	}

	tags := strings.Split(tagString, ",")
	bm := bookmarks.NewBookmark(u, url, title, tags)
	_, err := bm.Save(c)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Location", rootURL(c))
	w.WriteHeader(http.StatusFound)
	return
}
Exemple #7
0
func getSettings(req *http.Request) (p Settings) {
	req.ParseForm()
	p = DefaultSettings()
	p.Cards = make(map[string]*bridge.ConventionCard)
	prefstr, _ := req.Header["Cookie"] // I don't care about errors!
	// fmt.Println("Trying to unmarshall string", prefstr)
	json.Unmarshal([]byte(prefstr), &p) // I don't care about errors!
	for k, v := range bridge.DefaultConvention().Pts {
		if _, ok := p.Card().Pts[k]; !ok {
			p.Card().Pts[k] = v
		}
	}
	for k, v := range bridge.DefaultConvention().Options {
		if _, ok := p.Card().Options[k]; !ok {
			p.Card().Options[k] = v
		}
	}
	for k, v := range bridge.DefaultConvention().Radio {
		if _, ok := p.Card().Radio[k]; !ok {
			p.Card().Radio[k] = v
		}
	}
	// fmt.Println("Unmarshal gave: %v", e)
	return p
}
Exemple #8
0
func (h *SearchPanelHandler) getSearchPanelHtml(hr *http.Request) string {
	fmt.Println("\n=== SearchPanelHandler : Requete reçue ====================")
	fmt.Println(" URL : " + hr.RawURL)
	hr.ParseForm()

	askerId := GetFormValueAsInt(hr, "asker")
	mdpr := GetFormValue(hr, "mdpr") // mot de passe restreint
	tok := GetFormValue(hr, "tok")
	compteOk := false
	var compte *Compte

	db, err := h.store.Connect()
	if err != nil {
		fmt.Printf("Erreur ouverture connexion BD dans makeBestiaryExtractHtml : %s\n", err.String())
		return err.String()
	}
	defer db.Close()

	if askerId > 0 && mdpr != "" {
		compteOk, compte, err = h.store.CheckCompte(db, uint(askerId), mdpr)
	}
	if !compteOk {
		return "Compte non authentifié"
	}
	if tok == "" {
		return "Demande non comprise"
	}
	amis, err := h.store.GetPartageurs(db, askerId)
	if err != nil {
		return fmt.Sprintf("Erreur récupération amis : %s\n", err.String())
	}
	observations, err := h.store.SearchObservations(db, tok, askerId, amis)
	if err != nil {
		return fmt.Sprintf("Erreur recherche : %s\n", err.String())
	}
	if len(observations) == 0 {
		return "Rien trouvé"
	}
	html := fmt.Sprintf("%d résultats :", len(observations))
	html += "<table border='0' cellspacing='1' cellpadding='2' class='mh_tdborder' align='center'>"
	html += "<tr class=mh_tdtitre><td class=mh_tdpage><b>Dist.</b></td><td class=mh_tdpage><b>Réf.</b></td><td class=mh_tdpage><b>Nom</b></td>"
	html += "<td class=mh_tdpage><b>Position</b></td>"
	html += "<td class=mh_tdpage><b>Vu par</b></td><td class=mh_tdpage><b>Le</b></td></tr>"
	for _, o := range observations {
		t := time.SecondsToLocalTime(o.Date)
		var lien string
		if o.Type == "troll" {
			lien = fmt.Sprintf("<a href='javascript:EPV(%d)' class=mh_trolls_1 id=%d>%s</a>", o.Num, o.Num, o.Nom)
		} else if o.Type == "monstre" {
			lien = fmt.Sprintf("<a href='javascript:EMV(%d, 750, 550)' class=mh_monstres id=%d>%s</a>", o.Num, o.Num, o.Nom)
		} else {
			lien = o.Nom
		}
		dist := dist(compte.Troll.X, o.X, compte.Troll.Y, o.Y, compte.Troll.Z, o.Z)
		btnVoir := fmt.Sprintf("<a x=%d y=%d z=%d class=gogo name=zoom>%d  %d  %d</a>", o.X, o.Y, o.Z, o.X, o.Y, o.Z)
		html += fmt.Sprintf("<tr class=mh_tdpage><td>%d</td><td>%d</td><td>%s</td><td>%s</td><td>%d</td><td>%s</td></tr>", dist, o.Num, lien, btnVoir, o.Auteur, t.Format("02/01 à 15h04"))
	}
	html += "</table>"
	return html
}
Exemple #9
0
func (h *JSONSignHandler) handleSign(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()

	badReq := func(s string) {
		http.Error(rw, s, http.StatusBadRequest)
		log.Printf("bad request: %s", s)
		return
	}
	// TODO: SECURITY: auth

	jsonStr := req.FormValue("json")
	if jsonStr == "" {
		badReq("missing \"json\" parameter")
		return
	}
	if len(jsonStr) > kMaxJsonLength {
		badReq("parameter \"json\" too large")
		return
	}

	sreq := &jsonsign.SignRequest{
		UnsignedJson:      jsonStr,
		Fetcher:           h.pubKeyFetcher,
		ServerMode:        true,
		SecretKeyringPath: h.secretRing,
	}
	signedJson, err := sreq.Sign()
	if err != nil {
		// TODO: some aren't really a "bad request"
		badReq(fmt.Sprintf("%v", err))
		return
	}
	rw.Write([]byte(signedJson))
}
Exemple #10
0
func RequireParams(request *http.Request, params []string) (success bool) {
	err := request.ParseForm()
	if err != nil {
		return false
	}

	for _, v := range params {
		if thisParam, exists := request.Form[v]; exists {
			hasGoodValue := false
			for _, paramValue := range thisParam {
				if len(paramValue) > 0 {
					hasGoodValue = true
					break
				}
			}
			if !hasGoodValue {
				return false
			}
		} else {
			return false
		}
	}

	return true
}
Exemple #11
0
func HandleNewPaste(writer http.ResponseWriter, request *http.Request) {
	err := request.ParseForm()
	if err != nil {
		write_error(writer, err)
		return
	}
	text := request.FormValue("paste_text")
	language := request.FormValue("language")

	var page *Page
	page, err = NewPage(text, language)

	if err != nil {
		write_error(writer, err)
		return
	}
	// check if we already have a page
	// and not store it again
	oldpage, err := GetPageFromDataStore(page.UrlId, request)
	if oldpage == nil {
		err = StorePage(page, request)
		if err != nil {
			write_error(writer, err)
			return
		}
	}
	http.Redirect(writer, request, "/"+page.UrlId[0:LENGTH], http.StatusFound)
}
func handleLogout(w http.ResponseWriter, r *http.Request) {
	c = appengine.NewContext(r)
	returnURL := "/"
	// parse form
	err := r.ParseForm()
	if err != nil {
		serveError(c, w, err)
		return
	}
	if r.FormValue("continue") != "" {
		returnURL = r.FormValue("continue")
	}

	if useOpenID {
		// adjust returnURL to bring us back to a local user login form
		laterReturnUrl := returnURL
		returnURL = "/Login/?chooseLogin=1&continue=" + http.URLEscape(laterReturnUrl)
	}
	// redirect to google logout (for OpenID as well, or else we won't be locally logged out)
	lourl, err := user.LogoutURL(c, returnURL)
	if err != nil {
		c.Errorf("handleLogout: error getting LogoutURL")
	}
	c.Debugf("handleLogout: redirecting to logoutURL=%v", lourl)
	http.Redirect(w, r, lourl, http.StatusFound)
	return
}
Exemple #13
0
// handle a request to change the status
func HandleUpdateStatus(c *http.Conn, req *http.Request) {
	req.ParseForm()
	statusStr := req.FormValue("status")
	log.Stdoutf("status to be sent:\n%s\n\n", statusStr)
	jsonStr, _ := twitter.TweetJson(&creds, statusStr)
	io.WriteString(c, jsonStr)
}
Exemple #14
0
func (h *JSONSignHandler) handleVerify(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	sjson := req.FormValue("sjson")
	if sjson == "" {
		http.Error(rw, "missing \"sjson\" parameter", http.StatusBadRequest)
		return
	}

	m := make(map[string]interface{})

	// TODO: use a different fetcher here that checks memory, disk,
	// the internet, etc.
	fetcher := h.pubKeyFetcher

	vreq := jsonsign.NewVerificationRequest(sjson, fetcher)
	if vreq.Verify() {
		m["signatureValid"] = 1
		m["signerKeyId"] = vreq.SignerKeyId
		m["verifiedData"] = vreq.PayloadMap
	} else {
		errStr := vreq.Err.String()
		m["signatureValid"] = 0
		m["errorMessage"] = errStr
	}

	rw.WriteHeader(http.StatusOK) // no HTTP response code fun, error info in JSON
	httputil.ReturnJson(rw, m)
}
Exemple #15
0
// receives ?returnto=/replies etc.
func CALLBACK(c *http.Conn, req *http.Request, auth_client *oauth.AuthClient) {
	log.Stderr("CALLBACK!");
	req.ParseForm();
	for k,v := range req.Header {
		log.Stderrf("header:%s:%s", k, v);
	}
	for k,vs := range req.Form {
		log.Stderrf("form:%s::", k);
		for i := range vs {
			log.Stderrf("::%s", vs[i]);
		}
	}

	var auth_token = req.FormValue("oauth_token");
	var auth_verifier = req.FormValue("oauth_verifier");
	log.Stderrf("CALLBACK:auth_token:%s:", auth_token);
	log.Stderrf("CALLBACK:auth_verifier:%s:", auth_verifier);

	user_info := auth_client.GetUserInfo(auth_token, auth_verifier);

	log.Stderrf("USER_INFO:");
	for k,v := range user_info {
		log.Stderrf("k:%s v:%s", k, v);
	}

	session_service.StartSession(c, req, user_info);
	var url = "/";
	returnto := req.FormValue("returnto");
	if returnto != "" {
		url = returnto;
	}
	http.Redirect(c, url, http.StatusFound); // should be 303 instead of 302?
}
Exemple #16
0
func (set *TileServer) ServeHTTP(conn *http.Conn, req *http.Request) {
	req.ParseForm()
	var x, y, zoom int
	x, err := strconv.Atoi(req.Form["x"][0])
	if err == nil {
		y, err = strconv.Atoi(req.Form["y"][0])
	}
	if err == nil {
		zoom, err = strconv.Atoi(req.Form["z"][0])
	}

	if err != nil {
		fmt.Println("Err:", err.String())
		conn.WriteHeader(404)
		return
	}

	tile := set.GetTile(x, y, zoom)
	if tile == nil {
		fmt.Println("No tile at", x, y, zoom)
		conn.WriteHeader(404)
		return
	}
	conn.Write(tile)
}
Exemple #17
0
func AppEngineVerify(r *http.Request) string {

	if err := r.ParseForm(); err != nil {
		return "Anonymous"
	}

	token := r.FormValue("assertion")
	url := "https://browserid.org/verify"
	bodytype := "application/x-www-form-urlencoded"
	body := strings.NewReader("assertion=" + token + "&audience=" + r.Host)

	var response_body []byte
	c := appengine.NewContext(r)
	client := urlfetch.Client(c)
	res, err := client.Post(url, bodytype, body)
	if err != nil {
		fmt.Println("err=", err)
		return "Anonymous"
	} else {
		response_body, _ = ioutil.ReadAll(res.Body)
		res.Body.Close()
	}

	var f interface{}
	json.Unmarshal(response_body, &f)

	m := f.(map[string]interface{})
	return fmt.Sprintf("%s", m["email"])
}
Exemple #18
0
func moveCardHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method == "POST" {
		req.ParseForm()
		id, x, y := req.Form["id"][0], req.Form["x"][0], req.Form["y"][0]
		moveCard(id, x, y)
	} else {
		w.WriteHeader(400)
	}
}
Exemple #19
0
func removeCardHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method == "GET" {
		req.ParseForm()
		id := req.Form["id"][0]
		removeCard(id)
	} else {
		w.WriteHeader(400)
	}
}
Exemple #20
0
// url: /blog/entry/add
func AddEntry(c *http.Conn, req *http.Request) {
	req.ParseForm();
	heading, body := req.FormValue("heading"), req.FormValue("body");
	if len(heading) > 0 && len(body) > 0 {
		blog.AddEntry(heading, body)
	}
	c.SetHeader("Location", "/blog");
	c.WriteHeader(http.StatusFound);
}
Exemple #21
0
func createCardHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method == "POST" {
		req.ParseForm()
		id, title, desc, x, y := req.Form["id"][0], req.Form["title"][0], req.Form["desc"][0], req.Form["x"][0], req.Form["y"][0]
		addCard(id, title, desc, x, y)
	} else {
		w.WriteHeader(400)
	}
}
Exemple #22
0
func getForm(r *http.Request) map[string]string {
	form := make(map[string]string)
	r.ParseForm()
	if len(r.Form) > 0 {
		for k := range r.Form {
			form[k] = r.FormValue(k)
		}
	}
	return form
}
Exemple #23
0
func addLinkHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	name := r.FormValue("name")
	url := r.FormValue("url")
	if !strings.HasPrefix(url, "http://") {
		url = "http://" + url
	}
	location := r.Header.Get("X-AppEngine-country")
	getStorage(r).Save(Linky{Name: name, URL: url, Location: location, Created: datastore.SecondsToTime(time.Seconds())})
	writeTemplate(w, MainPage, &PageModel{FooterMessage: "Link added", LinkyURL: r.Host + "/" + name, StatsURL: r.Host + "/stats/" + name, LinkyName: name})
}
Exemple #24
0
//模拟login
func login(w http.responseWriter, r *http.Request) {
	sess := gloablSession.SessionStart(w, r)
	r.ParseForm()
	if r.Method == "GET" {
		t, _ := template.ParseFiles("login.gtpl")
		w.Header().Set("Content-Type", "text/html")
		t.execute(w, sess.Get("username"))
	} else {
		sess.Set("username", r.Form["username"])
		http.Redirect(w, r, "/", 302)
	}
}
Exemple #25
0
// url: /blog/comment/add
func AddComment(c *http.Conn, req *http.Request) {
	req.ParseForm();
	entryIDString, text := req.FormValue("entry_id"), req.FormValue("text");
	if len(entryIDString) > 0 && len(text) > 0 {
		if entryID, parseErr := strconv.Atoi(entryIDString); parseErr == nil {
			if foundEntry := blog.FindEntry(entryID); foundEntry != nil {
				foundEntry.AddComment(text);
			}
		}
	}
	c.SetHeader("Location", "/blog/entry/" + entryIDString);
	c.WriteHeader(http.StatusFound);
}
Exemple #26
0
func updateHandler(w http.ResponseWriter, r *http.Request) {

	var err os.Error
	var ok bool

	c := appengine.NewContext(r)

	printLog(c, "Post Handler Start")

	if r.Method != "POST" {
		printLog(c, "Not Post Method Return")
		return
	}

	err = r.ParseForm()
	check(err)

	printLog(c, "form parsed")
	u := user.Current(c)

	printLog(c, "User:"******"Set Values")

	check(err)

	if err, ok = task.IsValid(); ok {
		check(err)
		// postエラーの場合にjQueryでステータスを取れるか?
	}

	printLog(c, "Validated")

	if task.KeyID != 0 {
		k := datastore.NewKey("Tasks", "", task.KeyID, nil)
		_, err = datastore.Put(c, k, task)
	} else {
		_, err = datastore.Put(c, datastore.NewIncompleteKey("Tasks"), task)
	}

	log.Println(err)
	check(err)

	printLog(c, "Puted")

	returnJson(w, task.KeyID)

}
func (this RestJsonMongo) LoadJson(r *http.Request, item interface{}) (err os.Error) {
	logger.Debug("LoadJson(%v)", r.URL.Path)

	if err = r.ParseForm(); err != nil {
		logger.Warn(err)
		return
	}

	jsonfile := r.Form[this.JsonParam]
	if err = json.NewDecoder(strings.NewReader(jsonfile[0])).Decode(&item); err != nil {
		logger.Warn(err)
	}
	return
}
Exemple #28
0
func getTransitoryData(req *http.Request) (d *TransitoryData) {
	d = new(TransitoryData)
	req.ParseForm()
	if xx, ok := req.Form["transitorydata"]; ok {
		json.Unmarshal([]byte(strings.Replace(xx[0], "'", "\"", -1)), &d) // I don't care about errors!
	}
	d.Url = req.URL.Path
	s := getSettings(req)
	if _, ok := s.Cards[d.NScard]; !ok {
		d.NScard = s.WhichCard
	}
	if _, ok := s.Cards[d.EWcard]; !ok {
		d.EWcard = s.WhichCard
	}
	return
}
Exemple #29
0
// Parses an access token and verifier from a redirected authorize reqeust.
func (c *UserConfig) ParseAuthorize(request *http.Request, service *Service) (string, string, os.Error) {
	request.ParseForm()
	urlParts := request.URL.Query()
	token := urlParts.Get("oauth_token")
	verifier := urlParts.Get("oauth_verifier")
	if token == "" {
		token = request.Form.Get("oauth_token")
	}
	if verifier == "" {
		verifier = request.Form.Get("oauth_verifier")
	}
	if token == "" || verifier == "" {
		return "", "", os.NewError("Token or verifier were missing from response")
	}
	return token, verifier, nil
}
Exemple #30
0
func (s *Swif) ServeHTTP(c *http.Conn, req *http.Request) {
	err := req.ParseForm()

	if err != nil {
		s.handleError(http.StatusBadRequest, c)
		return
	}

	action, isAction := req.Form["action"]
	if isAction {
		s.handleAction(action[0], c)
		return
	}

	s.printMenu(c)
}