Example #1
0
File: hms.go Project: jordonwii/hms
func APIKeyAddHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		loginUrl, _ := user.LoginURL(c, r.URL.RequestURI())
		http.Redirect(w, r, loginUrl, http.StatusFound)
		return
	} else {
		if !u.Admin {
			w.WriteHeader(http.StatusForbidden)
			w.Write([]byte("You're not an admin. Go away."))
		} else {
			key := randomString(26)
			owner := r.FormValue("owner")

			if owner == "" {
				w.Write([]byte("You forgot a parameter."))
			} else {
				apiKey := APIKey{
					APIKey:     key,
					OwnerEmail: owner,
				}
				dkey := datastore.NewIncompleteKey(c, "APIKey", nil)
				_, err := datastore.Put(c, dkey, &apiKey)
				if err != nil {
					w.Write([]byte(fmt.Sprintf("error! %s", err.Error())))
				} else {
					w.Write([]byte(key))

				}
			}
		}
	}
}
Example #2
0
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()
	}
}
Example #3
0
// 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)
}
Example #4
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)
}
Example #5
0
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)
}
Example #6
0
func editHandler(w http.ResponseWriter, r *http.Request) {
	//For now identify by the ThreadId since each submission will have a unique one
	strVal := r.FormValue("thread")

	//TODO update with YAML require login to not need to check the user status

	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
	}

	page := template.Must(template.ParseFiles(
		"public/templates/_base_edit.html",
		"public/templates/edit.html",
	))

	data := struct{ ThreadId string }{strVal}

	if err := page.Execute(w, data); err != nil {
		serveError(c, w, err)
		fmt.Fprintf(w, "\n%v\n%v", err.Error(), data)
		return
	}
}
Example #7
0
func appstatsHandler(w http.ResponseWriter, r *http.Request) {
	ctx := storeContext(appengine.NewContext(r))
	if appengine.IsDevAppServer() {
		// noop
	} else if u := user.Current(ctx); u == nil {
		if loginURL, err := user.LoginURL(ctx, 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(ctx, w, r)
	} else if fileURL == r.URL.Path {
		file(ctx, w, r)
	} else if strings.HasPrefix(r.URL.Path, staticURL) {
		name := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]
		content, ok := static[name]
		if !ok {
			http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
			return
		}
		http.ServeContent(w, r, name, initTime, content)
	} else {
		index(ctx, w, r)
	}
}
Example #8
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)
}
Example #9
0
func handle(res http.ResponseWriter, req *http.Request) {
	if req.URL.Path != "/" {
		http.NotFound(res, req)
		return
	}

	ctx := appengine.NewContext(req)
	u := user.Current(ctx)

	if u != nil {
		key := datastore.NewKey(ctx, "profile", u.Email, 0, nil)
		var p profile
		err := datastore.Get(ctx, key, &p)
		if err == datastore.ErrNoSuchEntity {
			http.Redirect(res, req, "/CreateProfile", http.StatusSeeOther)
			return
		} else if err != nil {
			http.Error(res, "Server error!", http.StatusInternalServerError)
			log.Errorf(ctx, "Datastore get Error: %s\n", err.Error())
			return
		}
	}

	// Get recent tweets
	query := datastore.NewQuery("Tweets")
	tweets := []tweet{}
	_, err := query.GetAll(ctx, &tweets)
	if err != nil {
		http.Error(res, "Server error!", http.StatusInternalServerError)
		log.Errorf(ctx, "Query Error: %s\n", err.Error())
		return
	}

	// Create template
	loginURL, err := user.LoginURL(ctx, "/")
	if err != nil {
		http.Error(res, "Server error!", http.StatusInternalServerError)
		log.Errorf(ctx, "Login URL Error: %s\n", err.Error())
		return
	}
	data := mainpageData{
		Tweets:   tweets,
		Logged:   u != nil,
		LoginURL: loginURL,
	}
	if data.Logged {
		data.Email = u.Email
	}

	err = tpl.ExecuteTemplate(res, "index.gohtml", data)
	if err != nil {
		http.Error(res, "Server error!", http.StatusInternalServerError)
		log.Errorf(ctx, "Template Execute Error: %s\n", err.Error())
		return
	}
}
Example #10
0
// handleGAEAuth sends a redirect to GAE authentication page.
func handleGAEAuth(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	url, err := user.LoginURL(c, r.URL.String())
	if err != nil {
		errorf(c, "user.LoginURL(%q): %v", r.URL.String(), err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, url, http.StatusFound)
}
Example #11
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)
}
Example #12
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)
}
Example #13
0
func handle(res http.ResponseWriter, req *http.Request) {
	if req.URL.Path != "/" {
		http.NotFound(res, req)
		return
	}

	ctx := appengine.NewContext(req)
	u := user.Current(ctx)

	if u != nil {
		_, err := getProfileByEmail(ctx, u.Email)
		if err == datastore.ErrNoSuchEntity {
			http.Redirect(res, req, "/CreateProfile", http.StatusSeeOther)
			return
		} else if err != nil {
			http.Error(res, "Server error!", http.StatusInternalServerError)
			log.Errorf(ctx, "Datastore get Error: %s\n", err.Error())
			return
		}
	}

	//Get recent tweets
	tweets, err := getTweets(ctx, "")
	if err != nil {
		http.Error(res, "server error!", http.StatusInternalServerError)
		log.Errorf(ctx, "Query Error: &s\n", err.Error())
		return
	}

	// Create template
	loginURL, err := user.LoginURL(ctx, "/")
	if err != nil {
		http.Error(res, "server error!", http.StatusInternalServerError)
		log.Errorf(ctx, "Login URL Error: &s\n", err.Error())
		return
	}
	data := mainpageData{
		Tweets:   tweets,
		Logged:   u != nil,
		LoginURL: loginURL,
	}
	if data.Logged {
		data.Email = u.Email
	}

	err = tpl.ExecuteTemplate(res, "index.gohtml", nil)
	if err != nil {
		http.Error(res, "Serever error!", http.StatusInternalServerError)
		log.Errorf(ctx, "Template Parse Error: %s\n", err.Error())
		return
	}
}
func login(c context.Context, w http.ResponseWriter, r *http.Request) {
	// TODO: check default page and redirect to page list without it

	var postLogin string
	if dest, ok := r.URL.Query()["dest"]; ok {
		postLogin = dest[0]
	} else {
		postLogin = MNG_ROOT_URL
	}

	loginURL, _ := user.LoginURL(c, postLogin)
	http.Redirect(w, r, loginURL, http.StatusFound)
}
Example #15
0
func handler(res http.ResponseWriter, req *http.Request) {
	c := appengine.NewContext(req)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, req.URL.String())
		if err != nil {
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}
		res.Header().Set("Location", url)
		res.WriteHeader(http.StatusFound)
		return
	}
	fmt.Fprintf(res, "Hello, %v!", u)
}
Example #16
0
func authdemo(w http.ResponseWriter, r *http.Request) *appError {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			return &appError{err, "Could not determine LoginURL", http.StatusInternalServerError}
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return nil
	}
	fmt.Fprintf(w, "Hello, %v!", u)
	return nil
}
Example #17
0
File: urls.go Project: husio/apps
func handleLogin(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	next := r.URL.Query().Get("next")
	if next == "" {
		next = r.URL.Query().Get("continue")
	}
	if next == "" {
		next = r.Referer()
	}

	if user.Current(ctx) != nil {
		url, _ := user.LoginURL(ctx, "/")
		http.Redirect(w, r, url, http.StatusTemporaryRedirect)
	} else {
		http.Redirect(w, r, next, http.StatusTemporaryRedirect)
	}
}
// Hard profiles?
//
// Not used yet.
// TODO To be adapted to : Handle optional user strong auth
func handleAuth(w http.ResponseWriter, r *http.Request) error {
	// Cf https://developers.google.com/appengine/docs/go/users/
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, "/")
		if err != nil {
			return err
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return nil
	}
	fmt.Fprintf(w, "Hello, %v!", u)
	return nil
}
Example #19
0
func meHandler(w http.ResponseWriter, r *http.Request) {

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

	if u == nil {
		url, err := user.LoginURL(c, "/me/")
		if err != nil {
		}

		http.Redirect(w, r, url, 301)
		return
	}

	du, err := getUser(r)
	if err != nil {
	}

	if du == nil {
		//register userkey
		meRender(w, "./templates/me/userkey.tmpl", nil)
	} else {
		//select user slide
		userkey := du.UserKey
		q := datastore.NewQuery("Slide").
			Filter("UserKey = ", userkey).
			Order("- SpeakDate")
		var s []Slide

		// function get user Slide

		keys, err := q.GetAll(c, &s)
		if err != nil {
		}

		rtn := make([]TemplateSlide, len(s))
		for i, elm := range s {
			rtn[i] = TemplateSlide{
				Title:     elm.Title,
				SubTitle:  elm.SubTitle,
				SpeakDate: elm.SpeakDate,
				Key:       keys[i].StringID(),
			}
		}
		meRender(w, "./templates/me/top.tmpl", rtn)
	}
}
Example #20
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
}
Example #21
0
// delete world data
func (a *MinecraftApi) Delete(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)

	u := user.Current(ctx)
	if u == nil {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.WriteHeader(http.StatusUnauthorized)
		loginURL, err := user.LoginURL(ctx, "")
		if err != nil {
			log.Errorf(ctx, "get user login URL error, %s", err.Error())
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.Write([]byte(fmt.Sprintf(`{"loginURL":"%s"}`, loginURL)))
		return
	}
	if user.IsAdmin(ctx) == false {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.WriteHeader(http.StatusForbidden)
		return
	}

	keyStr := r.FormValue("key")

	key, err := datastore.DecodeKey(keyStr)
	if err != nil {
		log.Infof(ctx, "invalid key, %v", r.Body)
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(`{"message": "invalid key."}`))
		return
	}

	err = datastore.RunInTransaction(ctx, func(c context.Context) error {
		return datastore.Delete(ctx, key)
	}, nil)
	if err != nil {
		log.Errorf(ctx, "Minecraft Delete Error. error = %s", err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(`{}`)
}
Example #22
0
// enforceLoginHandler wraps another handler, returning a handler that will
// enforce user login and then pass off control down the chain.
func enforceLoginHandler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		c := appengine.NewContext(req)
		u := user.Current(c)
		if u == nil {
			// Not logged in
			url, err := user.LoginURL(c, req.URL.String())
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			http.Redirect(w, req, url, http.StatusSeeOther)
			return
		}
		// Pass off control
		next.ServeHTTP(w, req)
	})
}
Example #23
0
func createHandler(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
	}

	http.ServeFile(w, r, "public/templates/create.html")
}
Example #24
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)
	}
}
Example #25
0
File: dl.go Project: 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)
	}
}
Example #26
0
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	c := context{
		c: ctx,
		r: r,
		w: w,
		u: user.Current(ctx),
	}

	if c.u == nil {
		url, _ := user.LoginURL(c.c, c.r.URL.Path)
		http.Redirect(w, r, url, 301)
		return
	}

	err := h(&c)
	if err != nil {
		http.Error(w, "server error", 500)
		c.c.Errorf("error %v", err)
	}
}
Example #27
0
func handler(res http.ResponseWriter, req *http.Request) {

	if req.URL.Path != "/" {
		http.NotFound(res, req)
		return
	}

	ctx := appengine.NewContext(req)

	u := user.Current(ctx)
	if u == nil {
		url, err := user.LoginURL(ctx, req.URL.String())
		if err != nil {
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}
		res.Header().Set("Location", url)
		res.WriteHeader(http.StatusFound)
		return
	}
	fmt.Fprintf(res, "Hello, %v\n\n", u)

	gcsClient, err := storage.NewClient(ctx)
	if err != nil {
		log.Errorf(ctx, "ERROR handler NewClient: ", err)
		return
	}
	defer gcsClient.Close()

	d := &demo{
		ctx:    ctx,
		res:    res,
		client: gcsClient,
		bucket: gcsClient.Bucket(gcsBucket),
	}

	d.delFiles()
	d.createFiles()
	d.listFiles()
}
Example #28
0
func Home(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	c := appengine.NewContext(req)
	u := user.Current(c)
	email := u.String()
	//	url, _ := user.LogoutURL(c, "/")
	if u == nil {
		url, err := user.LoginURL(c, req.URL.String())
		if err != nil {
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}
		res.Header().Set("Location", url)
		res.WriteHeader(http.StatusFound)
		return
	}
	key := datastore.NewKey(c, "Users", email, 0, nil)
	var us User
	err := datastore.Get(c, key, &us)
	log.Infof(c, "ERR: %v", err)
	if err != nil {
		user := User{
			Email: email,
			Alias: Getalias(),
		}
		key := datastore.NewKey(c, "Users", user.Email, 0, nil)
		key, err = datastore.Put(c, key, &user)
		if err != nil {
			http.Error(res, err.Error(), 500)
			return
		}
		tpl.ExecuteTemplate(res, "home.html", &user)
	} else {
		user := User{
			Email: us.Email,
			Alias: us.Alias,
		}
		tpl.ExecuteTemplate(res, "home.html", &user)
	}
	return
}
Example #29
0
// If the user wants to login via Google, we will redirect them to this URL
func GetLoginUrl(r *http.Request, fromScratch bool) string {
	ctx := appengine.NewContext(r)

	destURL := r.URL
	destURL.Path = callbackUrlPath

	// Check for the case where the user remains logged in (via appengine cookie),
	// but clicked 'Logout' on our app; these guys shouldn't be bounced back to the "do you
	// grant this app permissions" page.
	u := user.Current(ctx)
	if !fromScratch && u != nil {
		return destURL.String()
	}

	// This is a 'start from scratch' Google login URL, that involves re-selecting the google acct.
	url, err := user.LoginURL(ctx, destURL.String())
	if err != nil {
		log.Errorf(ctx, "g.GetLoginUrl, %v", err)
		return ""
	}
	return url
}
Example #30
0
File: hms.go Project: jordonwii/hms
func BackupLinksHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		loginUrl, _ := user.LoginURL(c, r.URL.RequestURI())
		http.Redirect(w, r, loginUrl, http.StatusFound)
		return
	} else {
		if !u.Admin {
			w.WriteHeader(http.StatusForbidden)
			w.Write([]byte("You're not an admin. Go away."))
		} else {
			w.Header().Set("Content-Type", "text/plain")
			results := datastore.NewQuery("Link").Order("-Created").Run(c)
			DELIM := "|||"
			var link Link
			for {
				_, err := results.Next(&link)
				if err == datastore.Done {
					break
				} else if err != nil {
					w.Write([]byte(err.Error()))
				} else {
					var chat Chat
					s := link.Path + DELIM + link.TargetURL + DELIM + link.Creator + DELIM
					s += strconv.FormatInt(link.Created.Unix(), 10) + DELIM
					if link.ChatKey != nil {
						err = datastore.Get(c, link.ChatKey, &chat)
						if err != nil {
							continue
						}
						s += strconv.FormatInt(chat.FacebookChatID, 10) + DELIM + chat.ChatName
					}
					w.Write([]byte(s + "\n"))
				}
			}
		}
	}
}