Example #1
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").Order("-Timestamp").Limit(10)
	greetings := make([]Greeting, 0, 10)
	if _, err := q.GetAll(c, &greetings); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	url, _ := user.LogoutURL(c, "/")
	if err := guestBookTemplate.Execute(w,
		struct {
			LogoutUrl string
			Greetings []Greeting
		}{url, greetings}); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Example #2
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)
	}
}
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)
	}
}
Example #4
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)
	}
}
Example #5
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)
	}

}
Example #6
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
}
Example #7
0
func filterUsers(f http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c := appengine.NewContext(r)
		u := user.Current(c)
		if u == nil {
			w.Header().Set(
				"Content-type",
				"text/plain; charset=utf-8")
			w.WriteHeader(http.StatusInternalServerError)
			io.WriteString(w, "'login: required' is needed at app.yaml.\n")
			return
		}
		if _, ok := permittedUserEmails[u.Email]; !ok {
			w.Header().Set(
				"Content-type",
				"text/html; charset=utf-8")
			url, _ := user.LogoutURL(c, "/")
			w.WriteHeader(http.StatusForbidden)
			forbiddenTmpl.Execute(w, map[string]interface{}{
				"LogoutURL": url,
			})
			return
		}
		f(w, r)
	}
}
Example #8
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
}
Example #9
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
	}
}
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
}
Example #11
0
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	url, _ := user.LogoutURL(c, "/")
	w.Header().Set("Location", url)
	w.WriteHeader(http.StatusFound)
	return
}
Example #12
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
}
Example #13
0
func rootHandler(e env) {
	userKey, done := getUser(e)
	if done {
		return
	}

	q := datastore.NewQuery("projectTop").Ancestor(userKey).KeysOnly()

	e.w.Header().Set("Content-type", "text/html; charset=utf-8")
	fmt.Fprintf(e.w, `<ul>`)
	for t := q.Run(e.ctx); ; {
		key, err := t.Next(nil)
		if err == datastore.Done {
			break
		}
		if err != nil {
			e.w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintf(e.w, `</ul>Got an error retrieving projects`)
			log.Println("Error retrieving projects", err)
			return
		}

		fmt.Fprintf(e.w, `<li><a href="/%s">%s</a></li>`, key.StringID(), key.StringID())
	}
	fmt.Fprintf(e.w, `</ul>`)

	url, _ := user.LogoutURL(e.ctx, "/")
	fmt.Fprintf(e.w, `<a href="%s">Sign out</a>`, url)
}
Example #14
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)
}
func root(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)

	if u == nil {
		panic("User should not be nil")
	}
	// Ancestor queries, as shown here, are strongly consistent with the High
	// Replication Datastore. Queries that span entity groups are eventually
	// consistent. If we omitted the .Ancestor from this query there would be
	// a slight chance that Greeting that had just been written would not
	// show up in a query.
	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
	}

	url, _ := user.LogoutURL(c, "/")
	//fmt.Fprintf(w, `Welcome, %s! (<a href="%s">sign out</a>)`, u, url)

	page := GreetingPage{
		User:       u,
		SignOutURL: url,
		Greetings:  greetings,
	}

	if err := guestbookTemplate.Execute(w, page); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Example #16
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
}
Example #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
}
Example #18
0
func LogoutURL(c appengine.Context, r *http.Request) (string, error) {
	url, err := user.LogoutURL(c, r.URL.String())
	if err != nil {
		return "", err
	}
	return url, nil
}
Example #19
0
func headerLoggedIn(w http.ResponseWriter, r *http.Request, c appengine.Context, u *user.User) {
	url, err := user.LogoutURL(c, "/")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	} else {
		fmt.Fprintf(w, `Welcome, %s! (<a href="%s">sign out</a>)<br>`, u.Email, url)
	}
}
Example #20
0
func logout(res http.ResponseWriter, req *http.Request) {
	c := appengine.NewContext(req)
	logout_url, err := user.LogoutURL(c, "/")
	if error_check(res, err) {
		return
	}
	http.Redirect(res, req, logout_url, http.StatusTemporaryRedirect)
}
Example #21
0
func logout(c common.Context) {
	url, err := user.LogoutURL(c.Context, c.Req.URL.Scheme+c.Req.URL.Host)
	if err != nil {
		panic(err)
	}
	c.Resp.Header().Set("Location", url)
	c.Resp.WriteHeader(302)
}
Example #22
0
func logoutHandler(w http.ResponseWriter, r *http.Request, c Context) error {
	url, err := user.LogoutURL(c, "/")
	if err != nil {
		return err
	}
	http.Redirect(w, r, url, http.StatusFound)
	return nil
}
Example #23
0
func logout(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, _ := user.LogoutURL(c, "/")
		http.Redirect(w, r, url, http.StatusFound)
	}

}
Example #24
0
func Logout(c util.Context) (err error) {
	url, err := user.LogoutURL(c, "/")
	if err != nil {
		return
	}

	http.Redirect(c.W, c.R, url, 303)
	return
}
Example #25
0
func handleMainPage(w http.ResponseWriter, r *http.Request) {
	var pageData listPage
	pageData.SiteBase = Site
	pageData.QueryBase = Site + "/query/?"
	pageData.NumMsgs.Value = getCount(w, r)
	if r.Method != "GET" || r.URL.Path != "/" {
		serve404(w)
		return
	}
	c := appengine.NewContext(r)
	u := user.Current(c)
	pageData.U = u
	if u == nil {
		url, _ := user.LoginURL(c, "/")
		pageData.Loginbar = "<a href=\"" + url + "\">Login with google</a>"
	} else {
		url, _ := user.LogoutURL(c, "/")
		pageData.Loginbar = "Welcome," + u.String() + "(<a href=\"" + url + "\">Logout</a>)"
	}
	q := datastore.NewQuery("aMessage").Order("-Date").Limit(10)
	ks, err := q.GetAll(c, &(pageData.Msgs))
	if err != nil {
		serveError(c, w, err)
		return
	}
	// display ID from Key.IntID
	for i, _ := range pageData.Msgs {
		pageData.Msgs[i].ID = ks[i].IntID()
		pageData.Msgs[i].Content = []byte(SubstrByByte(string(pageData.Msgs[i].Content), lenSummery))
	}
	// tagcloud
	tags := new([]*Tag)
	q = datastore.NewQuery("aTag").Order("-Count").Limit(100)
	ks, err = q.GetAll(c, tags)
	if err != nil {
		serveError(c, w, err)
		return
	}
	for i, k := range ks {
		tagcount := new(TagCount)
		tagcount.TagName = k.StringID()
		tagcount.Count = (*tags)[i].Count
		pageData.TagCloud = append(pageData.TagCloud, tagcount)
	}
	//end tagcloud
	pageData.Arts = Msgs2Arts(pageData.Msgs)
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	mainPage, err := template.ParseFiles(templatePath+"msglist.html", templatePath+"articles.html", templatePath+"header.html", templatePath+"footer.html")
	if err != nil {
		c.Errorf("%v", err)
		return
	}
	if err := mainPage.Execute(w, pageData); err != nil {
		c.Errorf("%v", err)
	}
}
Example #26
0
func signoutHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	url, err := user.LogoutURL(c, "/")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Location", url)
	w.WriteHeader(http.StatusFound)
}
Example #27
0
func resolveUser() gin.HandlerFunc {
	return func(c *gin.Context) {
		gaeCtx := getGaeContext(c)
		currentGaeUser := appengineuser.Current(gaeCtx)

		var user *User
		if currentGaeUser != nil {
			dao := createDao(gaeCtx)
			userDao := userDao{dao}

			var err error
			user, err = userDao.getUserByID(currentGaeUser.ID)

			if err != nil {
				c.AbortWithError(http.StatusInternalServerError, err)
				return
			}

			if user == nil {
				user = &User{
					UserID: currentGaeUser.ID,
					Email:  currentGaeUser.Email,
				}
				userDao.saveUser(user)
			}

			user.LoggedIn = true
			if currentGaeUser.Admin {
				user.Role = Admin
			} else {
				user.Role = Standard
			}

			logoutURL, _ := appengineuser.LogoutURL(gaeCtx, "")
			user.AddLink(relLogout, logoutURL)

			user.AddLink(relPrepare, "/api/context/prepare")
		} else {
			user = &User{
				LoggedIn: false,
			}

			loginURL, err := appengineuser.LoginURL(gaeCtx, "")

			if err != nil {
				c.AbortWithError(http.StatusInternalServerError, err)
				return
			}

			user.AddLink(relLogin, loginURL)
		}

		c.Set(userKey, user)
	}
}
Example #28
0
func handleRoot(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	uinfo, err := getUser(c)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if len(uinfo.Feeds) == 0 && (r.URL.Path == "/" || r.URL.Path == "/all") {
		http.Redirect(w, r, managePage, http.StatusFound)
		return
	}

	var page = struct {
		Logout   string
		Title    string
		Link     string
		Errors   []error
		Articles Articles
	}{}

	page.Logout, err = user.LogoutURL(c, "/")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	switch r.URL.Path {
	case "/":
		page.Title = "Latest Articles"
		page.Articles, page.Errors = articles(c, uinfo, mcacheLatestPrefix)
	case "/all":
		page.Title = "All Articles"
		page.Articles, page.Errors = articles(c, uinfo, mcacheAllPrefix)

	default:
		var key *datastore.Key
		var err error
		if key, err = datastore.DecodeKey(path.Base(r.URL.Path)); err != nil {
			http.NotFound(w, r)
			return
		}
		var f FeedInfo
		f, page.Articles, page.Errors = articlesByFeed(c, key)
		page.Title = f.Title
		page.Link = f.Link
	}

	sort.Sort(page.Articles)

	if err := templates.ExecuteTemplate(w, "articles.html", page); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Example #29
0
func myHandler(c appengine.Context, w http.ResponseWriter, r *http.Request) {
	d := make(ContentData)
	u := gaeuser.Current(c)

	if u == nil || u.ID == "" {
		url, err := gaeuser.LoginURL(c, "/-/me")
		gonuts.LogError(c, err)
		d["LoginURL"] = url
		d["OpenIDURL"] = "/-/me/openid"
	} else {
		user := new(gonuts.User)
		err := datastore.Get(c, gonuts.UserKey(c, u), user)
		if err == nil {
			url, err := gaeuser.LogoutURL(c, "/")
			gonuts.LogError(c, err)
			d["LogoutURL"] = url
			d["Identifier"] = user.Identifier()
			d["Token"] = user.Token
			d["GenerateURL"] = "/-/me/generate"
			d["Vendors"] = user.Vendors
		} else if err == datastore.ErrNoSuchEntity {
			user = &gonuts.User{Id: u.ID, Email: u.Email, FederatedIdentity: u.FederatedIdentity}
			url, err := gaeuser.LogoutURL(c, "/-/me")
			gonuts.LogError(c, err)
			d["LogoutURL"] = url
			d["Identifier"] = user.Identifier()
			d["RegisterURL"] = "/-/me/register"
		} else {
			panic(err)
		}
	}

	var content bytes.Buffer
	gonuts.PanicIfErr(Base.ExecuteTemplate(&content, "me.html", d))

	bd := BaseData{
		Tabtitle: "Me",
		Title:    "Me",
		Content:  template.HTML(content.String()),
	}
	gonuts.PanicIfErr(Base.Execute(w, &bd))
}
Example #30
0
func logout(response http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	u := user.Current(context)

	if u != nil {
		url, _ := user.LogoutURL(context, request.URL.String())
		http.Redirect(response, request, url, http.StatusFound)
	} else {
		http.Redirect(response, request, "/", http.StatusFound)
	}
}