func close_event(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) event, key, err_string := find_single_event(c, r.FormValue("sender"), r.FormValue("date")) if len(err_string) > 0 { fmt.Fprintf(w, err_string) return } // TODO: Check to make sure the closer matches the owner if event.ClosedDate > 0 { fmt.Fprintf(w, "This message is already closed.") return } event.ClosedDate = datastore.SecondsToTime(time.Seconds()) _, err := datastore.Put(c, key, &event) if err != nil { fmt.Fprintf(w, err.String()) return } else { target_url := fmt.Sprintf("/show?sender=%s&date=%d", event.Sender, event.RecieptDate) http.Redirect(w, r, target_url, http.StatusFound) } }
func search(c *http.Conn, r *http.Request) { query := strings.TrimSpace(r.FormValue("q")) var result SearchResult if index, timestamp := searchIndex.get(); index != nil { result.Query = query result.Hit, result.Alt, result.Illegal = index.(*Index).Lookup(query) _, ts := fsTree.get() result.Accurate = timestamp >= ts } var buf bytes.Buffer if err := searchHTML.Execute(result, &buf); err != nil { log.Stderrf("searchHTML.Execute: %s", err) } var title string if result.Hit != nil { title = fmt.Sprintf(`Results for query %q`, query) } else { title = fmt.Sprintf(`No results found for query %q`, query) } servePage(c, title, query, buf.Bytes()) }
func handleInboxItem(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) userid, _, err := getSession(c, r) if err != nil { sendError(w, r, "No session cookie") return } s := newStore(c) perma_blobref := r.FormValue("perma") item, err := s.GetInboxItem(userid, perma_blobref) if err != nil { http.Error(w, "Could not get inbox item", http.StatusInternalServerError) c.Errorf("handleInboxItem: %v", err) return } entry := make(map[string]interface{}) entry["perma"] = perma_blobref entry["seq"] = item.LastSeq err = fillInboxItem(s, perma_blobref, item.LastSeq, entry) if err != nil { fmt.Fprintf(w, `{"ok":false, "error":%v}`, err.String()) return } info, _ := json.Marshal(entry) fmt.Fprintf(w, `{"ok":true, "item":%v}`, string(info)) }
func serveFile(c *http.Conn, r *http.Request) { path := r.Url.Path // pick off special cases and hand the rest to the standard file server switch ext := pathutil.Ext(path); { case path == "/": serveHtmlDoc(c, r, "doc/root.html") case r.Url.Path == "/doc/root.html": // hide landing page from its real name http.NotFound(c, r) case ext == ".html": serveHtmlDoc(c, r, path) case ext == ".go": serveGoSource(c, path, &Styler{highlight: r.FormValue("h")}) default: // TODO: // - need to decide what to serve and what not to serve // - don't want to download files, want to see them fileServer.ServeHTTP(c, r) } }
func get(w http.ResponseWriter, r *http.Request) { keyName := r.FormValue("key") c := appengine.NewContext(r) result := map[string]string{ keyName: "", "error": "", } if item, err := memcache.Get(c, keyName); err == nil { result[keyName] = fmt.Sprintf("%q", item.Value) fmt.Fprintf(w, "%s", mapToJson(result)) return } key := datastore.NewKey("Entity", keyName, 0, nil) entity := new(Entity) if err := datastore.Get(c, key, entity); err == nil { result[keyName] = entity.Value // Set the value to speed up future reads - errors here aren't // that bad, so don't worry about them item := &memcache.Item{ Key: keyName, Value: []byte(entity.Value), } memcache.Set(c, item) } else { result["error"] = fmt.Sprintf("%s", err) } fmt.Fprintf(w, "%s", mapToJson(result)) }
func c1LoginHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) if l, err := c1IsLoggedIn(c); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } else if l { /// http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/index", http.StatusFound) return } if r.Method == "GET" { w.Write([]byte( "<html><body><form action='/c1Login' method='POST'>" + "<input type='text' name='usr'></input>" + "<input type='password' name='pwd'></input>" + "<input type='submit' value='Submit'></input>" + "</form></body></html>")) return } else if r.Method == "POST" { usr := r.FormValue("usr") pwd := r.FormValue("pwd") _, err := C1Login(c, usr, pwd) if err == C1AuthError { http.Error(w, err.String(), http.StatusUnauthorized) return } http.Redirect(w, r, "/index", http.StatusFound) /// http.Redirect(w, r, "/", http.StatusFound) } }
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) }
func saveHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[lenPath:] body := r.FormValue("body") p := &Page{Title: title, Body: []byte(body)} p.save() http.Redirect(w, r, "/view/"+title, http.StatusFound) }
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) }
func (authData *validatorImpl) LoginHandler(w http.ResponseWriter, r *http.Request) { client := r.FormValue("client") token := r.FormValue("token") if client == "" || token == "" { w.Write([]byte(loginHtml)) return } existingToken, found := authData.tokenMap[client] if !found { http.Error(w, "Invalid auth token", http.StatusForbidden) return } if token != existingToken { log.Printf("Invalid token: %s != %s", token, existingToken) http.Error(w, "Invalid auth token", http.StatusForbidden) return } // Set cookies. clientCookie := &http.Cookie{Name: "client", Value: client, Secure: true} http.SetCookie(w, clientCookie) tokenCookie := &http.Cookie{Name: "token", Value: token, Secure: true} http.SetCookie(w, tokenCookie) w.Write([]byte("Login successful")) }
func postPosition(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) gid, _ := strconv.Atoi(r.FormValue("gid")) pid, _ := strconv.Atoi(r.FormValue("pid")) lat, _ := strconv.Atoi(r.FormValue("lat")) lng, _ := strconv.Atoi(r.FormValue("lng")) now := datastore.SecondsToTime(time.Seconds()) go savePlayer(c, &Player{pid, gid, lat, lng, now}) q := datastore.NewQuery("Player"). Filter("GameId =", gid) players := make([]Player, 0, 10) for t := q.Run(c); ; { var p Player _, err := t.Next(&p) if err == datastore.Done { break } if err != nil { serveError(c, w, err) return } if p.PlayerId != pid { players = append(players, p) } } m := map[string]interface{}{"players": players, "dead": false} enc := json.NewEncoder(w) enc.Encode(m) }
func signInTwitterHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) id := r.FormValue("id") if id == "" { serveError(c, w, os.NewError("Missing ID parameter")) return } conf := &tweetlib.Config{ ConsumerKey: appConfig.TwitterConsumerKey, ConsumerSecret: appConfig.TwitterConsumerSecret, Callback: "http://" + appConfig.AppHost + "/twitter?action=temp&id=" + id} tok := &tweetlib.Token{} tr := &tweetlib.Transport{Config: conf, Token: tok, Transport: &urlfetch.Transport{Context: c}} tt, err := tr.TempToken() if err != nil { c := appengine.NewContext(r) serveError(c, w, err) c.Errorf("%v", err) return } item := &memcache.Item{ Key: tt.Token, Value: []byte(tt.Secret), } // Add the item to the memcache, if the key does not already exist memcache.Add(c, item) http.Redirect(w, r, tt.AuthURL(), http.StatusFound) }
func (ui *UIHandler) serveDiscovery(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("Content-Type", "text/javascript") inCb := false if cb := req.FormValue("cb"); identPattern.MatchString(cb) { fmt.Fprintf(rw, "%s(", cb) inCb = true } pubRoots := map[string]interface{}{} for key, pubh := range ui.PublishRoots { pubRoots[key] = map[string]interface{}{ "name": pubh.RootName, // TODO: include gpg key id } } bytes, _ := json.Marshal(map[string]interface{}{ "blobRoot": ui.BlobRoot, "searchRoot": ui.SearchRoot, "jsonSignRoot": ui.JSONSignRoot, "uploadHelper": "?camli.mode=uploadhelper", // hack; remove with better javascript "downloadHelper": "./download/", "publishRoots": pubRoots, }) rw.Write(bytes) if inCb { rw.Write([]byte{')'}) } }
/* Check the uniqueness of a Uid. * * FIXME: RESTify this! */ func CheckUidHandler(w http.ResponseWriter, r *http.Request) { log.Println("CheckUidHandler got request with method: " + r.Method) if r.Method == "POST" { context := appengine.NewContext(r) isUnique := controller.IsUidUnique(context, r.FormValue("uid")) encoder := json.NewEncoder(w) type UidResponse struct { Uid string Available string } response := new(UidResponse) response.Uid = r.FormValue("uid") log.Println("Result from IsUidUnique is: " + strconv.Btoa(isUnique) + " : " + reflect.TypeOf(isUnique).String()) if isUnique { log.Println("Username " + response.Uid + " is available") response.Available = "available" } else { log.Println("Username " + response.Uid + " is not available") response.Available = "not available" } log_, _ := json.Marshal(&response) log.Println("Sending to JQuery: " + string(log_)) if err := encoder.Encode(&response); err != nil { log.Println("Cannot send JSON to AJAX code: " + err.String()) } } return }
// hello world, the web server func PageExecuteJS(w http.ResponseWriter, req *http.Request) { url := req.FormValue("url") js := req.FormValue("js") header := w.Header() if url == "" { log.Printf("ERROR: url is required. (%s)\n", url) w.WriteHeader(http.StatusInternalServerError) header.Set("Content-Type", "text/plian;charset=UTF-8;") io.WriteString(w, "Internal Server Error: please input url.\n") return } if strings.Index(url, "http") != 0 { log.Printf("ERROR: url is invalid. (%s)\n", url) w.WriteHeader(http.StatusInternalServerError) header.Set("Content-Type", "text/plian;charset=UTF-8;") io.WriteString(w, "Internal Server Error: please input valid url.\n") return } if js == "" { log.Printf("ERROR: js is required. (%s)\n", url) w.WriteHeader(http.StatusInternalServerError) header.Set("Content-Type", "text/plian;charset=UTF-8;") io.WriteString(w, "Internal Server Error: please input js.\n") return } json := ExecuteJS(url, js) if len(json) == 0 { log.Printf("ERROR: failed to execute. (%s)\n", url) json = []byte("{}") } header.Set("Content-Type", "application/json;charset=UTF-8;") w.Write(json) }
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)) }
func PageInternalUpdateJson(w http.ResponseWriter, req *http.Request) { id := req.FormValue("id") updateJson := req.FormValue("json") header := w.Header() conn, err := GetConnection() c := GetExecuteCollection(conn) var ( rs ExecuteRs jsonb []byte ) execId, err := mongo.NewObjectIdHex(id) log.Printf("Search ExecuteId=%s", execId) err = c.Find(map[string]interface{}{"_id": execId}).One(&rs) if err != nil { jsonb = []byte(`{error: "Not found."}`) } else { rs.Json = updateJson err = c.Update(mongo.M{"_id": execId}, rs) if err != nil { jsonb = []byte(`{result: "failed"}`) } else { jsonb = []byte(`{result: "success"}`) } } conn.Close() header.Set("Access-Control-Allow-Origin", "*") header.Set("Content-Type", "application/json") w.Write(jsonb) }
func addWidget(w http.ResponseWriter, r *http.Request) { var err os.Error if fixup == nil { fixup, err = regexp.Compile(`[^A-Za-z0-9\-_. ]`) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } } ctx := appengine.NewContext(r) name := fixup.ReplaceAllString(r.FormValue("name"), "") if len(name) == 0 { http.Error(w, "Invalid/no name provided", http.StatusInternalServerError) return } widget := NewWidget(ctx, name) err = widget.Commit() if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } http.Redirect(w, r, "/widget/list", http.StatusFound) }
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"]) }
func myWidgets(w http.ResponseWriter, r *http.Request) { var err os.Error ctx := appengine.NewContext(r) page, err := template.Parse(myWidgetTemplate, nil) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } data := myWidgetData{ CSS: commonCSS(), Header: header(ctx), } data.Widget, err = LoadWidgets(ctx) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } if len(r.FormValue("ids_only")) > 0 { w.Header().Set("Content-Type", "text/plain") for _, widget := range data.Widget { fmt.Fprintln(w, widget.ID) } return } page.Execute(w, data) }
// articlesIndex is the handler for the site's index page. // It shows up to the last 10 article summaries (all public info except // for the Body) on a single page. func articlesIndex(w http.ResponseWriter, r *http.Request) { // Get the user-entered offset, or default to a zero offset. offsetS := r.FormValue("Page") var offset int if len(offsetS) > 0 { offset64, err := strconv.Btoi64(offsetS, 10) check(err) offset = int(offset64) } else { offset = 0 } // Fetch public data from datastore, up to 10, with offset `offset * 10` c := appengine.NewContext(r) q := datastore.NewQuery("Article").Order("-Date").Filter("Public =", true).Limit(10).Offset(10 * offset) a := make([]Article, 0, 10) _, err := q.GetAll(c, &a) check(err) // Prepares the `indexTemplate.html` template t := template.New("index") t, err = t.ParseFile("templates/indexTemplate.html") check(err) // Executes the template, providing the data gathered from the datastore err = t.Execute(w, a) check(err) }
func loginView(req *http.Request, s *session) interface{} { rurl := req.FormValue("back") if rurl == "" { rurl = "/" } if req.FormValue("username") != "" && req.FormValue("password") != "" { user := study.GetUser(req.FormValue("username")) if user != nil && user.CheckPass(req.FormValue("password")) { s.User = user s.Admin = false if user.GetAttr("admin") == study.DBTRUE { if _, ok := config.Conf.AdminUsers[user.Username]; ok { s.Admin = true } else { user.SetAttr("admin", study.DBFALSE) } } return redirectResponse(rurl) } return giveTplData{ "ReturnTo": rurl, "Error": messages["BadUserOrPass"], } } return giveTplData{ "ReturnTo": rurl, } }
func put(w http.ResponseWriter, r *http.Request) { keyName := r.FormValue("key") value := r.FormValue("val") c := appengine.NewContext(r) key := datastore.NewKey("Entity", keyName, 0, nil) entity := new(Entity) entity.Value = value result := map[string]string{ "error": "", } if _, err := datastore.Put(c, key, entity); err != nil { result["error"] = fmt.Sprintf("%s", err) } // Set the value to speed up future reads - errors here aren't // that bad, so don't worry about them item := &memcache.Item{ Key: keyName, Value: []byte(value), } memcache.Set(c, item) bumpGeneration(c) fmt.Fprintf(w, "%s", mapToJson(result)) }
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 }
func handle(w http.ResponseWriter, r *http.Request) { // If root, show the link registration page. if r.URL.Path == "/" { switch r.Method { case "GET": w.Write([]byte(registration)) case "POST": // Get input key := r.FormValue("key") url := r.FormValue("url") // Write to db resp := make(chan bool) save <- SaveRequest{key, url, resp} _ = <-resp w.Write([]byte("ok")) } return } // Redirect user based on the path. resp := make(chan string) code := r.URL.Path[1:] lookup <- LookupRequest{code, resp} url := <-resp if url == "" { http.Error(w, "Key not found", http.StatusNotFound) return } http.Redirect(w, r, <-resp, http.StatusFound) }
func authCallback(w http.ResponseWriter, r *http.Request, oldSession *Session) { // We cheat here -- font-end has direct access to the oauth data code := r.FormValue("code") context := appengine.NewContext(r) var userKey datastore.Key _, err := memcache.Gob.Get(context, "oauth-code-"+code, &userKey) if err != nil { w.Write([]byte("Invalid code")) } else { /* auth := model.NewOAuth2(&userKey) if _, err = datastore.Put(context, datastore.NewIncompleteKey(context, "Authentication", nil), auth); err != nil { context.Errorf("Error saving: %v", err) w.Write([]byte("Error saving: " + err.String())) return } // replace session cookie oldKey := datastore.NewKey(context, "Session", oldSession.Key, 0, nil) datastore.Delete(context, oldKey) session := NewSession(context) oldSession.Key = session.Key oldSession.Token = auth.Token oldSession.SetCookie(w, context) // redirect */ } }
// tileHandler implements a tile renderer for use with the Google Maps JavaScript API. // See http://code.google.com/apis/maps/documentation/javascript/maptypes.html#ImageMapTypes func tileHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) x, _ := strconv.Atoi(r.FormValue("x")) y, _ := strconv.Atoi(r.FormValue("y")) z, _ := strconv.Atoi(r.FormValue("z")) w.Header().Set("Content-Type", "image/png") // Try memcache first. key := fmt.Sprintf("mandelbrot:%d/%d/%d", x, y, z) if z < maxMemcacheLevel { if item, err := memcache.Get(c, key); err == nil { w.Write(item.Value) return } } b := render(x, y, z) if z < maxMemcacheLevel { memcache.Set(c, &memcache.Item{ Key: key, Value: b, Expiration: 3600, // TTL = 1 hour }) } w.Header().Set("Content-Length", strconv.Itoa(len(b))) w.Write(b) }
func RenderTiles(w http.ResponseWriter, req *http.Request) { e := os.Remove("svg/test-surface.svg") if e != nil { os.Stderr.WriteString(e.String() + "\n") } if CurrentTiling == nil { EmptySvg(w, req) return } style := req.FormValue("style") image := cairo.NewSurface("svg/test-surface.svg", 72*4, 72*4) image.SetSourceRGB(0., 0., 0.) image.SetLineWidth(.1) image.Translate(72*2., 72*2.) image.Scale(4., 4.) if style == "edges" { image.SetSourceRGBA(0., 0., 0., 1.) CurrentTiling.DrawEdges(image) } else if style == "plain" { CurrentTiling.ColourFaces(image, zellij.OrangeBlueBrush) } else { CurrentTiling.ColourDebugFaces(image) CurrentTiling.DrawDebugEdges(image) } image.Finish() http.ServeFile(w, req, "svg/test-surface.svg") }
func view(w http.ResponseWriter, r *http.Request) { id, _ := strconv.Atoi(r.FormValue("id")) c := appengine.NewContext(r) var view detail_view // グループ情報を取得 if group, err := model.GetGroup(c, id); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } else { view.Group = group } // メンバー情報を取得 if memberlist, err := model.MemberList(c, id); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } else { view.Member = memberlist } // 詳細画面を表示 if err := detailTemplate.Execute(w, view); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } }
func accept_event(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) event, key, err_string := find_single_event(c, r.FormValue("sender"), r.FormValue("date")) if len(err_string) > 0 { fmt.Fprintf(w, err_string) return } if event.OwnerDate > 0 { fmt.Fprintf(w, "This message is already owned by %s.", event.Owner) return } event.OwnerDate = datastore.SecondsToTime(time.Seconds()) event.Owner = "Someone" _, err := datastore.Put(c, key, &event) if err != nil { fmt.Fprintf(w, err.String()) return } else { target_url := fmt.Sprintf("/show?sender=%s&date=%d", event.Sender, event.RecieptDate) http.Redirect(w, r, target_url, http.StatusFound) } }