Example #1
0
func init() {
	angular_ver := "1.0.7"
	bootstrap_ver := "2.3.2"
	font_awesome_ver := "3.2.1"
	jquery_ver := "1.9.1"
	jqueryui_ver := "1.10.3"
	underscore_ver := "1.4.4"
	isDevServer = appengine.IsDevAppServer()

	if appengine.IsDevAppServer() {
		Angular = fmt.Sprintf("/static/js/angular-%v.js", angular_ver)
		BootstrapCss = fmt.Sprintf("/static/css/bootstrap-combined-no-icons-%v.css", bootstrap_ver)
		BootstrapJs = fmt.Sprintf("/static/js/bootstrap-%v.js", bootstrap_ver)
		FontAwesome = fmt.Sprintf("/static/css/font-awesome-%v.css", font_awesome_ver)
		Jquery = fmt.Sprintf("/static/js/jquery-%v.js", jquery_ver)
		JqueryUI = fmt.Sprintf("/static/js/jquery-ui-%v.js", jqueryui_ver)
		Underscore = fmt.Sprintf("/static/js/underscore-%v.js", underscore_ver)
	} else {
		Angular = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/angularjs/%v/angular.min.js", angular_ver)
		BootstrapCss = fmt.Sprintf("//netdna.bootstrapcdn.com/twitter-bootstrap/%v/css/bootstrap-combined.no-icons.min.css", bootstrap_ver)
		BootstrapJs = fmt.Sprintf("//netdna.bootstrapcdn.com/twitter-bootstrap/%v/js/bootstrap.min.js", bootstrap_ver)
		FontAwesome = fmt.Sprintf("//netdna.bootstrapcdn.com/font-awesome/%v/css/font-awesome.min.css", font_awesome_ver)
		Jquery = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/jquery/%v/jquery.min.js", jquery_ver)
		JqueryUI = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/jqueryui/%v/jquery-ui.min.js", jqueryui_ver)
		Underscore = fmt.Sprintf("/static/js/underscore-%v.min.js", underscore_ver)
	}
}
Example #2
0
func init() {
	angular_ver := "1.0.5"
	bootstrap_ver := "2.3.2"
	jquery_ver := "1.9.1"
	jqueryui_ver := "1.10.3"
	underscore_ver := "1.4.4"
	isDevServer = appengine.IsDevAppServer()

	if appengine.IsDevAppServer() {
		Angular = fmt.Sprintf("/static/js/angular-%v.js", angular_ver)
		BootstrapCss = fmt.Sprintf("/static/css/bootstrap-combined-%v.css", bootstrap_ver)
		BootstrapJs = fmt.Sprintf("/static/js/bootstrap-%v.js", bootstrap_ver)
		Jquery = fmt.Sprintf("/static/js/jquery-%v.js", jquery_ver)
		JqueryUI = fmt.Sprintf("/static/js/jquery-ui-%v.js", jqueryui_ver)
		SiteStyleCss = "/static/css/styles.css"
		Underscore = fmt.Sprintf("/static/js/underscore-%v.js", underscore_ver)
	} else {
		Angular = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/angularjs/%v/angular.min.js", angular_ver)
		BootstrapCss = fmt.Sprintf("//netdna.bootstrapcdn.com/twitter-bootstrap/%v/css/bootstrap-combined.min.css", bootstrap_ver)
		BootstrapJs = fmt.Sprintf("//netdna.bootstrapcdn.com/twitter-bootstrap/%v/js/bootstrap.min.js", bootstrap_ver)
		Jquery = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/jquery/%v/jquery.min.js", jquery_ver)
		JqueryUI = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/jqueryui/%v/jquery-ui.min.js", jqueryui_ver)
		SiteStyleCss = "/static/css/styles.css"
		Underscore = fmt.Sprintf("/static/js/underscore-%v.min.js", underscore_ver)
	}
}
Example #3
0
func init() {
	angular_ver := "1.2.1"
	bootstrap_ver := "3.0.2"
	font_awesome_ver := "4.0.3"
	jquery_ver := "2.0.3"
	jqueryui_ver := "1.10.3.sortable"
	isDevServer = appengine.IsDevAppServer()

	if appengine.IsDevAppServer() {
		Angular = "/static/js/angular.js"
		BootstrapCss = "/static/css/bootstrap.css"
		BootstrapJs = "/static/js/bootstrap.js"
		FontAwesome = "/static/css/font-awesome.css"
		Jquery = fmt.Sprintf("/static/js/jquery-%v.js", jquery_ver)
		JqueryUI = fmt.Sprintf("/static/js/jquery-ui-%v.js", jqueryui_ver)
		Underscore = "/static/js/underscore.js"
	} else {
		Angular = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/angularjs/%v/angular.min.js", angular_ver)
		BootstrapCss = fmt.Sprintf("//netdna.bootstrapcdn.com/bootstrap/%v/css/bootstrap.min.css", bootstrap_ver)
		BootstrapJs = fmt.Sprintf("//netdna.bootstrapcdn.com/bootstrap/%v/js/bootstrap.min.js", bootstrap_ver)
		FontAwesome = fmt.Sprintf("//netdna.bootstrapcdn.com/font-awesome/%v/css/font-awesome.min.css", font_awesome_ver)
		Jquery = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/jquery/%v/jquery.min.js", jquery_ver)
		JqueryUI = fmt.Sprintf("/static/js/jquery-ui-%v.min.js", jqueryui_ver)
		Underscore = "/static/js/underscore-min.js"
	}
}
Example #4
0
func hash(path string) string {
	hashmutex.Lock()
	defer hashmutex.Unlock()

	if !appengine.IsDevAppServer() {
		if cached, ok := hashcache[path]; ok {
			return cached
		}
	}

	b, e := ioutil.ReadFile(path)

	if e != nil {
		panic(e)
	}

	sha := sha256.New()
	sha.Write(b)
	sum := sha.Sum(nil)
	hash := hex.EncodeToString(sum)

	hashcache[path] = hash

	return hash
}
// Creates a new Google Cloud Storage Client
func newStorageService(c appengine.Context) (*storage.Service, error) {
	var httpClient *http.Client
	var err error

	if appengine.IsDevAppServer() {
		httpClient, err = devserviceaccount.NewClient(c, devStorageKeyPath, scope)
	} else {
		httpClient, err = serviceaccount.NewClient(c, scope)
	}

	if err != nil {
		return nil, err
	}

	service, err := storage.New(httpClient)
	if err != nil {
		return nil, err
	}

	if err = initDefaultBucket(service); err != nil {
		return nil, err
	}

	return service, nil
}
Example #6
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)
	}
}
Example #7
0
func ExecTemplate(c *TemplateConfig) error {
	cname := ""
	for i, name := range c.Names {
		c.Names[i] = filepath.Join(c.Dir, name+".html")
		cname += name
	}

	templatesMutex.Lock()
	defer templatesMutex.Unlock()

	t, ok := templatesCache[cname]
	if !ok || appengine.IsDevAppServer() {
		var err error
		t, err = template.New(cname).ParseFiles(c.Names...)
		if err != nil {
			return fmt.Errorf("templates parsing failed: %s", err)
		}
		templatesCache[cname] = t
	}

	if err := t.ExecuteTemplate(c.W, "base", c.Data); err != nil {
		return fmt.Errorf("exec templates failed: %s", err)
	}

	return nil
}
Example #8
0
func init() {
	http.HandleFunc("/", frontPageHandler)
	http.HandleFunc("/tiles", tileHandler)

	for i := range color {
		// Use a broader range of color for low intensities.
		if i < 255/10 {
			color[i] = image.RGBAColor{uint8(i * 10), 0, 0, 0xFF}
		} else {
			color[i] = image.RGBAColor{0xFF, 0, uint8(i - 255/10), 0xFF}
		}
	}

	tmpl := template.New(nil)
	tmpl.SetDelims("{{", "}}")
	if err := tmpl.ParseFile("map.html"); err != nil {
		frontPage = []byte("tmpl.ParseFile failed: " + err.String())
		return
	}
	b := new(bytes.Buffer)
	data := map[string]interface{}{
		"InProd": !appengine.IsDevAppServer(),
	}
	if err := tmpl.Execute(b, data); err != nil {
		frontPage = []byte("tmpl.Execute failed: " + err.String())
		return
	}
	frontPage = b.Bytes()
}
Example #9
0
func wrapHandler(f func(w http.ResponseWriter, r *http.Request) error) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		// pre ops:
		// - setup response
		front_origin := ""
		if appengine.IsDevAppServer() {
			front_origin = "http://127.0.0.1:9000"
		} else {
			front_origin = "http://pgu-geo-ng.appspot.com"
		}

		w.Header().Set("Access-Control-Allow-Origin", front_origin)
		w.Header().Set("Content-Type", "application/json")

		// execute handler
		err := f(w, r)

		// post ops
		// - handle an error
		if err == nil {
			return
		}
		switch err.(type) {
		case badRequest:
			http.Error(w, err.Error(), http.StatusBadRequest)
		case notFound:
			http.Error(w, "entity not found", http.StatusNotFound)
		default:
			log.Println(err)
			http.Error(w, "oops", http.StatusInternalServerError)
		}
	}
}
Example #10
0
func ExecTemplate(c *TemplateConfig) error {
	templatesMutex.Lock()
	defer templatesMutex.Unlock()

	cname := ""
	for i, name := range c.Names {
		c.Names[i] = filepath.Join(c.Dir, name+".html")
		cname += name
	}

	t, ok := templatesCache[cname]
	if !ok || appengine.IsDevAppServer() {
		var err error
		t = template.New(cname).Delims(c.LeftDelim, c.RightDelim)

		t, err = t.Funcs(templatesFuncs).ParseFiles(c.Names...)
		if err != nil {
			return errors.New(err)
		}
		templatesCache[cname] = t
	}

	if err := t.ExecuteTemplate(c.W, "base", c.Data); err != nil {
		return errors.New(err)
	}

	return nil
}
Example #11
0
func init() {
	page.DevCssFiles = []string{
		"reset.css",
		"general.css",
		"form.css",
		"subreddit-picker.css",
		"board.css",
		"board-item.css",
	}

	page.CompiledCssFile = "1uePdv.css"
	page.CompiledJsFile = "1vkcJu.js"
	page.IsDevAppServer = appengine.IsDevAppServer()

	var err error
	if cachedTemplate, err = loadTemplate(); err != nil {
		http.HandleFunc("/", handleInitError(err))
		return
	}

	http.HandleFunc("/", handleRequest)

	// The most requested URL that doesn't exist anymore. Handling it outside of
	// handleRequest avoids expensive RegEx testing that is going on in
	// handleRequest.
	http.HandleFunc("/feeds/atom/", handleFeedRequest)
}
Example #12
0
func CheckForAdminUser(r *http.Request) (bool, *user.User, string) {

	if appengine.IsDevAppServer() {
		return true, &user.User{Email: "*****@*****.**", Admin: true, ID: "32168"}, "DevServer login granted"
	}

	u, msg := UserFromReq(r)

	if u == nil {
		msg = "google appengine oauth required - admin rights - no login found \n" + msg
		msg = "use /appengine/login\n" + msg
		return false, nil, msg
	}
	if u != nil && !u.Admin {
		msg = "google appengine oauth required - admin rights - login found without admin \n" + msg
		msg = "use /appengine/login\n" + msg
		return false, nil, msg
	}

	// if u.ID != "108853175242330402880" && u.ID != "S-1-5-21-2175189548-897864986-1736798499-1000" {
	// }

	return true, u, msg

}
Example #13
0
// Wraps other http handlers. Creates context object, recovers from panics, etc.
func WrapHandlerImpl(fn AppHandlerFunc, parseForm bool) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c := &Context{}

		// See http://blog.golang.org/2010/08/defer-panic-and-recover.html.
		defer func() {
			if data := recover(); data != nil {
				c.Aec().Errorf(fmt.Sprint(data))
				ServeError(w, data)
			}
		}()

		// Initialize the request context object.
		c.SetAec(appengine.NewContext(r))
		CheckError(ReadSession(r, c))
		if msg, err := ConsumeFlash(w, r); err != nil && err != http.ErrNoCookie {
			ServeError(w, err)
			return
		} else {
			c.SetFlash(msg)
		}

		if parseForm {
			CheckError(r.ParseForm())
		}

		if appengine.IsDevAppServer() {
			tmpl = template.Must(template.ParseGlob("templates/*.html"))
			text_tmpl = text_template.Must(text_template.ParseGlob("templates/*.txt"))
		}
		fn(w, r, c)
	}
}
Example #14
0
func init() {
	var err error
	local, err = time.LoadLocation("America/New_York")
	if err != nil {
		panic(err)
	}
	http.Handle("/", webapp.Router)
	webapp.HandleFunc("/", index)
	webapp.HandleFunc("/class", class)
	webapp.Handle("/roster", userContextHandler(webapp.HandlerFunc(roster)))
	if appengine.IsDevAppServer() {
		webapp.HandleFunc("/error", throwError)
	}

	for url, template := range map[string]string{
		"/about":           "templates/about.html",
		"/pricing":         "templates/pricing.html",
		"/privates-groups": "templates/privates-groups.html",
		"/teachers":        "templates/teachers.html",
		"/workshops":       "templates/workshops.html",
		"/mailinglist":     "templates/mailinglist.html",
	} {
		webapp.HandleFunc(url, staticTemplate(template))
	}
}
Example #15
0
func init() {
	if appengine.IsDevAppServer() {
		ContextFactory = tokeninfoContextFactory
	} else {
		ContextFactory = cachingContextFactory
	}
}
Example #16
0
func InitHandlers() {

	initCodeBaseDir()

	// Register datatypes such that it can be saved in the session.
	gob.Register(SessionUserKey(0))
	gob.Register(&User{})

	// Initialize XSRF token key.
	xsrfKey = "My personal very secure XSRF token key"

	sessKey := []byte("secure-key-234002395432-wsasjasfsfsfsaa-234002395432-wsasjasfsfsfsaa-234002395432-wsasjasfsfsfsaa")

	// Create a session cookie store.
	cookieStore = sessions.NewCookieStore(
		sessKey[:64],
		sessKey[:32],
	)

	cookieStore.Options = &sessions.Options{
		MaxAge:   maxSessionIDAge, // Session valid for 30 Minutes.
		HttpOnly: true,
	}

	// Create identity toolkit client.
	c := &gitkit.Config{
		ServerAPIKey: getConfig(siteName, "serverAPIKey"),
		ClientID:     getConfig(siteName, "clientID"),
		WidgetURL:    WidgetSigninAuthorizedRedirectURL,
	}
	// Service account and private key are not required in GAE Prod.
	// GAE App Identity API is used to identify the app.
	if appengine.IsDevAppServer() {
		c.ServiceAccount = getConfig(siteName, "serviceAccount")
		c.PEMKeyPath = privateKeyPath
	}
	var err error
	gitkitClient, err = gitkit.New(c)
	if err != nil {
		log.Fatal(err)
	}

	// The gorilla sessions use gorilla request context
	ClearHandler := func(fc http.HandlerFunc) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			defer gorillaContext.Clear(r)
			fc(w, r)
		})
	}

	http.Handle(homeURL, ClearHandler(handleHome))

	http.Handle(WidgetSigninAuthorizedRedirectURL, ClearHandler(handleWidget))
	http.Handle(signOutURL, ClearHandler(handleSignOut))

	http.Handle(signinLandingDefaultURL, ClearHandler(handleSigninSuccessLanding))
	http.Handle(signoutLandingDefaultURL, ClearHandler(handleSignOutLanding))

	http.HandleFunc(accountChooserBrandingURL, accountChooserBranding)
}
Example #17
0
func cron(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	q := datastore.NewQuery("asin")

	for t := q.Run(c); ; {
		var x Asin
		_, err := t.Next(&x)
		if err == datastore.Done {
			break
		}
		if err != nil {
			return
		}

		task := taskqueue.NewPOSTTask("/task/fetching", url.Values{
			"asin": {x.Name},
		})

		if !appengine.IsDevAppServer() {
			host := backendName + "." + appengine.DefaultVersionHostname(c)
			task.Header.Set("Host", host)
		}

		if _, err := taskqueue.Add(c, task, ""); err != nil {
			c.Errorf("add fetching task: %v", err)
			http.Error(w, "Error: couldn't schedule fetching task", 500)
			return
		}

		fmt.Fprintf(w, "OK")
	}
}
Example #18
0
func aboutPage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	fmt.Fprintf(w, "<h1>%v</h1>", appengine.DefaultVersionHostname(c))

	token, expire, _ := appengine.AccessToken(c, "test")
	fmt.Fprintf(w, "<p>AccessToken: %v %v", token, expire)

	fmt.Fprintf(w, "<p>AppID: %v", appengine.AppID(c))
	fmt.Fprintf(w, "<p>FQAppID: %v", c.FullyQualifiedAppID())
	fmt.Fprintf(w, "<p>Go version: %v", runtime.Version())
	fmt.Fprintf(w, "<p>Datacenter: %v", appengine.Datacenter())
	fmt.Fprintf(w, "<p>InstanceID: %v", appengine.InstanceID())
	fmt.Fprintf(w, "<p>IsDevAppServer: %v", appengine.IsDevAppServer())
	fmt.Fprintf(w, "<p>RequestID: %v", appengine.RequestID(c))
	fmt.Fprintf(w, "<p>ServerSoftware: %v", appengine.ServerSoftware())

	sa, _ := appengine.ServiceAccount(c)
	fmt.Fprintf(w, "<p>ServiceAccount: %v", sa)

	keyname, signed, _ := appengine.SignBytes(c, []byte("test"))
	fmt.Fprintf(w, "<p>SignBytes: %v %v", keyname, signed)
	fmt.Fprintf(w, "<p>VersionID: %v", appengine.VersionID(c))

	fmt.Fprintf(w, "<p>Request: %v", r)
	r2 := c.Request()
	fmt.Fprintf(w, "<p>Context Request type/value: %T %v", r2, r2)
}
Example #19
0
// EnableIfAdminOrDev returns true if this is the dev server or the current
// user is an admin. This is the default for miniprofiler.Enable.
func EnableIfAdminOrDev(r *http.Request) bool {
	if appengine.IsDevAppServer() {
		return true
	}
	c := appengine.NewContext(r)
	u := user.Current(c)
	return u.Admin
}
/* Main entry function on app engine */
func init() {
	http.HandleFunc("/", home)
	http.HandleFunc("/list", managelist)
	http.HandleFunc("/list/", manageitem)
	if !appengine.IsDevAppServer() {
		config.RedirectURL = "http://plussytodo.appspot.com/"
	}
}
Example #21
0
func IsLocalHostedOrOnDevBranch(r *http.Request) bool {
	if appengine.IsDevAppServer() {
		return true
	}
	if strings.ToLower(r.URL.Host[:4]) == "dev." {
		return true
	}
	return false
}
Example #22
0
func printLog(c appengine.Context, v string) {

	if appengine.IsDevAppServer() {
		log.Println(v)
	} else {
		c.Logf("%v", v)
	}

}
Example #23
0
func validKey(c appengine.Context, key, builder string) bool {
	if appengine.IsDevAppServer() {
		return true
	}
	if key == secretKey(c) {
		return true
	}
	return key == builderKey(c, builder)
}
Example #24
0
func handler(w http.ResponseWriter, r *http.Request) {
	isDev := appengine.IsDevAppServer()

	if isDev {
		//trueの時は開発サーバ
		fmt.Fprintf(w, "開発サーバで実行中\n")
	} else {
		fmt.Fprintf(w, "本番環境で実行中\n")
	}
}
Example #25
0
func allowShare(r *http.Request) bool {
	if appengine.IsDevAppServer() {
		return true
	}
	switch r.Header.Get("X-AppEngine-Country") {
	case "", "ZZ", "CN":
		return false
	}
	return true
}
Example #26
0
func init() {
	if !appengine.IsDevAppServer() {
		compileTemplates()
	}

	http.HandleFunc("/", Index)
	http.HandleFunc("/bug/", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "https://github.com/jshint/jshint-next/issues/new", 302)
	})
}
Example #27
0
func gaeUrl() string {
	if appengine.IsDevAppServer() {
		return "http://localhost:8080"
	} else {
		// Include your URL on App Engine here.
		// I found no way to get AppID without appengine.Context and this always
		// based on a http.Request.
		return "http://federatedservices.appspot.com"
	}
}
Example #28
0
func init() {
	Files = &fileembed.Files{
		DirFallback: "uistatic",

		// In dev_appserver, allow edit-and-reload without
		// restarting. In production, though, it's faster to just
		// slurp it in.
		SlurpToMemory: !appengine.IsDevAppServer(),
	}
}
Example #29
0
func IsUserAdminOrDev(r *http.Request) bool {
	if appengine.IsDevAppServer() {
		return true
	}
	c := appengine.NewContext(r)
	if u := user.Current(c); u != nil {
		return u.Admin
	}
	return false
}
Example #30
0
func syncFeeds(pfc *PFContext) (interface{}, error) {
	c := pfc.C

	staleDuration := time.Duration(subscriptionStalePeriodInMinutes) * time.Minute
	if appengine.IsDevAppServer() {
		// On dev server, stale period is 1 minute
		staleDuration = time.Duration(1) * time.Minute
	}

	userSubscriptions, err := storage.NewUserSubscriptions(c, pfc.UserID)
	if err != nil {
		return nil, err
	}

	if time.Since(pfc.User.LastSubscriptionUpdate) > staleDuration {
		pfc.User.LastSubscriptionUpdate = time.Now()
		if err := pfc.User.Save(c); err != nil {
			c.Warningf("Could not write user object back to store: %s", err)
		} else {
			started := time.Now()

			// Determine if new feeds are available
			if needRefresh, err := storage.AreNewEntriesAvailable(c, userSubscriptions.Subscriptions); err != nil {
				c.Warningf("Could not determine if new entries are available: %s", err)
			} else if needRefresh {
				if appengine.IsDevAppServer() {
					c.Debugf("Subscriptions need update; initiating a refresh (took %s)", time.Since(started))
				}

				if err := startTask(pfc, "syncFeeds", nil, refreshQueue); err != nil {
					c.Warningf("Could not initiate the refresh task: %s", err)
				}
			} else {
				if appengine.IsDevAppServer() {
					c.Debugf("Subscriptions are up to date (took %s)", time.Since(started))
				}
			}
		}
	}

	return userSubscriptions, nil
}