示例#1
0
// GetUserInfoHandler returns either the location where the user can log into
// the app, or metadata about the currently authenticated user.
func GetUserInfoHandler(w util.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)

	dest := mux.Vars(r)["dest"]
	if dest == "" {
		dest = "/"
	}

	if u == nil {
		url, err := user.LoginURL(c, dest)
		w.WriteJSON(map[string]interface{}{"loginURL": url}, err)
		return
	}

	// Check if the user exists in the database
	q := datastore.NewQuery("Users").Limit(1)
	q.Filter("GoogleID = ", u.ID)

	var results []User
	keys, err := q.GetAll(c, &results)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if len(results) == 0 {
		newUser := User{
			GoogleID:    u.ID,
			CreatedTime: time.Now(),
			Email:       u.Email,
		}

		key := datastore.NewIncompleteKey(c, "Users", nil)
		newKey, err := datastore.Put(c, key, &newUser)

		if newKey != nil {
			newUser.ID = newKey.IntID()
		}

		url, _ := user.LogoutURL(c, dest)
		newUser.LogoutURL = url
		w.WriteJSON(newUser, err)
		return
	}

	url, _ := user.LogoutURL(c, dest)

	fullUser := results[0]
	fullUser.ID = keys[0].IntID()
	fullUser.LogoutURL = url

	w.WriteJSON(fullUser, nil)
}
示例#2
0
文件: tada.go 项目: catamorphism/tada
func rootHandler(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	u := user.Current(ctx)
	if u == nil {
		url, _ := user.LoginURL(ctx, "/")
		fmt.Fprintf(w, `<a href="%s">Sign in or register</a>`, url)
		return
	}

	fmt.Fprint(w, `<html><h1>Hi! Welcome to Tada</h1>`)

	fmt.Fprint(w, "<!-- About to call writeItems -->")

	fmt.Fprint(w, `<ol>`)
	writeItems(w, r, u)
	fmt.Fprint(w, `</ol>`)

	fmt.Fprint(w, "<!-- Called writeItems -->")

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

	fmt.Fprint(w, `</html>`)

	makeNewItemForm(w)
}
示例#3
0
// Retrieve User object and return the user's email
// If the user is logged in, return a logout URL so
// the user can logout
func GetUser(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	u := user.Current(c)
	localUser := new(User)

	if u == nil {
		url, _ := user.LoginURL(c, "/")

		localUser.Url = url
		data, err := json.MarshalIndent(localUser, "", "\t")
		if err != nil {
			panic(err)
		}

		w.Write(data)
		return
	}

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

	localUser.Url = url
	localUser.Email = u.Email
	data, err := json.MarshalIndent(localUser, "", "\t")
	if err != nil {
		panic(err)
	}

	w.Write(data)
}
示例#4
0
文件: goploy.go 项目: mottam/goploy
func loginWithGoogle() gin.HandlerFunc {
	return func(c *gin.Context) {
		ctx := appengine.NewContext(c.Request)
		u := user.Current(ctx)
		if u == nil {
			url, _ := user.LoginURL(ctx, c.Request.URL.String())
			c.HTML(302, "login.tmpl", gin.H{
				"url": url,
			})
			c.Abort()
			return
		}
		email := strings.Split(u.Email, "@")
		if email[1] == "elo7.com" && len(email) == 2 {
			developer := models.Developer{Email: u.Email}
			developer.Create(&db)

			log.Infof(ctx, developer.Email)
		} else {
			url, _ := user.LogoutURL(ctx, "/")
			c.Redirect(http.StatusTemporaryRedirect, url)
		}
		c.Next()
	}
}
示例#5
0
func index(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	// user.Current gives data about what the requester is
	// logged in as, or nil if they are not logged in.
	u := user.Current(ctx)

	var model indexModel

	// If they are not nil, they are logged in.
	if u != nil {
		// So let the template know, and get the logout url.
		model.Login = true
		logoutURL, err := user.LogoutURL(ctx, "/")
		if err != nil {
			log.Errorf(ctx, err.Error())
			http.Error(res, "Server Error", http.StatusInternalServerError)
			return
		}
		model.LogoutURL = logoutURL
	} else {
		// Otherwise, get the login url.
		loginURL, err := user.LoginURL(ctx, "/")
		if err != nil {
			log.Errorf(ctx, err.Error())
			http.Error(res, "Server Error", http.StatusInternalServerError)
			return
		}
		model.LoginURL = loginURL
	}
	tpl.ExecuteTemplate(res, "index", model)
}
示例#6
0
文件: api.go 项目: dherbst/lmjrfll
// If the user is not logged in, then return the login url.  Otherwise return a json
// structure containing the user's name and email address, and which team they are on.
func Api1UserProfileHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	data := UserProfileData{}
	ctx := appengine.NewContext(r)
	u := user.Current(ctx)
	if u == nil {
		url, _ := user.LoginURL(ctx, "/")
		data.LoginUrl = url
		datajson, err := json.Marshal(data)
		if err != nil {
			http.Error(w, "Internal Service Error", http.StatusInternalServerError)
			return
		}
		fmt.Fprintf(w, "%s", datajson)
		return
	}
	url, _ := user.LogoutURL(ctx, "/")
	data.LogoutUrl = url
	data.Email = u.Email
	data.IsAdmin = u.Admin
	data.IsLoggedIn = true
	datajson, err := json.Marshal(data)
	if err != nil {
		http.Error(w, "Internal Service Error", http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "%s", datajson)
}
示例#7
0
func admin(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)
	url, _ := user.LogoutURL(ctx, "/")
	res.Header().Set("Content-Type", "text/html")
	fmt.Fprintf(res, `Welcome ADMIN, %s! <br>`, u.Email)
	fmt.Fprintf(res, `(<a href="%s">sign out</a>)`, url)
}
示例#8
0
func logout(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	http.SetCookie(res, &http.Cookie{Name: "logged_in", Value: "", MaxAge: -1})
	url, err := user.LogoutURL(ctx, "/")
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}
	http.Redirect(res, req, url, 302)
}
示例#9
0
func welcome(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-type", "text/html; charset=utf-8")
	ctx := appengine.NewContext(r)
	u := user.Current(ctx)
	if u == nil {
		url, _ := user.LoginURL(ctx, "/")
		fmt.Fprintf(w, `<a href="%s">Sign in or register</a>`, url)
		return
	}
	url, _ := user.LogoutURL(ctx, "/")
	fmt.Fprintf(w, `Welcome, %s! (<a href="%s">sign out</a>)`, u, url)
}
示例#10
0
func index(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)
	url, _ := user.LogoutURL(ctx, "/")
	res.Header().Set("Content-Type", "text/html")
	fmt.Fprintf(res, `Welcome, %s! <br>`, u.Email)
	fmt.Fprintf(res, `You are admin: %v  <br>`, u.Admin)
	if u.Admin {
		fmt.Fprint(res, `(<a href="/admin">go to admin</a>) <br>`)
	}
	fmt.Fprintf(res, `(<a href="%s">sign out</a>)`, url)
}
示例#11
0
// mainHandler tracks how many times each user has visited this page.
func mainHandler(w http.ResponseWriter, r *http.Request) *appError {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return nil
	}

	ctx := appengine.NewContext(r)
	u := user.Current(ctx)
	if u == nil {
		login, err := user.LoginURL(ctx, r.URL.String())
		if err != nil {
			return &appError{err, "Error finding login URL", http.StatusInternalServerError}
		}
		http.Redirect(w, r, login, http.StatusFound)
		return nil
	}
	logoutURL, err := user.LogoutURL(ctx, "/")
	if err != nil {
		return &appError{err, "Error finding logout URL", http.StatusInternalServerError}
	}

	// Increment visit count for user.
	tbl := client.Open(tableName)
	rmw := bigtable.NewReadModifyWrite()
	rmw.Increment(familyName, u.Email, 1)
	row, err := tbl.ApplyReadModifyWrite(ctx, u.Email, rmw)
	if err != nil {
		return &appError{err, "Error applying ReadModifyWrite to row: " + u.Email, http.StatusInternalServerError}
	}
	data := struct {
		Username, Logout string
		Visits           uint64
	}{
		Username: u.Email,
		// Retrieve the most recently edited column.
		Visits: binary.BigEndian.Uint64(row[familyName][0].Value),
		Logout: logoutURL,
	}

	// Display hello page.
	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, data); err != nil {
		return &appError{err, "Error writing template", http.StatusInternalServerError}
	}
	buf.WriteTo(w)
	return nil
}
示例#12
0
func logOutHandler(w http.ResponseWriter, r *http.Request, s string) {
	ctx := appengine.NewContext(r)
	url, err := user.LogoutURL(ctx, "/")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// Deleting session cookie
	var cookie *http.Cookie
	cookie, err = r.Cookie(s)
	if err != http.ErrNoCookie {
		cookie.MaxAge = -1
		http.SetCookie(w, cookie)
	}
	//  CHANGE NECESSARY DB FIELDS OF USER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	http.Redirect(w, r, url, http.StatusFound)
}
示例#13
0
func handleMainPage(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "GET requests only", http.StatusMethodNotAllowed)
		return
	}
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	c := appengine.NewContext(r)
	tic := time.Now()
	q := datastore.NewQuery("Greeting").Ancestor(guestbookKey(c)).Order("-Date").Limit(10)
	var gg []*Greeting
	_, err := q.GetAll(c, &gg)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		c.Errorf("GetAll: %v", err)
		return
	}
	c.Infof("Datastore lookup took %s", time.Since(tic).String())
	c.Infof("Rendering %d greetings", len(gg))

	var email, logout, login string
	if u := user.Current(c); u != nil {
		logout, _ = user.LogoutURL(c, "/")
		email = u.Email
	} else {
		login, _ = user.LoginURL(c, "/")
	}
	data := struct {
		Greetings            []*Greeting
		Login, Logout, Email string
	}{
		Greetings: gg,
		Login:     login,
		Logout:    logout,
		Email:     email,
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := tpl.ExecuteTemplate(w, "guestbook.html", data); err != nil {
		c.Errorf("%v", err)
	}
}
示例#14
0
文件: goploy.go 项目: mottam/goploy
func init() {
	r := gin.New()
	r.LoadHTMLGlob("templates/*")
	r.Use(sessions.Sessions("session_id", store))
	r.Static("/assets", "./assets")

	r.Use(gin.Recovery())
	v1 := r.Group("api/v1")
	v1.Use(loginWithGoogle())
	{
		v1.GET("/systems", controllers.GetSystems)
		v1.POST("/systems", controllers.CreateSystem)
		v1.GET("/systems/:id", controllers.GetSystem)
		v1.PUT("/systems/:id", controllers.UpdateSystem)
		v1.DELETE("/systems/:id", controllers.DeleteSystem)

		v1.GET("/developers", controllers.UpdatePage)
		v1.POST("/developers", controllers.UpdateDeveloper)

		v1.GET("/deploys", controllers.GetDeploys)
		v1.POST("/deploys", controllers.CreateDeploy)
	}
	r.Use(loginWithGoogle())
	r.Use(updateDevPending())
	{
		r.GET("/", func(c *gin.Context) {
			c.HTML(http.StatusOK, "index.tmpl", gin.H{})
		})
	}
	r.GET("/logout", func(c *gin.Context) {
		ctx := appengine.NewContext(c.Request)
		url, _ := user.LogoutURL(ctx, "/")
		c.Redirect(http.StatusTemporaryRedirect, url)
	})
	http.Handle("/", r)

	/*
		Use this for https instead of r.Run()
		r.RunTLS(":8080", pathToCertFile, pathToKeyFile)
	*/
}
示例#15
0
文件: dl.go 项目: barthy1/s3cli
func listHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	var (
		c = appengine.NewContext(r)
		d listTemplateData
	)
	if _, err := memcache.Gob.Get(c, cacheKey, &d); err != nil {
		if err == memcache.ErrCacheMiss {
			log.Debugf(c, "cache miss")
		} else {
			log.Errorf(c, "cache get error: %v", err)
		}

		var fs []File
		_, err := datastore.NewQuery("File").Ancestor(rootKey(c)).GetAll(c, &fs)
		if err != nil {
			log.Errorf(c, "error listing: %v", err)
			return
		}
		d.Stable, d.Unstable = filesToReleases(fs)
		if len(d.Stable) > 0 {
			d.Featured = filesToFeatured(d.Stable[0].Files)
		}

		d.LoginURL, _ = user.LoginURL(c, "/dl")
		if user.Current(c) != nil {
			d.LoginURL, _ = user.LogoutURL(c, "/dl")
		}

		item := &memcache.Item{Key: cacheKey, Object: &d, Expiration: cacheDuration}
		if err := memcache.Gob.Set(c, item); err != nil {
			log.Errorf(c, "cache set error: %v", err)
		}
	}
	if err := listTemplate.ExecuteTemplate(w, "root", d); err != nil {
		log.Errorf(c, "error executing template: %v", err)
	}
}
示例#16
0
文件: user.go 项目: tetrafolium/gae
func (u userImpl) LogoutURL(dest string) (string, error) {
	return user.LogoutURL(u.aeCtx, dest)
}
示例#17
0
func logoutRedirect(w http.ResponseWriter, r *http.Request) {
	url, _ := user.LogoutURL(appengine.NewContext(r), "/")
	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func renderPage(id string, u *user.User, c context.Context, w http.ResponseWriter, r *http.Request, edit bool) {

	var pageKey *datastore.Key

	pID, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		// check alias
		paKey := model.NewPageAliasKey(c, id)
		var pa model.PageAlias
		if err := ds.Get(c, paKey, &pa); err != nil {
			handleError(c, w, err, http.StatusNotFound)
			return
		}
		pID = pa.PageKey.IntID()
		pageKey = pa.PageKey
	} else {
		pageKey = model.NewPageKey(c, pID)
	}

	var p model.Page
	if err := ds.Get(c, pageKey, &p); err != nil {
		handleError(c, w, err, http.StatusNotFound)
		return
	}

	if edit {
		if u == nil {
			loginURL, _ := user.LoginURL(c, p.URLBase()+common.EDIT_PAGE_EXT)
			http.Redirect(w, r, loginURL, http.StatusFound)
			return
		} else if !u.Admin {
			// TODO: prepare error page
			http.Redirect(w, r, "/caterpillar/error/invalidUser", http.StatusFound)
			return
		}
	}

	leaf := leaves[p.Leaf]
	if leaf == nil {
		errmsg := fmt.Sprintf("leaf not found:" + p.Leaf)
		handleError(c, w, errors.New(errmsg), http.StatusNotFound)
		return
	}

	tparam := struct {
		Properties map[string]interface{}
		Areas      map[string]interface{}
		User       *user.User
		Edit       bool
		PageID     int64
		ViewURL    string
		EditURL    string
		PagesURL   string
		LogoutURL  string
	}{
		make(map[string]interface{}),
		make(map[string]interface{}),
		u,
		edit,
		pID,
		"",
		"",
		"",
		"",
	}

	if u != nil {
		tparam.PagesURL = "/caterpillar/static/mng/#/queryPage"

		purl := p.URLBase()
		tparam.ViewURL = purl + common.VIEW_PAGE_EXT
		tparam.EditURL = purl + common.EDIT_PAGE_EXT

		logoutURL, err := user.LogoutURL(c, tparam.ViewURL)
		if err != nil {
			// only log
			applog.Warningf(c, "cannot get logoutURL. err:%v", err)
		}
		tparam.LogoutURL = logoutURL
	}

	futureProps := make(map[string]<-chan func() (*model.PageProperty, error))
	futureAreas := make(map[string]<-chan func() (*model.Area, []model.Block, error))

	for _, hole := range leaf.Wormholes {
		var pkey *datastore.Key
		if hole.Global {
			pkey = model.NewGlobalPageKey(c)
		} else {
			pkey = pageKey
		}
		switch hole.Type {
		case PROPERTY:
			propkey := model.NewPagePropertyKey(c, hole.Name, pkey)
			ch := getPagePropertyAsync(c, propkey)
			futureProps[hole.Name] = ch
		case AREA:
			ch := getAreaAndBlocksAsync(c, pkey, hole.Name)
			futureAreas[hole.Name] = ch
		}
	}

	pageURLs := make(map[string]string)

	for _, hole := range leaf.Wormholes {
		switch hole.Type {
		case PROPERTY:
			prop, err := (<-futureProps[hole.Name])()
			if err == nil {
				tparam.Properties[hole.Name] = prop.Value
			} else {
				// TODO handle error
				applog.Errorf(c, "%s", err)
			}
		case AREA:
			area, blocks, err := (<-futureAreas[hole.Name])()

			if err == nil {
				areasrc := renderArea(hole.Global, area, blocks, edit)

				if !edit {
					futurePages := make(map[string]<-chan func() (*model.Page, error))

					urls := pageUrlRegex.FindAllStringSubmatch(areasrc, -1)

					for _, url := range urls {
						purl := url[0]

						if _, exists := pageURLs[purl]; exists {
							continue
						}
						if _, exists := futurePages[purl]; exists {
							continue
						}

						pageID, err := strconv.ParseInt(url[1], 10, 64)
						if err != nil {
							// TODO handle error
							applog.Errorf(c, "%s", err)
							continue
						}

						pkey := model.NewPageKey(c, pageID)
						futurePages[purl] = getPageAsync(c, pkey)
					}

					for purl, ch := range futurePages {
						page, err := (<-ch)()
						if err != nil {
							// TODO handle error
							applog.Errorf(c, "%s", err)
							continue
						}
						pageURLs[purl] = page.URLBase() + common.VIEW_PAGE_EXT
					}

					areasrc = pageUrlRegex.ReplaceAllStringFunc(areasrc, func(s string) string {
						if r, true := pageURLs[s]; true {
							return r
						}
						return s
					})
				}

				tparam.Areas[hole.Name] = template.HTML(areasrc)
			} else {
				// TODO handle error
				applog.Errorf(c, "%s", err)
			}
		}
	}

	// TODO: validate reserved page name property
	// or put some prefix?
	tparam.Properties["name"] = p.Name

	// TODO: resolve charset from somewhere
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	if err = leaf.Template.Execute(w, tparam); err != nil {
		handleError(c, w, err, http.StatusInternalServerError)
		return
	}

	return

}