Ejemplo n.º 1
0
func authOnly(next myHandler) myHandler {
	return func(ctx *Context, w http.ResponseWriter, r *http.Request) error {
		if ctx.user == nil {
			url, err := user.LoginURL(ctx.c, "/login")
			if err != nil {
				return err
			}
			ctx.SetTitle("Please log in to continue ...")
			return ctx.Render(signinTmpl, url)
		}

		err := ctx.LoadUserSession()
		if err != nil {
			return err
		}

		if ctx.userSession == nil {
			url, err := user.LoginURL(ctx.c, "/login")
			if err != nil {
				return err
			}
			ctx.SetTitle("Invalid user ...")
			return ctx.Render(signinTmpl, url)
		}

		return next(ctx, w, r)
	}
}
Ejemplo n.º 2
0
func adminHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/admin/" {
		errorHandler(w, r, http.StatusNotFound)
		return
	}
	admin := template.Must(template.ParseFiles(
		"http/html/_base.html",
		"http/html/admin.html",
	))

	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.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	if !u.Admin {
		url, _ := user.LoginURL(c, r.URL.String())
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}

	admin.Execute(w, nil)

}
Ejemplo n.º 3
0
func admin(w http.ResponseWriter, r *http.Request) {
	// handle requests to "/admin/"
	c := appengine.NewContext(r)
	billQuery := datastore.NewQuery("Bill").Order("-Session").Order("-Number")
	bills := make([]bill.Bill, 0)
	if _, err := billQuery.GetAll(c, &bills); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	senatorQuery := datastore.NewQuery("Senator").Order("-Name")
	senators := make([]senator.Senator, 0)
	if _, err := senatorQuery.GetAll(c, &senators); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	login, _ := user.LoginURL(c, "/")
	logout, _ := user.LogoutURL(c, "/")
	pageInfo := PageInfo{Title: "Administrator Dashboard",
		User:      user.Current(c),
		Admin:     user.IsAdmin(c),
		LoginURL:  login,
		LogoutURL: logout,
		Bills:     bills,
		Senators:  senators}
	if err := adminTemplate.Execute(w, pageInfo); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Ejemplo n.º 4
0
func webuserOK(c appengine.Context, w http.ResponseWriter, r *http.Request) bool {
	if !userauthenticated(c) {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return false
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return false
	}
	u := user.Current(c)
	authzed, err := userauthorized(c, u.Email)
	if err != nil {
		c.Errorf("authorization error: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return false
	}
	if !authzed {
		c.Warningf("authorization failure: %v", u.Email)
		w.WriteHeader(http.StatusForbidden)
		err = templates.ExecuteTemplate(w, "unauthorized.html", nil)
		if err != nil {
			c.Errorf("unauthorized user and got err on template: %v", err)
		}
		return false
	}
	return true
}
Ejemplo n.º 5
0
func createPageHeader(title string, w http.ResponseWriter, r *http.Request) *PageHeader {
	pageHeader := &PageHeader{Title: title}
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			panic("user.LoginURL error: " + err.Error())
		}
		pageHeader.UserURL = url
		pageHeader.UserLabel = "Login"
		pageHeader.IsAdmin = false

	} else {
		url, err := user.LogoutURL(c, r.URL.String())
		if err != nil {
			panic("user.LogoutURL error: " + err.Error())
		}
		pageHeader.UserURL = url
		pageHeader.UserLabel = "Logout"
		pageHeader.LoginMessage = "Hello, " + u.String() + "!"
		pageHeader.IsAdmin = user.IsAdmin(c)
		w.Header().Set("Pragma", "no-cache")
	}

	return pageHeader
}
Ejemplo n.º 6
0
// require_login is a wrapper for a function that serves web pages.
// By wrapping the function in require_login, the user is forced to
// log in to their Google account in order to access the system.
func require_login(H handler) handler {

	return func(w http.ResponseWriter, r *http.Request) {

		c := appengine.NewContext(r)

		// Force the person to log in.
		client := user.Current(c)
		if client == nil {

			U := strings.Split(r.URL.String(), "/")
			V := U[len(U)-1]
			url, err := user.LoginURL(c, V)
			if err != nil {
				http.Error(w, "Error",
					http.StatusInternalServerError)
				return
			}
			c.Infof(fmt.Sprintf("Login url: %s", url))
			msg := "To use this site, you must be logged into your Google account."
			return_msg := "Continue to login page"
			Message_page(w, r, nil, msg, return_msg, url)
			return
		}

		H(w, r)
	}
}
Ejemplo n.º 7
0
func AppstatsHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if appengine.IsDevAppServer() {
		// noop
	} else if u := user.Current(c); u == nil {
		if loginURL, err := user.LoginURL(c, r.URL.String()); err == nil {
			http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
		} else {
			serveError(w, err)
		}
		return
	} else if !u.Admin {
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	if detailsURL == r.URL.Path {
		Details(w, r)
	} else if fileURL == r.URL.Path {
		File(w, r)
	} else if strings.HasPrefix(r.URL.Path, staticURL) {
		Static(w, r)
	} else {
		Index(w, r)
	}
}
Ejemplo n.º 8
0
func handler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		loginUrl, _ := user.LoginURL(c, "/todo")
		http.Redirect(w, r, loginUrl, http.StatusFound)
		return
	}

	// start 2 OMIT
	t, err := template.ParseFiles("todo/todo.tmpl") // テンプレート読み込み // HL
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-type", "text/html; charset=utf-8")

	logoutUrl, _ := user.LogoutURL(c, "/")

	params := struct {
		LogoutUrl string
		User      *user.User
	}{
		logoutUrl,
		u,
	}

	err = t.Execute(w, params) // テンプレート適用! // HL
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// end 2 OMIT
}
Ejemplo n.º 9
0
// NewParams returns a new initialized Params
func NewParams(r *http.Request, page *Page) *Params {
	now := time.Now()
	c := appengine.NewContext(r)

	p := Params{Pages: Pages, PathPageMap: PathPageMap, NamePageMap: NamePageMap,
		Request: r, Mobile: isMobile(r), Page: page, Start: now, AppCtx: c,
		Custom: make(map[string]interface{})}

	p.User = user.Current(c)

	if p.User == nil {
		p.LoginURL, p.Err = user.LoginURL(c, r.URL.String())
	} else {
		p.LogoutURL, p.Err = user.LogoutURL(c, r.URL.String())
		if p.Err != nil {
			// Log if error, but this is not a show-stopper:
			c.Errorf("Error getting logout URL: %s", p.Err.Error())
		}
		p.Account, p.Err = cache.GetAccount(p.Request, c, p.User)
	}
	if p.Err != nil {
		c.Errorf("ERROR: %s", p.Err.Error())
	}

	return &p
}
Ejemplo n.º 10
0
Archivo: game.go Proyecto: f4rez/Cronos
func GetGameInfo(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		c.Infof("Not logged in")
		url, _ := user.LoginURL(c, "/")
		fmt.Fprintf(w, `<a href="%s">Sign in or register</a>`, url)
		return
	}
	if !users.IsUserSignedIn(c) {
		fmt.Fprintf(w, "Not Registerd")
		return
	}
	id, pErr := strconv.ParseInt(r.FormValue("game_id"), 10, 32)
	if pErr != nil {
		c.Infof("Error parseing int: %v", pErr)
		http.Error(w, pErr.Error(), http.StatusInternalServerError)
		return
	}
	mGame, _, err := GetGame(c, int(id))
	if err != nil {
		c.Infof("Error getting game: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	mess, jErr := json.Marshal(mGame)
	if jErr != nil {
		c.Infof("Error json marshal: %v", jErr)
		http.Error(w, jErr.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, string(mess))

}
Ejemplo n.º 11
0
func ensureProfile(w http.ResponseWriter, r *http.Request) (*datastore.Key, *Profile) {
	c := appengine.NewContext(r)
	u := user.Current(c)

	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())

		check(err)

		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return nil, nil
	}

	q := datastore.NewQuery("Profile").Filter("Username="******"Profile", nil), &p)

	check(err)

	w.Header().Set("Location", r.URL.String())
	w.WriteHeader(http.StatusFound)

	return nil, nil
}
func registration(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	u := User{
		Name:      "TestHendrik",
		StartDate: datastore.SecondsToTime(time.Seconds()),
	}

	if g := user.Current(c); g != nil {
		var u2 User
		u.Account = g.String()
		if err := datastore.Get(c, datastore.NewKey("user", g.String(), 0, nil), &u2); err == datastore.ErrNoSuchEntity {
			key, err := datastore.Put(c, datastore.NewKey("user", u.Account, 0, nil), &u)
			if err != nil {
				http.Error(w, err.String(), http.StatusInternalServerError)
				return
			}
			fmt.Fprintf(w, "User %q stored %q", u.Account, key)
			return
		} else {
			fmt.Fprintf(w, "User %q  is already logged in", g.String())
			return
		}
	} else {
		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
	}

}
Ejemplo n.º 13
0
func Root(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	var u *user.User
	if u = user.Current(c); u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}

	// Get last numEntries entries & display them
	q := datastore.NewQuery("Entry").Ancestor(userKey(u.Email, c)).Order("-Time").Limit(numEntries)
	entries := make([]entry.Entry, 0, numEntries)
	if _, err := q.GetAll(c, &entries); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	for i := 0; i < len(entries)/2; i++ {
		entries[i], entries[len(entries)-i-1] = entries[len(entries)-i-1], entries[i]
	}
	for i, _ := range entries {
		entries[i].Time = entries[i].Time.Round(10 * time.Millisecond)
	}
	if err := homeTemplate.Execute(w, map[string]interface{}{
		"User":    u.Email,
		"Entries": entries}); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Ejemplo n.º 14
0
func AdminHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	db := DB{c}
	adminUser := user.Current(c)
	if adminUser == nil {
		url, _ := user.LoginURL(c, "/admin/dashboard")
		http.Redirect(w, r, url, 301)
		return
	}
	if r.Method == "GET" {
		dir := path.Join(os.Getenv("PWD"), "templates")
		admin := path.Join(dir, "admin.html")
		data := map[string]interface{}{"user": adminUser.String(), "config": Config}
		page := mustache.RenderFile(admin, data)
		fmt.Fprint(w, page)
	} else if r.Method == "POST" {
		if len(r.FormValue("v")) == 0 {
			return
		}
		switch r.FormValue("op") {
		case "UnqueueUser":
			db.Context.Infof("unqueuing %v", r.FormValue("v"))
			db.UnqueueUser(r.FormValue("v"))
		case "BatchUsers":
			users := strings.Split(r.FormValue("v"), ",")
			for _, v := range users {
				QueueUser(v, c)
			}
		}
		fmt.Fprintf(w, "{\"op\":\"%v\",\"success\":true}", r.FormValue("op"))
	}
}
Ejemplo n.º 15
0
func root(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" || r.URL.Path != "/" {
		serve404(w)
		return
	}

	c := appengine.NewContext(r)
	u := user.Current(c)

	gg, err := brg.GetBuriggies(c, 100)
	if err != nil {
		serveError(c, w, err)
		return
	}

	log.Println("hoi")
	loginUrl, _ := user.LoginURL(c, "/")
	logoutUrl, _ := user.LogoutURL(c, "/")
	mdi := modelIndex{Buriggies: gg, User: u, LoginUrl: loginUrl, LogoutUrl: logoutUrl}

	t, errTpl := template.ParseFiles("code/main.tpl")
	if errTpl != nil {
		serveError(c, w, errTpl)
		return
	}

	if err := t.Execute(w, mdi); err != nil {
		c.Errorf("%v", err)
	}
}
Ejemplo n.º 16
0
/**
 * get logout link with redirection url
 * @param  {[type]} w http.ResponseWriter [description]
 * @param  {[type]} r *http.Request       [description]
 * @return {[type]}   [description]
 */
func getAdminUserLogout(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}

	redirect := Redirect{}
	if err := json.Unmarshal(body, &redirect); err != nil {
		SetError(w, r, 400, "")
		return
	}

	u := user.Current(c)
	connected := (u != nil)
	if !connected {
		uriResponse := &Uri{
			Uri: "",
		}
		json.NewEncoder(w).Encode(uriResponse)
	} else {
		uri, _ := user.LoginURL(c, redirect.Redirect)
		uriResponse := &Uri{
			Uri: uri,
		}
		json.NewEncoder(w).Encode(uriResponse)
	}
	return
}
Ejemplo n.º 17
0
/**
 * get admin user info and connect/disconnect link
 * @param  {[type]} w http.ResponseWriter [description]
 * @param  {[type]} r *http.Request       [description]
 * @return {[type]}   [description]
 */
func getCurrentUser(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	u := user.Current(c)
	connected := (u != nil)
	if !connected {
		uri, _ := user.LoginURL(c, "/")
		currentUser := &CurrentUser{
			Connected: connected,
			Admin:     false,
			Config:    true,
			Uri:       uri,
		}
		json.NewEncoder(w).Encode(currentUser)
	} else {
		uri, _ := user.LogoutURL(c, "/")
		currentUser := &CurrentUser{
			Connected: connected,
			Admin:     u.Admin,
			Config:    true,
			Uri:       uri,
		}
		json.NewEncoder(w).Encode(currentUser)
	}
	return
}
Ejemplo n.º 18
0
func fg(w http.ResponseWriter, r *http.Request) {
	// Start by checking so that the user is logged in!
	c := appengine.NewContext(r)
	c.Infof("THis is info")
	u := user.Current(c)
	if u == nil {
		c.Infof("User not signed in")
		// Generate a response that may be used to login the user
		// since this might be needed!
		str, er := user.LoginURL(c, "https://vronpass.appspot.com/")
		if er != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		w.WriteHeader(http.StatusUnauthorized)
		w.Write([]byte(str))
		return
	}

	// We simply store the information under the username!
	path := u.Email

	k := datastore.NewKey(c, "Entity", path, 0, nil)
	e := new(Entity)
	if err := datastore.Get(c, k, e); err != nil {
		// This does not exist so simply return a empty response
		w.Write([]byte("{}"))
		return
	}
	// Otherwise return the string
	w.Write([]byte(e.Value))
}
Ejemplo n.º 19
0
func admin(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.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}

	/* Si el usuario es administrador. */
	if user.IsAdmin(c) {

		categorias := getCategorias(c, 10)

		contenido := ContenidoAdmin{categorias}

		/* Ejecuto el template y envio la salida al Writer. */
		err2 := adminTpl.Execute(w, contenido)

		if err2 != nil {
			http.Error(w, err2.Error(), http.StatusInternalServerError)
		}
	} else {
		fmt.Fprint(w, "El usuario no es admin.")
	}
}
Ejemplo n.º 20
0
func handler(w http.ResponseWriter, r *http.Request) {
	// [START new_context]
	c := appengine.NewContext(r)
	// [END new_context]
	// [START get_current_user]
	u := user.Current(c)
	// [END get_current_user]
	// [START if_user]
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	w.Header().Set("myLocation", r.URL.String())
	w.Header().Set("myname", "todd")
	w.WriteHeader(http.StatusOK)
	// [END if_user]
	// [START output]
	fmt.Fprintf(w, "Hello, %v!", u)
	// [END output]
}
Ejemplo n.º 21
0
func root(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	pageData := TodoPageData{}

	if u := user.Current(c); u == nil {
		pageData.Username = "******"
		url, err := user.LoginURL(c, r.URL.String())
		handleErr(w, err)
		pageData.LoginUrl = url
	} else {
		pageData.Username = u.String()
		url, err := user.LogoutURL(c, r.URL.String())
		handleErr(w, err)
		pageData.LoginUrl = url
	}

	q := datastore.NewQuery(pageData.Username).Order("-Created").Limit(10)
	//make is like a constructor
	//[] is a "slice", ref counted, dynamic array
	items := make([]TodoItem, 0, 10)

	_, err := q.GetAll(c, &items)
	pageData.TodoItems = items

	templ, err := template.ParseFiles("todo.html")
	handleErr(w, err)
	err = templ.Execute(w, pageData) // populate html page with data from pageData
	handleErr(w, err)
}
Ejemplo n.º 22
0
func Admin(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	an := AdminPage{"", ""}
	var templ = ""

	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	c.Debugf("User present %v", u)
	an.Admin_email = u.Email
	templ = "adminIndex"
	url, err := user.LogoutURL(c, "/admin")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	an.LogoutUrl = url
	err = templates.ExecuteTemplate(w, templ, an)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Ejemplo n.º 23
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)
}
Ejemplo n.º 24
0
func LoginPageHtml(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	client := urlfetch.Client(c)

	loginPageURL, _ := user.LoginURL(c, "/admin/")

	if !strings.HasPrefix(loginPageURL, "http") {
		loginPageURL = "https://goblog-geoct826.c9.io/" + loginPageURL
	}

	loginPageURL = loginPageURL + "&output=embed"

	resp, err := client.Get(loginPageURL)

	if err != nil {
		//log.Println(err)
		fmt.Fprintf(w, "Sorry, something went wrong")
		return
	}

	defer resp.Body.Close()

	contents, err1 := ioutil.ReadAll(resp.Body)

	if err1 != nil {
		//log.Println(err)
		fmt.Fprintf(w, "Sorry, something went wrong")
		return
	}

	fmt.Fprintf(w, string(contents))
}
Ejemplo n.º 25
0
func ninjalogForm(w http.ResponseWriter, req *http.Request) {
	if req.Method == "POST" {
		ninjalogUpload(w, req)
		return
	}
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)
	login, err := user.LoginURL(ctx, "/ninja_log/")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	logout, err := user.LogoutURL(ctx, "/ninja_log/")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/html")
	w.WriteHeader(http.StatusOK)
	data := struct {
		User   *user.User
		Login  string
		Logout string
	}{
		User:   u,
		Login:  login,
		Logout: logout,
	}
	err = formTmpl.Execute(w, data)
	if err != nil {
		ctx.Errorf("formTmpl: %v", err)
	}

}
Ejemplo n.º 26
0
func SearchHandler(w http.ResponseWriter, r *http.Request) {
	data := make(map[string]string)
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u != nil {
		data["Email"] = u.String()
		upload_url, upload_err := blobstore.UploadURL(c, "/upload")
		if upload_err != nil {
			c.Logf("blob store is disabled? %v", upload_err)
			data["Upload_Action"] = "/upload"
		} else {
			data["Upload_Action"] = upload_url.String()
		}
	} else {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
		data["Login_url"] = url
	}
	data["Base_person"] =
		"{\"name\": \"James Morrison\", \"Date of Birth\": [1981, 10, 2]}"

	template_err := searchTemplate.Execute(w, data)
	if template_err != nil {
		log.Print("Error rendering template ", template_err)
	}
}
Ejemplo n.º 27
0
func newgame(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.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	url, err := user.LogoutURL(c, r.URL.String())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	i := Index{
		User:  u.Email,
		Login: false,
		URL:   url,
	}
	if err := newGameTemplate.Execute(w, i); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Ejemplo n.º 28
0
func handlePost(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if r.Method != "GET" || r.URL.Path != "/post" {
		serve404(w)
		return
	}
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			serveError(c, w, err)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	if !user.IsAdmin(c) {
		serve404(w)
		return
	}
	uploadURL, err := blobstore.UploadURL(c, "/upload", nil)
	if err != nil {
		serveError(c, w, err)
		return
	}
	err = postTemplate.Execute(w, uploadURL)
	if err != nil {
		serveError(c, w, err)
	}
}
Ejemplo n.º 29
0
// NewPage returns a new Page initialized embedding the template with the
// given name and data, the current user for the given context, and the
// latest announcement.
func NewPage(ctx appengine.Context, name string, data interface{}) (*Page, error) {
	p := &Page{
		Content: name,
		Data:    data,
		Topics:  topicList,
		Cities:  cityList,
	}

	a, err := conf.LatestAnnouncement(ctx)
	if err != nil {
		ctx.Errorf("latest announcement: %v", err)
	}
	if a != nil {
		p.Announcement = a.Message
	}

	if u := user.Current(ctx); u != nil {
		p.User = u
		p.LogoutURL, err = user.LogoutURL(ctx, "/")
	} else {
		p.LoginURL, err = user.LoginURL(ctx, "/")
	}

	return p, err
}
Ejemplo n.º 30
0
func root(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.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}

	q := datastore.NewQuery("Greeting").Ancestor(guestbookKey(c)).Order("-Date").Limit(10)
	greetings := make([]Greeting, 0, 10)
	if _, err := q.GetAll(c, &greetings); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if err := guestbookTemplate.Execute(w, greetings); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}