Exemplo n.º 1
0
func addPhoto(fName string, id string, req *http.Request) error {
	ctx := appengine.NewContext(req)

	// DATASTORE
	md, err := retrieveDstore(id, req)
	if err != nil {
		return err
	}
	md.Pictures = append(md.Pictures, fName)
	err = storeDstore(md, req) // removed id in parameter
	if err != nil {
		log.Errorf(ctx, "ERROR addPhoto storeDstore: %s", err)
		return err
	}

	// MEMCACHE
	var mc model
	mc, err = retrieveMemc(id, req)
	if err != nil {
		log.Errorf(ctx, "ERROR addPhoto retrieveMemc: %s", err)
		return err
	}
	mc.Pictures = append(mc.Pictures, fName)
	err = storeMemc(mc, req) // removed id in parameter
	if err != nil {
		log.Errorf(ctx, "ERROR addPhoto storeMemc: %s", err)
		return err
	}

	return nil
}
Exemplo n.º 2
0
func Get(c context.Context, key, def string, values ...interface{}) string {
	configLock.Lock()
	defer configLock.Unlock()
	val, ok := configCache[key]
	if ok {
		return fmt.Sprintf(val, values...)
	}
	value := Value{}
	dskey := datastore.NewKey(c, ConfigName, key, 0, nil)
	err := datastore.Get(c, dskey, &value)
	if err == datastore.ErrNoSuchEntity {
		value.Val = def
		log.Infof(c, "Creating default config for key - %s - default value is - %s", key, value.Val)
		_, err = datastore.Put(c, dskey, &value)
		if err != nil {
			log.Errorf(c, "Error creating default config for key - %s - error is - %v", key, err)
		}
		return fmt.Sprintf(def, values...) // return default, totally new config setting
	}
	if err != nil {
		log.Errorf(c, "Error fetching config for key - %s - error is - %v", key, err)
		return def // error, return the default
	}
	configCache[key] = value.Val
	return fmt.Sprintf(value.Val, values...)
}
Exemplo n.º 3
0
func createUser(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	ctx := appengine.NewContext(req)
	hashedPass, err := bcrypt.GenerateFromPassword([]byte(req.FormValue("password")), bcrypt.DefaultCost)
	if err != nil {
		log.Errorf(ctx, "error creating password: %v", err)
		http.Error(res, err.Error(), 500)
		return
	}
	user := User{
		Email:    req.FormValue("email"),
		UserName: req.FormValue("userName"),
		Password: string(hashedPass),
	}
	key := datastore.NewKey(ctx, "Users", user.UserName, 0, nil)
	key, err = datastore.Put(ctx, key, &user)
	if err != nil {
		log.Errorf(ctx, "error adding todo: %v", err)
		http.Error(res, err.Error(), 500)
		return
	}

	createSession(res, req, user)
	// redirect
	http.Redirect(res, req, "/", 302)
}
Exemplo n.º 4
0
func index(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)

	id, err := getID(res, req)
	if err != nil {
		log.Errorf(ctx, "getID: %s", err)
		http.Error(res, err.Error(), http.StatusInternalServerError)
		return
	}

	if req.Method == "POST" {
		src, _, err := req.FormFile("data")
		if err != nil {
			log.Errorf(ctx, "ERROR index req.FormFile: %s", err)
			http.Redirect(res, req, `/?id=`+id, http.StatusSeeOther)
			return
		}
		err = uploadPhoto(src, id, req)
		if err != nil {
			log.Errorf(ctx, "ERROR index uploadPhoto: %s", err)
			http.Redirect(res, req, "/logout", http.StatusSeeOther)
			return
		}
	}

	m, err := retrieveMemc(id, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index retrieveMemc: %s", err)
		http.Redirect(res, req, "/logout", http.StatusSeeOther)
		return
	}
	tpl.ExecuteTemplate(res, "index.html", m)
}
Exemplo n.º 5
0
func handleAdd(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	var err error

	if req.Method == "POST" {
		name := strings.TrimSpace(req.FormValue("name"))
		summary, err := getHTML(ctx, req.FormValue("summary"))
		if err != nil {
			http.Error(res, "Server error", http.StatusInternalServerError)
			log.Errorf(ctx, "%v\n", err)
			return
		}

		mov := &movie{
			Name:    name,
			Summary: summary,
			URL:     strings.ToLower(strings.Replace(name, " ", "", -1)),
		}
		err = addMovie(ctx, mov)
		if err != nil {
			http.Error(res, "Server error", http.StatusInternalServerError)
			log.Errorf(ctx, "%v\n", err)
			return
		}
		http.Redirect(res, req, "/", http.StatusSeeOther)
		return
	}

	err = tpl.ExecuteTemplate(res, "addMovie", nil)
	if err != nil {
		http.Error(res, "Server error", http.StatusInternalServerError)
		log.Errorf(ctx, "%v\n", err)
		return
	}
}
Exemplo n.º 6
0
func handleUpdate(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var (
		d   int
		day time.Weekday
		err error
	)
	// Check if there is a signed in user.
	u := currentUser(r)
	if u == nil {
		aelog.Errorf(c, "No signed in user for updating")
		goto out
	}
	// Validate XSRF token first.
	if !xsrftoken.Valid(r.PostFormValue(xsrfTokenName), xsrfKey, u.ID, updateURL) {
		aelog.Errorf(c, "XSRF token validation failed")
		goto out
	}
	// Extract the new favorite weekday.
	d, err = strconv.Atoi(r.PostFormValue(favoriteName))
	if err != nil {
		aelog.Errorf(c, "Failed to extract new favoriate weekday: %s", err)
		goto out
	}
	day = time.Weekday(d)
	if day < time.Sunday || day > time.Saturday {
		aelog.Errorf(c, "Got wrong value for favorite weekday: %d", d)
	}
	// Update the favorite weekday.
	updateWeekdayForUser(r, u, day)
out:
	// Redirect to home page to show the update result.
	http.Redirect(w, r, homeURL, http.StatusFound)
}
Exemplo n.º 7
0
func handleIndex(res http.ResponseWriter, req *http.Request) {
	if req.URL.Path != "/" {
		handleMovieDetails(res, req)
		return
	}

	ctx := appengine.NewContext(req)
	data := struct {
		Movies []movie
	}{}
	m, err := getRecentMovies(ctx, 15)
	if err != nil {
		http.Error(res, "Server error", http.StatusInternalServerError)
		log.Errorf(ctx, "%v\n", err)
		return
	}
	data.Movies = m

	err = tpl.ExecuteTemplate(res, "index", data)
	if err != nil {
		http.Error(res, "Server error", http.StatusInternalServerError)
		log.Errorf(ctx, "%v\n", err)
		return
	}
}
Exemplo n.º 8
0
func user(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	ctx := appengine.NewContext(req)
	user := User{UserName: ps.ByName("user")}
	//get tweets
	tweets, err := getTweets(req, &user)
	if err != nil {
		log.Errorf(ctx, "error getting tweets: %v", err)
		http.Error(res, err.Error(), 500)
		return
	}
	// get session
	memItem, err := getSession(req)
	var sd SessionData
	if err == nil {
		// logged in
		json.Unmarshal(memItem.Value, &sd)
		sd.LoggedIn = true
		sd.ViewingUser = user.UserName
		sd.FollowingUser, err = following(sd.UserName, user.UserName, req)
		if err != nil {
			log.Errorf(ctx, "error running following query: %v", err)
			http.Error(res, err.Error(), 500)
			return
		}
	}
	sd.Tweets = tweets
	tpl.ExecuteTemplate(res, "user.html", &sd)
}
Exemplo n.º 9
0
func fing(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	ctx := appengine.NewContext(req)
	// get session
	memItem, err := getSession(req)
	if err != nil {
		log.Infof(ctx, "Attempt to see following from logged out user")
		http.Error(res, "You must be logged in", http.StatusForbidden)
		return
	}
	var sd SessionData
	if err == nil {
		// logged in
		json.Unmarshal(memItem.Value, &sd)
		sd.LoggedIn = true
	}
	// declare a variable of type user
	// initialize user with values from memcache item
	var user User
	json.Unmarshal(memItem.Value, &user)
	// Get followees
	// get the datastore key for the follower
	followerKey := datastore.NewKey(ctx, "Users", user.UserName, 0, nil)
	var XF []F
	_, err = datastore.NewQuery("Follows").Ancestor(followerKey).Project("Following").GetAll(ctx, &XF)
	log.Errorf(ctx, "here is type %T \n and value %v", XF, XF)
	if err != nil {
		log.Errorf(ctx, "error getting followees: %v", err)
		http.Error(res, err.Error(), 500)
		return
	}
	sd.Following = XF
	tpl.ExecuteTemplate(res, "follow.html", &sd)
}
Exemplo n.º 10
0
func handleCron(w http.ResponseWriter, r *http.Request) *appError {
	// X-Appengine-Cron: true
	c := appengine.NewContext(r)
	a, err := LoadMagazines(c)
	if err != nil {
		return &appError{
			Error:   err,
			Message: "failed to load",
			Code:    http.StatusInternalServerError,
		}
	}
	client := urlfetch.Client(c)
	for _, m := range a {
		f, err := fetchFeed(client, m.URL)
		if err != nil {
			log.Errorf(c, "fetch url: %v", err)
			continue
		}
		if err = SendArticles(c, m, f); err != nil {
			log.Errorf(c, "send article: %v", err)
			continue
		}
	}
	return nil
}
Exemplo n.º 11
0
func textMessageHandler(w http.ResponseWriter, r *http.Request) {

	ctx := appengine.NewContext(r)

	to := r.FormValue("to")
	text := r.FormValue("text")

	log.Debugf(ctx, "to: %s, text: %s.", to, text)

	chi, _ := strconv.ParseInt(os.Getenv("CHANNEL_ID"), 10, 64)
	chs := os.Getenv("CHANNEL_SECRET")
	mid := os.Getenv("MID")

	client := urlfetch.Client(ctx)
	bot, err := linebot.NewClient(chi, chs, mid, linebot.WithHTTPClient(client))
	if err != nil {
		log.Errorf(ctx, "Client initialization failure. to: %s, text: %s, context: %s", to, text, err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	res, err := bot.SendText([]string{to}, text)
	if err != nil {
		log.Errorf(ctx, "Message Send Failed. to: %s, text: %s, context: %s", to, text, err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	log.Infof(ctx, "Message send succeed. MessageID: %s, to: %s, text: %s", res.MessageID, to, text)
	w.WriteHeader(http.StatusOK)
}
Exemplo n.º 12
0
func makeCookie(m model, req *http.Request) (*http.Cookie, error) {
	ctx := appengine.NewContext(req)

	// DATASTORE
	err := storeDstore(m, req)
	if err != nil {
		log.Errorf(ctx, "ERROR makeCookie storeDstore: %s", err)
		return nil, err
	}

	// MEMCACHE
	err = storeMemc(m, req)
	if err != nil {
		log.Errorf(ctx, "ERROR makeCookie storeMemc: %s", err)
		return nil, err
	}

	// COOKIE
	cookie := &http.Cookie{
		Name:  "session-id",
		Value: m.ID,
		// Secure: true,
		HttpOnly: true,
	}
	return cookie, nil
}
Exemplo n.º 13
0
//function copyFile takes in the string fileName and reads that
//fileName in the system then writes it in the gcs in short makes
//a copy of the file to gcs
func (a *app) copyFile(fileName string) {
	writer := a.bucket.Object(fileName).NewWriter(a.ctx)
	writer.ACL = []storage.ACLRule{
		{storage.AllUsers, storage.RoleReader},
	}
	writer.ContentType = "image/jpg"

	//read file from folders img and photos
	b, err := ioutil.ReadFile(fileName)
	if err != nil {
		log.Errorf(a.ctx, "Error in copyFile: ", err)
		return
	}

	//writes the read bytes to gcs bucket.
	_, err = writer.Write(b)
	if err != nil {
		log.Errorf(a.ctx, "createFile: unable to write data to bucket")
		return
	}
	err = writer.Close()
	if err != nil {
		log.Errorf(a.ctx, "createFile Close")
		return
	}
}
Exemplo n.º 14
0
func (d *demo) statFiles() {
	io.WriteString(d.res, "\nRETRIEVING FILE STATS\n")

	client, err := storage.NewClient(d.ctx)
	if err != nil {
		log.Errorf(d.ctx, "%v", err)
		return
	}
	defer client.Close()

	// create a query
	q := storage.Query{
		MaxResults: 2,
	}

	// instead of nil
	// now passing in a *storage.Query
	objs, err := client.Bucket(gcsBucket).List(d.ctx, &q)
	if err != nil {
		log.Errorf(d.ctx, "%v", err)
		return
	}

	for _, v := range objs.Results {
		d.statFile(v.Name)
	}
}
Exemplo n.º 15
0
// PrimaryPublicCertificates returns primary's PublicCertificates.
func PrimaryPublicCertificates(c context.Context, primaryURL string) (*PublicCertificates, error) {
	cacheKey := fmt.Sprintf("pub_certs:%s", primaryURL)
	var pubCerts []byte
	setCache := false
	item, err := memcache.Get(c, cacheKey)
	if err != nil {
		setCache = true
		if err != memcache.ErrCacheMiss {
			log.Warningf(c, "failed to get cert from cache: %v", err)
		}
		pubCerts, err = downloadCert(urlfetch.Client(c), primaryURL)
		if err != nil {
			log.Errorf(c, "failed to download cert: %v", err)
			return nil, err
		}
	} else {
		pubCerts = item.Value
	}
	pc := &PublicCertificates{}
	if err = json.Unmarshal(pubCerts, pc); err != nil {
		log.Errorf(c, "failed to unmarshal cert: %v %v", string(pubCerts), err)
		return nil, err
	}
	if setCache {
		err = memcache.Set(c, &memcache.Item{
			Key:        cacheKey,
			Value:      pubCerts,
			Expiration: time.Hour,
		})
		if err != nil {
			log.Warningf(c, "failed to set cert to cache: %v", err)
		}
	}
	return pc, nil
}
Exemplo n.º 16
0
func index(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)

	id, err := getID(res, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index getID: %s", err)
		http.Error(res, err.Error(), http.StatusInternalServerError)
		return
	}

	// DATASTORE
	m := model{
		Fname: "Todd",
	}
	err = storeDstore(m, id, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index storeDstore: %s", err)
		http.Error(res, err.Error(), http.StatusInternalServerError)
		return
	}

	// MEMCACHE
	err = storeMemc(m, id, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index storeMemc: %s", err)
		http.Error(res, err.Error(), http.StatusInternalServerError)
		return
	}

	fmt.Fprint(res, `
	<h1>EVERYTHING SET ID: `+id+`</h1>
	<h1><a href="/?id=`+id+`">HOME AGAIN</a></h1>
	<h1><a href="/retrieve?id=`+id+`">RETRIEVE</a></h1>
	`)
}
Exemplo n.º 17
0
// New creates a new appengine datastore filesystem.
// Notice that variadic options are submitted as functions,
// as is explained and justified here:
// http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
func New(options ...func(fsi.FileSystem)) *dsFileSys {

	fs := dsFileSys{}

	fs.dirsorter = func(fis []os.FileInfo) { sort.Sort(FileInfoByName(fis)) }
	fs.filesorter = func(fis []DsFile) { sort.Sort(DsFileByName(fis)) }

	for _, option := range options {
		option(&fs)
	}

	if fs.mount == "" {
		fs.mount = MountPointLast()
	}

	if fs.c == nil {
		panic("this type of filesystem needs appengine context, submitted as option")
	}

	rt, err := fs.dirByPath(fs.mount)
	_ = rt
	if err == datastore.ErrNoSuchEntity {
		rt, err = fs.saveDirByPath(fs.mount) // fine
		if err != nil {
			aelog.Errorf(fs.c, "could not create mount %v => %v", fs.mount, err)
		} else {
		}
	} else if err != nil {
		aelog.Errorf(fs.c, "could read mount dir %v => %v", fs.mount, err)
	} else {
		// fs.Ctx().Infof("Found rtdr %v  %v  %v ", rt.Dir, rt.BName, rt.Key)
	}

	return &fs
}
Exemplo n.º 18
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)
	key := datastore.NewKey(ctx, "Profile", u.Email, 0, nil)
	var profile Profile
	err := datastore.Get(ctx, key, &profile)
	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, err.Error())
		return
	}

	tpl, err := template.ParseFiles("viewProfile.gohtml")
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}
	err = tpl.Execute(res, &profile)
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}
}
Exemplo n.º 19
0
// To run a job directly: /backend/fdb-batch/flight?job=...&key=...&
func batchSingleFlightHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	f, err := formValueFlightByKey(r)
	if err != nil {
		log.Errorf(c, "batch/fdb/track/getflight: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// You now have a job name, and a flight object. Get to it !
	job := r.FormValue("job")
	var str string = ""
	switch job {
	case "tracktimezone":
		str, err = jobTrackTimezoneHandler(r, f)
	case "oceanictag":
		str, err = jobOceanicTagHandler(r, f)
	case "v2adsb":
		str, err = jobV2adsbHandler(r, f)
	}

	if err != nil {
		log.Errorf(c, "%s", str)
		log.Errorf(c, "backend/fdb-batch/flight: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	log.Debugf(c, "job=%s, on %s: %s", job, f, str)

	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte(fmt.Sprintf("OK\n * %s\n%s\n", f, str)))
}
Exemplo n.º 20
0
func createProfile(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	if req.Method == "POST" {
		u := user.Current(ctx)
		profile := Profile{
			Email:     u.Email,
			FirstName: req.FormValue("firstname"),
			LastName:  req.FormValue("lastname"),
		}
		key := datastore.NewKey(ctx, "Profile", u.Email, 0, nil)
		_, err := datastore.Put(ctx, key, &profile)
		if err != nil {
			http.Error(res, "Server Error", http.StatusInternalServerError)
			log.Errorf(ctx, err.Error())
			return
		}
		http.Redirect(res, req, "/", http.StatusSeeOther)
	}
	f, err := os.Open("createProfile.gohtml")
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}
	io.Copy(res, f)
}
Exemplo n.º 21
0
func addtrackHandler(w http.ResponseWriter, r *http.Request) {
	ctx := req2ctx(r)
	db := fdb.NewDB(r)

	icaoId := r.FormValue("icaoid")
	callsign := strings.TrimSpace(r.FormValue("callsign"))
	tStr := r.FormValue("track")

	// Validate it works before persisting
	t := ftype.Track{}
	if err := t.Base64Decode(tStr); err != nil {
		log.Errorf(ctx, " /mdb/addtrack: decode failed: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	ftf := ftype.FrozenTrackFragment{
		TrackBase64: tStr,
		Callsign:    callsign,
		Icao24:      icaoId,
	}
	if err := db.AddTrackFrgament(ftf); err != nil {
		log.Errorf(ctx, " /mdb/addtrack: db.AddTrackFragment failed: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	// 3. Routine to merge track fragments ? Extra credit ?

	// c.Infof(" /mdb/addtrack: added %d points for [%s][%s]", len(t), icaoId, callsign)
	w.Write([]byte(fmt.Sprintf("Added %d for %s\n", len(t), icaoId)))
}
Exemplo n.º 22
0
func handleLogin(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	ctx := appengine.NewContext(req)

	//get session for storing state to check on callback
	s := getSession(ctx, req)

	//generate state for checking later
	state, err := uuid.NewV4()
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}

	//put state in session and putting to memcache to check on callback
	s.State = state.String()
	err = putSession(ctx, res, s)
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}

	//generate the authorization url that goes to the login and consent page for google.
	//I set the ApprovalForce option so that it asks for consent each time so that we can see it.
	//Shows application asking to "Have offline access" each time. can remove second arg to remove this.
	url := conf.AuthCodeURL(s.State, oauth2.ApprovalForce)
	http.Redirect(res, req, url, http.StatusSeeOther)
}
Exemplo n.º 23
0
func addPhoto(fName string, id string, req *http.Request) error {
	ctx := appengine.NewContext(req)

	md, err := retrieveDstore(id, req)
	if err != nil {
		return err
	}
	md.Pictures = append(md.Pictures, fName)
	err = storeDstore(md, req)
	if err != nil {
		log.Errorf(ctx, "error adding photos due to storedstore: %s", err)
		return err
	}

	var mc model
	mc, err = retrieveMemc(id, req)
	if err != nil {
		log.Errorf(ctx, "error retrieving memc when storing photo: %s", err)
		return err
	}
	mc.Pictures = append(mc.Pictures, fName)
	err = storeMemc(mc, req)
	if err != nil {
		log.Errorf(ctx, "error storing memc while adding photo: %s", err)
		return err
	}

	return nil
}
Exemplo n.º 24
0
// ReceiveMail will receive an e-mail and echo it back to the sender.
func ReceiveMail(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)

	m, err := mail.ReadMessage(r.Body)
	if err != nil {
		log.Errorf(ctx, "Failed reading a mail!")
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = echoMailFunc.Call(ctx, m)
	if err != nil {
		log.Errorf(ctx, "Failed enqueing handler for a mail!")
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	io.WriteString(w, "OK")

	// TODO(flowlo):
	//  1. Check whether range m.Header.AddressList("From")
	//     fits a registered customer
	//  2. Filter mail content for further e-mail addresses
	//  3. Create a Fingerprint
	//  4. Mail the Fingerprint URL to the other address
}
Exemplo n.º 25
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)
}
Exemplo n.º 26
0
// createFile creates a file in Google Cloud Storage.
func (d *demo) createFile(fileName string) {
	//Prints to the webpage that the file is being created in a bucket with a filename.
	fmt.Fprintf(d.w, "Creating file /%v/%v\n", bucket, fileName)
	//Appears to be a writer for google cloud.
	wc := d.bucket.Object(fileName).NewWriter(d.ctx)
	//Data
	wc.ContentType = "text/plain"
	//More Data
	wc.Metadata = map[string]string{
		"x-goog-meta-foo": "foo",
		"x-goog-meta-bar": "bar",
	}
	//Need to look up what this does.
	d.cleanUp = append(d.cleanUp, fileName)
	//Writing to the writer abcde\n
	if _, err := wc.Write([]byte("abcde\n")); err != nil {
		log.Errorf(d.ctx, "createFile: unable to write data to bucket %q, file %q: %v", bucket, fileName, err)
		return
	}
	//Writing to the writer a lot of f and then a new one.
	if _, err := wc.Write([]byte(strings.Repeat("f", 1024*4) + "\n")); err != nil {
		log.Errorf(d.ctx, "createFile: unable to write data to bucket %q, file %q: %v", bucket, fileName, err)
		return
	}
	//Closes the writer.
	if err := wc.Close(); err != nil {
		log.Errorf(d.ctx, "createFile: unable to close bucket %q, file %q: %v", bucket, fileName, err)
		return
	}
}
Exemplo n.º 27
0
func login(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)

	id, err := getID(res, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index getID: %s", err)
		http.Error(res, err.Error(), http.StatusInternalServerError)
		return
	}

	if req.Method == "POST" && req.FormValue("password") == "secret" {
		m, err := retrieveMemc(id, req)
		if err != nil {
			log.Errorf(ctx, "ERROR index retrieveMemc: %s", err)
			// expired cookie may exist on client
			http.Redirect(res, req, "/logout", http.StatusSeeOther)
			return
		}
		m.State = true
		m.Name = req.FormValue("name")
		m.ID = id

		cookie, err := currentVisitor(m, req)
		if err != nil {
			log.Errorf(ctx, "ERROR login currentVisitor: %s", err)
			http.Redirect(res, req, `/?id=`+cookie.Value, http.StatusSeeOther)
			return
		}
		http.SetCookie(res, cookie)

		http.Redirect(res, req, `/?id=`+cookie.Value, http.StatusSeeOther)
		return
	}
	tpl.ExecuteTemplate(res, "login.html", nil)
}
Exemplo n.º 28
0
// ReceiveMail will receive an e-mail and echo it back to the sender.
func ReceiveMail(ctx context.Context, w http.ResponseWriter, r *http.Request) (int, error) {
	m, err := mail.ReadMessage(r.Body)
	if err != nil {
		log.Errorf(ctx, "Failed reading a mail!")
		return http.StatusInternalServerError, err
	}

	err = echoMailFunc.Call(ctx, m)
	if err != nil {
		log.Errorf(ctx, "Failed enqueing handler for a mail!")
		return http.StatusInternalServerError, err
	}

	if _, err = io.WriteString(w, "OK"); err != nil {
		return http.StatusInternalServerError, err
	}

	return http.StatusOK, nil

	// TODO(flowlo):
	//  1. Check whether range m.Header.AddressList("From")
	//     fits a registered customer
	//  2. Filter mail content for further e-mail addresses
	//  3. Create a Fingerprint
	//  4. Mail the Fingerprint URL to the other address
}
Exemplo n.º 29
0
func index(res http.ResponseWriter, req *http.Request) {

	ctx := appengine.NewContext(req)

	id := getID(res, req)

	if req.Method == "POST" {
		src, _, err := req.FormFile("data")
		if err != nil {
			log.Errorf(ctx, "ERROR index req.FormFile: %s", err)
			// TODO: create error page to show user
			http.Redirect(res, req, "/", http.StatusSeeOther)
			return
		}
		err = uploadPhoto(src, id, req)
		if err != nil {
			log.Errorf(ctx, "ERROR index uploadPhoto: %s", err)
			// expired cookie may exist on client
			http.Redirect(res, req, "/logout", http.StatusSeeOther)
			return
		}
	}

	m, err := retrieveMemc(id, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index retrieveMemc: %s", err)
		// expired cookie may exist on client
		http.Redirect(res, req, "/logout", http.StatusSeeOther)
		return
	}
	tpl.ExecuteTemplate(res, "index.html", m)
}
Exemplo n.º 30
0
//Copys files to bucket
func (googappengine *googctx) copyFile(fileName string) {
	writer := googappengine.bucket.Object(fileName).NewWriter(googappengine.ctx)
	writer.ACL = []storage.ACLRule{
		{storage.AllUsers, storage.RoleReader},
	}
	writer.ContentType = "image/jpg"

	//read all images
	files, err := ioutil.ReadFile(fileName)
	if err != nil {
		log.Errorf(googappengine.ctx, "Error in copyFile: ", err)
		return
	}

	//writes images previously read to gcs
	_, err = writer.Write(files)
	if err != nil {
		log.Errorf(googappengine.ctx, "createFile: unable to write data to bucket")
		return
	}
	err = writer.Close()
	if err != nil {
		log.Errorf(googappengine.ctx, "createFile Close")
		return
	}
}