func loginHandler(w http.ResponseWriter, r *http.Request) { // Determine the virtual host server, err := findServer(r.Host) if err != nil { errorHandler(w, r, err.String()) return } username := r.FormValue("username") password := r.FormValue("password") log.Println("LOGIN:", username) if err = server.UserAccountDatabase.CheckCredentials(username, password); err != nil { log.Println(err) http.Redirect(w, r, server.Config.LoginPage, 303) return } s, err := server.SessionDatabase.CreateSession(username) if err != nil { log.Println(err) http.Redirect(w, r, server.Config.LoginPage, 303) return } s.SetCookie(w) http.Redirect(w, r, server.Config.MainPage, 303) }
func signupHandler(w http.ResponseWriter, r *http.Request) { // Determine the virtual host server, err := findServer(r.Host) if err != nil { errorHandler(w, r, err.String()) return } username := r.FormValue("username") password := r.FormValue("password") email := r.FormValue("email") nickname := r.FormValue("nickname") log.Println("Register:", username) user, err := server.UserAccountDatabase.SignUpUser(email, nickname, username, password) if err != nil { log.Println(err) http.Redirect(w, r, server.Config.SignupPage, 303) return } s, err := server.SessionDatabase.CreateSession(user.Username) if err != nil { log.Println(err) http.Redirect(w, r, server.Config.LoginPage, 303) return } s.SetCookie(w) http.Redirect(w, r, server.Config.MainPage, 303) }
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 serveFile(w http.ResponseWriter, r *http.Request) { relpath := r.URL.Path[1:] // serveFile URL paths start with '/' abspath := absolutePath(relpath, *goroot) // pick off special cases and hand the rest to the standard file server switch r.URL.Path { case "/": serveHTMLDoc(w, r, filepath.Join(*goroot, "doc", "root.html"), "doc/root.html") return case "/doc/root.html": // hide landing page from its real name http.Redirect(w, r, "/", http.StatusMovedPermanently) return } switch path.Ext(relpath) { case ".html": if strings.HasSuffix(relpath, "/index.html") { // We'll show index.html for the directory. // Use the dir/ version as canonical instead of dir/index.html. http.Redirect(w, r, r.URL.Path[0:len(r.URL.Path)-len("index.html")], http.StatusMovedPermanently) return } serveHTMLDoc(w, r, abspath, relpath) return case ".go": serveTextFile(w, r, abspath, relpath, "Source file") return } dir, err := fs.Lstat(abspath) if err != nil { log.Print(err) serveError(w, r, relpath, err) return } if dir != nil && dir.IsDirectory() { if redirect(w, r) { return } if index := filepath.Join(abspath, "index.html"); isTextFile(index) { serveHTMLDoc(w, r, index, relativeURL(index)) return } serveDirectory(w, r, abspath, relpath) return } if isTextFile(abspath) { serveTextFile(w, r, abspath, relpath, "Text file") return } fileServer.ServeHTTP(w, r) }
func searchHandler(w http.ResponseWriter, r *http.Request) { context := &Search{} // prepare the template t, err := template.ParseFile("template/search.html") if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } context.T = t ae := appengine.NewContext(r) query := r.FormValue("q") queryLength := len([]int(query)) // unicode length // max 8 letters if queryLength > 8 { query = query[0:8] http.Redirect(w, r, fmt.Sprintf("search?q=%s", query), 302) return } // lowercase only if query != strings.ToLower(query) { http.Redirect(w, r, fmt.Sprintf("search?q=%s", strings.ToLower(query)), 302) return } context.Q = query hashTable := make(map[string]byte, 0) if 0 != queryLength { if queryLength > 8 { query = query[0:8] } // make sure enable is loaded var e *word.Enable var err os.Error if e, err = loadEnable(); err != nil { ae.Errorf("%v", err) } channel := word.StringPermutations(query) for p := range channel { if valid := e.WordIsValid(p); !valid { continue } if _, inHash := hashTable[p]; !inHash { context.Permutations = append(context.Permutations, p) hashTable[p] = 1 } } } // display template if err := context.T.Execute(w, context); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) } }
func SaveHandler(c http.ResponseWriter, r *http.Request) { fmt.Println(r) title, id, origID, dateString, desc, body, fileName, importance, delete := HandleNess(c, r) date, e := time.Parse(timeFormat, string(dateString)) event := new(Event) // The ID changed, remove the old one. if !bytes.Equal(id, origID) && len(origID) > 0 { fmt.Println("ID Changed!") origEvent := new(Event) origEvent.ID = string(origID) origEvent.Load() // Copy the info to the new event *event = *origEvent origEvent.Delete() } event.ID = string(id) event.Load() // TODO: Delete the uploaded image as well! if delete { event.Delete() http.Redirect(c, r, "/events", 301) return } event.Importance = importance event.Title = string(title) event.Desc = string(desc) event.Link = "/events/" + string(id) event.Time = (*Time)(date) if len(fileName) > 0 { event.Img = "/img/events/data/" + fileName } e = pages.SavePage("events/"+string(id), body, title) event.Save() fmt.Println(title, id, dateString, date, e, desc, body) fmt.Println(r.FormValue("img")) http.Redirect(c, r, "/events/"+event.ID, 301) }
func handleUpload(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) blobs, _, err := blobstore.ParseUpload(r) if err != nil { serveError(c, w, err) return } file := blobs["file"] if len(file) == 0 { c.Errorf("no file uploaded") http.Redirect(w, r, "/", http.StatusFound) return } http.Redirect(w, r, "/serve/?blobKey="+string(file[0].BlobKey), http.StatusFound) }
// For login authentication from picasa. // TODO: Add error handling. func AuthHandler(c http.ResponseWriter, r *http.Request) { // Get the token supplied in the URL. picasaLen := len("token=") url, _ := http.URLUnescape(r.URL.RawQuery) token := url[picasaLen:] fmt.Println(token, r.URL.RawQuery) // Try to upgrade the token to a multi-use one. See // http://code.google.com/apis/accounts/docs/AuthSub.html req := picasa.NewRequest("https://www.google.com/accounts/accounts/AuthSubSessionToken", token, "GET") resp, e := picasa.Send(req) // Get the upgraded token value body, e := ioutil.ReadAll(resp.Body) if e != nil { fmt.Println(e) } resp.Body.Close() if len(body) <= picasaLen { dlog.Println("Invalid or missing token! Response received was:", body) template.Error500(c, r, nil) } upgradedToken := body[picasaLen:] fmt.Println("Upgraded Token: ", string(upgradedToken)) // Finally, save the upgraded token in the server-side session. u, _ := user.Get(c, r) u.Set("picasa-authsub-token", string(upgradedToken)) http.Redirect(c, r, "/photos/upload", http.StatusFound) }
func redirect(w http.ResponseWriter, r *http.Request) (redirected bool) { if canonical := path.Clean(r.URL.Path) + "/"; r.URL.Path != canonical { http.Redirect(w, r, canonical, http.StatusMovedPermanently) redirected = true } return }
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 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 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) }
//This is what sends the Post data to the primarry "run" function func handleTest(writer http.ResponseWriter, request *http.Request) { BoardSize, _ := strconv.Atoi(request.FormValue("BoardSize")) NumberThreads, _ := strconv.Atoi(request.FormValue("NumberThreads")) NumberIterations, _ := strconv.Atoi(request.FormValue("NumberIterations")) run(writer, BoardSize, NumberThreads, NumberIterations) http.Redirect(writer, request, "/", http.StatusFound) }
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 mainHandler(rw http.ResponseWriter, req *http.Request) { relPath := req.URL.Path[1:] // serveFile URL paths start with '/' if strings.Contains(relPath, "..") { return } if strings.HasPrefix(relPath, "gw/") { path := relPath[3:] http.Redirect(rw, req, "/code/?p=camlistore.git;f="+path+";hb=master", http.StatusFound) return } absPath := path.Join(*root, "content", relPath) fi, err := os.Lstat(absPath) if err != nil { log.Print(err) serveError(rw, req, relPath, err) return } if fi.IsDirectory() { relPath += "/index.html" absPath = path.Join(*root, "content", relPath) fi, err = os.Lstat(absPath) if err != nil { log.Print(err) serveError(rw, req, relPath, err) return } } switch { case fi.IsRegular(): serveFile(rw, req, relPath, absPath) } }
func AuthHandler(c http.ResponseWriter, r *http.Request) { var o = new(openid.OpenID) o.ParseRPUrl(r.RawURL) grant, e := o.Verify() if e != nil { emsg := fmt.Sprintln("Error in openid auth handler:", e) fmt.Println(emsg) fmt.Fprintln(c, emsg) return } if !grant { fmt.Println("Permission denied!") fmt.Fprintln(c, "Access denied by user or internal error.") return } s := session.Get(c, r) fmt.Println("Permission granted!") fmt.Println(o) wantedValues := []string{"value.email", "value.first", "value.last", "value.country", "value.lang"} for _, wantedValue := range wantedValues { value, _ := http.URLUnescape(o.Params["openid.ext1."+wantedValue]) s.Set("openid-"+wantedValue[len("value."):], value) } id, _ := http.URLUnescape(o.Params["openid.ext1.value.email"]) continueURL := s.Get("openid-continue-url") if continueURL == "" { continueURL = "/" } fmt.Println(c, r, continueURL) http.Redirect(c, r, continueURL, 307) fmt.Fprintln(c, "Authenticated as", id) return }
func TWITTER_REPLIES(c *http.Conn, req *http.Request) { log.Stderrf(">REPLIES:"); s := session_service.GetSession(c,req); for k,v := range s.Data { log.Stderrf("session kv:%s:%s", k, v); } auth_token, atx := s.Data["oauth_token"]; if atx { log.Stderrf("TOKEN FOUND!"); auth_token_secret := s.Data["oauth_token_secret"]; r, finalUrl, err := twitter_client.MakeRequest("http://twitter.com/statuses/mentions.json", map[string]string{"oauth_token":auth_token}, auth_token_secret, false); //{"since_id":s.last_reply_id}) if err != nil { log.Stderrf(":REPLIES:err:%s",err); } else { log.Stderrf(":REPLIES:r:%s:finalUrl:%s", r, finalUrl); b, _ := io.ReadAll(r.Body); print ("REPLIES!"); str := bytes.NewBuffer(b).String(); println (str); j, ok, errtok := json.StringToJson(str); log.Stderr("REPLIES:j:%s:ok:%s:errtok:%s", j, ok, errtok); c.Write(strings.Bytes(j.String())); } } else { log.Stderrf("NO TOKEN FOUND!"); http.Redirect(c, "/login/twitter?returnto=/twitter/replies", http.StatusFound); // should be 303 instead of 302? } }
func fileHandler(w http.ResponseWriter, r *http.Request) { // Determine the virtual host server, err := findServer(r.Host) if err != nil { errorHandler(w, r, err.String()) return } // log.Println("URI is ", "/_static" + r.URL.Path) // Parse the URI, prepend "/_static" uri, ok := lightwave.NewURI("/_static" + r.URL.Path) if !ok { errorHandler(w, r, "Error parsing URI") return } // GET handler if r.Method != "GET" { errorHandler(w, r, "Unsupported HTTP method") } // Requests for the application page are redirected to the login page if r.URL.Path == server.Config.MainPage { // Find the session _, err := server.SessionDatabase.FindSession(r) if err != nil { http.Redirect(w, r, server.Config.LoginPage, 303) return } } ch := make(chan bool) req := &lightwave.GetRequest{lightwave.Request{w, r.URL.RawQuery, ch, lightwave.ClientOrigin, uri, nil}} server.Get(req) <-ch }
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 deleteAccountHandler(w http.ResponseWriter, r *http.Request) { id := "" session, err := sessions.Session(r, "", "datastore") c1 := appengine.NewContext(r) c1.Debugf("deleteAccount: id=%v, session=%v, err=%v\n", session["userID"], session, err) if err == nil { if session["userID"] != nil { id = session["userID"].(string) } } if id != "" { user := loadUser(r, id) if user.Id != "" { c := appengine.NewContext(r) key := datastore.NewKey(c, "User", user.Id, 0, nil) datastore.Delete(c, key) session["userID"] = "" sessions.Save(r, w) memUserDelete(c, user.Id) memcache.Delete(c, "user"+user.Id) http.SetCookie(w, &http.Cookie{Name: "userId", Value: "", Domain: appConfig.AppDomain, Path: "/", MaxAge: -1}) } } http.Redirect(w, r, "/", http.StatusFound) }
func init() { fmt.Println("Selog filekkkk") http.Handle("/index", http.HandlerFunc(Render)) http.Handle("/index.ghtml", http.HandlerFunc(RenderGoPagesForbidden)) http.Handle("/", http.HandlerFunc(func(conn http.ResponseWriter, request *http.Request) { if request.URL.Path == "/" { defaultPage := "index" if strings.TrimSpace(defaultPage) != "" { http.Redirect(conn, defaultPage, 307) } return } val := "src" + request.URL.Path input, err := os.OpenFile(val, os.O_RDONLY, 0666) // input,err := os.Open(val) if err != nil { conn.WriteHeader(404) conn.Write([]byte("<h1>404 Not Found</h1>")) return } s, _ := input.Stat() conn.Header.Set("Content-Length", fmt.Sprintf("%d(MISSING)", s.Size)) // conn.SetHeader("Content-Type", mime.TypeByExtension(strings.ToLower(path.Ext(val)))) fmt.Sprintf("%d(MISSING)", s.Size) mime.TypeByExtension(strings.ToLower(path.Ext(val))) conn.WriteHeader(200) http.ServeFile(conn, request, val) })) http.Handle("/src", http.HandlerFunc(RenderGoPagesForbidden)) http.Handle("/pages", http.HandlerFunc(RenderGoPagesForbidden)) }
// 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? }
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) } }
func get(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { http.Redirect(w, r, WEBSITE, http.StatusFound) return } parts := strings.Split(r.URL.Path, "/") if len(parts) == 3 { if key := parts[1]; key != "" { blobKey := appengine.BlobKey(key) bi, err := blobstore.Stat(appengine.NewContext(r), blobKey) if err == nil { w.Header().Add( "Cache-Control", fmt.Sprintf("public,max-age=%d", EXPIRATION_TIME), ) if imageTypes.MatchString(bi.ContentType) { w.Header().Add("X-Content-Type-Options", "nosniff") } else { w.Header().Add("Content-Type", "application/octet-stream") w.Header().Add( "Content-Disposition:", fmt.Sprintf("attachment; filename=%s;", parts[2]), ) } blobstore.Send(w, appengine.BlobKey(key)) return } } } http.Error(w, "404 Not Found", http.StatusNotFound) }
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 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 loginGoogle(w http.ResponseWriter, r *http.Request) { tr := emptyTransport() c := appengine.NewContext(r) tr.Transport = &urlfetch.Transport{Context: c} urls := tr.AuthCodeURL("login") + "&approval_prompt=force&access_type=offline" http.Redirect(w, r, urls, http.StatusFound) }
func redirect(c *http.Conn, r *http.Request) (redirected bool) { if canonical := pathutil.Clean(r.URL.Path) + "/"; r.URL.Path != canonical { http.Redirect(c, canonical, http.StatusMovedPermanently) redirected = true } return }
func saveHandler(w http.ResponseWriter, r *http.Request) { title, err := getTitle(w, r) if err != nil { return } body := r.FormValue("body") tags := r.FormValue("tags") m, err2 := Load(tagsPath + tagsFile) if err2 != nil { return } splitTokens := strings.Split(tags, " ", -1) for i := 0; i < len(splitTokens); i++ { Add(m, splitTokens[i], title) } err2 = Store(m, tagsPath+tagsFile) if err2 != nil { return } p := &Page{Title: title, Body: []byte(body)} err = p.save() if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } http.Redirect(w, r, view+title, http.StatusFound) }
func register(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) g := Member{ Usern: r.FormValue("usern"), Name: r.FormValue("name"), Passwd: r.FormValue("passwd"), Repasswd: r.FormValue("repasswd"), Phone: r.FormValue("phone"), Email: r.FormValue("email"), Study: r.FormValue("study"), Address: r.FormValue("address"), Date: datastore.SecondsToTime(time.Seconds()), } if g.Passwd == g.Repasswd && g.Usern != "" && g.Name != "" && g.Phone != "" && g.Email != "" { _, err := datastore.Put(c, datastore.NewIncompleteKey("Member"), &g) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } } else { http.Redirect(w, r, "/signin", http.StatusFound) } http.Redirect(w, r, "/view", http.StatusFound) }