Beispiel #1
0
func HandleSign(r *http.Request) (err error) {

	c := appengine.NewContext(r)

	if user.Current(c) == nil {
		panic("Not logged in .. can only post with authenticated users")
	}

	if err := r.ParseForm(); err != nil {
		return err
	}
	g := &Buriggie{
		Content: r.FormValue("bericht"),
		Date:    time.Now(),
	}
	if u := user.Current(c); u != nil {
		g.Author = u.String()
	}
	if _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Greeting", nil), g); err != nil {
		return err
	}

	// nice and clean
	memcache.Delete(c, "buriggies.list.100")

	return nil
}
Beispiel #2
0
func saveToken(w http.ResponseWriter, r *http.Request) *appError {
	c := appengine.NewContext(r)
	if appErr := loadConfig(r); appErr != nil {
		return appErr
	}
	if user.Current(c) == nil {
		return &appError{nil, "Must be signed in to save token.", 400}
	}
	code := r.FormValue("code")
	if code == "" {
		return &appError{nil, "No 'code' parameter found", 500}
	}
	t := &oauth.Transport{
		Config:    &cfg,
		Transport: urlfetch.Client(c).Transport,
	}

	if _, err := t.Exchange(code); err != nil {
		return &appError{err, "Error exchanging code for token.", 500}
	}

	d := datastore.New(c)
	if err := d.SaveToken(user.Current(c).Email, t.Token); err != nil {
		return &appError{err, "Error saving token.", 500}
	}
	http.Redirect(w, r, "/app", http.StatusFound)
	return nil
}
func TestContext(t *testing.T) {
	c, err := NewContext(nil)
	if err != nil {
		t.Fatalf("NewContext: %v", err)
	}
	defer c.Close()

	_, err = memcache.Get(c, "foo")
	if err != memcache.ErrCacheMiss {
		t.Fatalf("Get err = %v; want ErrCacheMiss", err)
	}

	it := &memcache.Item{
		Key:   "foo",
		Value: []byte("value"),
	}
	err = memcache.Set(c, it)
	if err != nil {
		t.Fatalf("Set err = %v", err)
	}
	it, err = memcache.Get(c, "foo")
	if err != nil {
		t.Fatalf("Get err = %v; want no error", err)
	}
	if string(it.Value) != "value" {
		t.Errorf("got Item.Value = %q; want %q", string(it.Value), "value")
	}

	e := &Entity{Foo: "foo", Bar: "bar"}
	k := datastore.NewKey(c, "Entity", "", 1, nil)
	_, err = datastore.Put(c, k, e)
	if err != nil {
		t.Fatalf("datastore.Put: %v", err)
	}
	u := user.Current(c)
	if u != nil {
		t.Fatalf("User should not be not logged in!")
	}
	c.Login("*****@*****.**", false)
	u = user.Current(c)
	if u == nil {
		t.Fatalf("User should be logged in!")
	}
	id1 := u.ID
	c.Logout()
	u = user.Current(c)
	if u != nil {
		t.Fatalf("User should not be not logged in!")
	}
	c.Login("*****@*****.**", false)
	u = user.Current(c)
	if u == nil {
		t.Fatalf("User should be logged in!")
	}
	if id1 == u.ID {
		t.Fatalf("User IDs should be unique")
	}
}
Beispiel #4
0
func handleSign(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		serve404(w)
		return
	}
	c := appengine.NewContext(r)
	u := user.Current(c)
	userName := ""
	if u != nil { //a google user
		userName = u.String()
	} else { //not a google user
		//is it a local user?
		cookie, err := r.Cookie("email")
		if err == nil {
			userName = cookie.Value
		} else { //no logged in yet

			badRequest(w, "Only login user can post messages.")
			return
		}
	}
	if err := r.ParseForm(); err != nil {
		serveError(c, w, err)
		return
	}
	tagsString := r.FormValue("tags")
	m := &Message{
		ID:      0,
		Title:   template.HTMLEscapeString(r.FormValue("title")),
		Author:  template.HTMLEscapeString(r.FormValue("author")),
		Content: []byte(template.HTMLEscapeString(r.FormValue("content"))),
		Tags:    strings.Split(template.HTMLEscapeString(tagsString), ","),
		Date:    time.Now(),
		Views:   0,
		Good:    0,
		Bad:     0,
	}
	if badTitle(m.Title) || badAuthor(m.Author) || badContent(string(m.Content)) || badTag(tagsString) {
		badRequest(w, "Input too long")
		return
	}

	processMsgContent(m)
	//TODO: build References and Referedby list
	if u := user.Current(c); u != nil {
		m.Author = userName
		//TODO: hook this message under user's msglist
	}
	k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "aMessage", nil), m)
	if err != nil {
		serveError(c, w, err)
		return
	}
	putMsgTags(r, k.IntID(), m.Tags)
	setCount(w, r)
	http.Redirect(w, r, "/", http.StatusFound)
}
Beispiel #5
0
// PUT http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM
// {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"}
//
func (u *ProfileApi) update(r *restful.Request, w *restful.Response) {
	c := appengine.NewContext(r.Request)

	// Decode the request parameter to determine the key for the entity.
	k, err := datastore.DecodeKey(r.PathParameter("profile-id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Marshall the entity from the request into a struct.
	p := new(Profile)
	err = r.ReadEntity(&p)
	if err != nil {
		w.WriteError(http.StatusNotAcceptable, err)
		return
	}

	// Retrieve the old entity from the datastore.
	old := Profile{}
	if err := datastore.Get(c, k, &old); err != nil {
		if err.Error() == "datastore: no such entity" {
			http.Error(w, err.Error(), http.StatusNotFound)
		} else {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		return
	}

	// Check we own the profile before allowing them to update it.
	// Optionally, return a 404 instead to help prevent guessing ids.
	// TODO: Allow admins access.
	if old.Email != user.Current(c).String() {
		http.Error(w, "You do not have access to this resource", http.StatusForbidden)
		return
	}

	// Since the whole entity is re-written, we need to assign any invariant fields again
	// e.g. the owner of the entity.
	p.Email = user.Current(c).String()

	// Keep track of the last modification date.
	p.LastModified = time.Now()

	// Attempt to overwrite the old entity.
	_, err = datastore.Put(c, k, p)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Let them know it succeeded.
	w.WriteHeader(http.StatusNoContent)
}
Beispiel #6
0
// Authenticate process the request and returns a populated UserProfile.
// If the Authenticate method can not authenticate the User based on the
// request, an error or a redirect URL wll be return.
func (p *Provider) Authenticate(w http.ResponseWriter, r *http.Request) (
	up *profile.Profile, redirectURL string, err error) {

	c := context.NewContext(r)

	url := r.FormValue("provider")
	// Set provider info.
	up = profile.New(p.Name, url)

	// Check for current User.

	u := aeuser.Current(c)

	if u == nil {
		redirectURL := r.URL.Path + "/callback"
		loginUrl, err := aeuser.LoginURLFederated(c, redirectURL, url)
		return up, loginUrl, err
	}

	if u.FederatedIdentity != "" {
		up.ID = u.FederatedIdentity
	} else {
		up.ID = u.ID
	}

	per := new(person.Person)
	per.Email = u.Email
	per.Emails = []*person.PersonEmails{
		&person.PersonEmails{true, "home", u.Email},
	}
	per.URL = u.FederatedIdentity
	up.Person = per

	return up, "", nil
}
Beispiel #7
0
func ExportOpml(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	cu := user.Current(c)
	gn := goon.FromContext(c)
	u := User{Id: cu.ID}
	ud := UserData{Id: "data", Parent: gn.Key(&User{Id: cu.ID})}
	if err := gn.Get(&u); err != nil {
		serveError(w, err)
		return
	}
	gn.Get(&ud)
	opml := Opml{}
	json.Unmarshal(ud.Opml, &opml)
	opml.Version = "1.0"
	opml.Title = fmt.Sprintf("%s subscriptions in Go Read", u.Email)
	for _, o := range opml.Outline {
		o.Text = o.Title
		if len(o.XmlUrl) > 0 {
			o.Type = "rss"
		}
		for _, so := range o.Outline {
			so.Text = so.Title
			so.Type = "rss"
		}
	}
	b, _ := xml.MarshalIndent(&opml, "", "\t")
	w.Header().Add("Content-Type", "text/xml")
	w.Header().Add("Content-Disposition", "attachment; filename=subscriptions.opml")
	fmt.Fprint(w, xml.Header, string(b))
}
Beispiel #8
0
func MarkUnread(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	cu := user.Current(c)
	gn := goon.FromContext(c)
	read := make(Read)
	f := r.FormValue("feed")
	s := r.FormValue("story")
	rs := readStory{Feed: f, Story: s}
	u := &User{Id: cu.ID}
	ud := &UserData{
		Id:     "data",
		Parent: gn.Key(u),
	}
	gn.RunInTransaction(func(gn *goon.Goon) error {
		if err := gn.Get(ud); err != nil {
			return err
		}
		gob.NewDecoder(bytes.NewReader(ud.Read)).Decode(&read)
		delete(read, rs)
		b := bytes.Buffer{}
		gob.NewEncoder(&b).Encode(&read)
		ud.Read = b.Bytes()
		_, err := gn.Put(ud)
		return err
	}, nil)
}
Beispiel #9
0
func Donate(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	cu := user.Current(c)
	gn := goon.FromContext(c)
	u := User{Id: cu.ID}
	if err := gn.Get(&u); err != nil {
		serveError(w, err)
		return
	}
	amount, err := strconv.Atoi(r.FormValue("amount"))
	if err != nil || amount < 200 {
		serveError(w, fmt.Errorf("bad amount: %v", r.FormValue("amount")))
		return
	}
	resp, err := stripe(c, "POST", "charges", url.Values{
		"amount":      {r.FormValue("amount")},
		"description": {fmt.Sprintf("%v - %v", u.Id, u.Email)},
		"card":        {r.FormValue("stripeToken")},
		"currency":    {"usd"},
	}.Encode())
	if err != nil {
		serveError(w, err)
		return
	} else if resp.StatusCode != http.StatusOK {
		c.Errorf("%s", resp.Body)
		serveError(w, fmt.Errorf("Error"))
		return
	}
}
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)
	}
}
Beispiel #11
0
func AppOps(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c) // Login is mandatory on this page. No need to check nil value here.
	if !IsUserAllowed(u) {
		InvalidUserPage(c, w, r, u)
		return
	}
	logoutUrl, err := LogoutURL(c, r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	investments, err := GetInvestments(c)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	params := appParams{
		User:        u.String(),
		LogoutURL:   logoutUrl,
		Investments: investments}
	if err := appOpsTemplate.Execute(w, params); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Beispiel #12
0
func DeleteTag(c appengine.Context, tag string) (err os.Error) {
	// Fetch bookmarks with this tag
	q := datastore.NewQuery("Bookmark").Filter("UserId=", user.Current(c).Id).Filter("Tags=", tag)
	count, err := q.Count(c)
	if err != nil {
		return err
	}
	var bms []Bookmark
	keys, err := q.GetAll(c, &bms)
	if err != nil {
		return err
	}

	// Remove tag from bookmark
	bmsRef := make([]interface{}, count)
	for i := 0; i < len(bms); i++ {
		bmsRef[i] = &bms[i]
		btags := bms[i].Tags
		for j := 0; j < len(btags); j++ {
			if btags[j] == tag {
				bms[i].Tags = append(btags[:j], btags[j+1:]...)
				break
			}
		}
	}

	// Put them back on the datastore
	_, err = datastore.PutMulti(c, keys, bmsRef)
	return err
}
Beispiel #13
0
func UploadOpml(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	opml := Opml{}
	if err := json.Unmarshal([]byte(r.FormValue("opml")), &opml.Outline); err != nil {
		serveError(w, err)
		return
	}
	backupOPML(c)
	cu := user.Current(c)
	gn := goon.FromContext(c)
	u := User{Id: cu.ID}
	ud := UserData{Id: "data", Parent: gn.Key(&u)}
	if err := gn.Get(&ud); err != nil {
		serveError(w, err)
		c.Errorf("get err: %v", err)
		return
	}
	if b, err := json.Marshal(&opml); err != nil {
		serveError(w, err)
		c.Errorf("json err: %v", err)
		return
	} else {
		l := Log{
			Parent: ud.Parent,
			Id:     time.Now().UnixNano(),
			Text:   fmt.Sprintf("upload opml: %v -> %v", len(ud.Opml), len(b)),
		}
		ud.Opml = b
		if _, err := gn.PutMany(&ud, &l); err != nil {
			serveError(w, err)
			return
		}
		backupOPML(c)
	}
}
Beispiel #14
0
func MarkRead(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	cu := user.Current(c)
	gn := goon.FromContext(c)
	read := make(Read)
	var stories []readStory
	defer r.Body.Close()
	b, _ := ioutil.ReadAll(r.Body)
	if err := json.Unmarshal(b, &stories); err != nil {
		serveError(w, err)
		return
	}
	gn.RunInTransaction(func(gn *goon.Goon) error {
		u := &User{Id: cu.ID}
		ud := &UserData{
			Id:     "data",
			Parent: gn.Key(u),
		}
		if err := gn.Get(ud); err != nil {
			return err
		}
		gob.NewDecoder(bytes.NewReader(ud.Read)).Decode(&read)
		for _, s := range stories {
			read[s] = true
		}
		var b bytes.Buffer
		gob.NewEncoder(&b).Encode(&read)
		ud.Read = b.Bytes()
		_, err := gn.Put(ud)
		return err
	}, nil)
}
Beispiel #15
0
func AddSubscription(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	backupOPML(c)
	cu := user.Current(c)
	url := r.FormValue("url")
	o := &OpmlOutline{
		Outline: []*OpmlOutline{
			&OpmlOutline{XmlUrl: url},
		},
	}
	if err := addFeed(c, cu.ID, o); err != nil {
		c.Errorf("add sub error (%s): %s", url, err.Error())
		serveError(w, err)
		return
	}

	gn := goon.FromContext(c)
	ud := UserData{Id: "data", Parent: gn.Key(&User{Id: cu.ID})}
	gn.Get(&ud)
	if err := mergeUserOpml(c, &ud, o); err != nil {
		c.Errorf("add sub error opml (%v): %v", url, err)
		serveError(w, err)
		return
	}
	gn.PutMany(&ud, &Log{
		Parent: ud.Parent,
		Id:     time.Now().UnixNano(),
		Text:   fmt.Sprintf("add sub: %v", url),
	})
	if r.Method == "GET" {
		http.Redirect(w, r, routeUrl("main"), http.StatusFound)
	}
	backupOPML(c)
}
Beispiel #16
0
// Renders a template
func Render(w http.ResponseWriter, r *http.Request, passedTemplate *bytes.Buffer, Statuscode ...int) {
	// Add some HTTP Headers
	if len(Statuscode) == 1 {
		w.WriteHeader(Statuscode[0])
	}

	c := appengine.NewContext(r)
	u := user.Current(c)
	headerdata := HeaderData{}
	if u != nil {
		headerdata.IsLoggedIn = true
		headerdata.Username = u.String()
		if user.IsAdmin(c) {
			headerdata.IsAdmin = true
		}
	}

	// Header
	template.Must(template.ParseFiles("templates/header.html")).Execute(w, headerdata)

	// Now add the passedTemplate
	fmt.Fprintf(w, "%s", string(passedTemplate.Bytes())) // %s = the uninterpreted bytes of the string or slice

	// And now we execute the footer
	template.Must(template.ParseFiles("templates/footer.html")).Execute(w, nil)
}
Beispiel #17
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)
	}

}
Beispiel #18
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
}
Beispiel #19
0
func DeleteUser(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	username := GetRequestVar(r, "username", c)
	username = strings.ToLower(username)

	userID, err := getUserID(username, c)
	if err != nil {
		c.Infof("Could not find user with username '%v': %v", username, err.Error())
		http.NotFound(w, r)
		return
	}

	currentUser := user.Current(c)

	if !canDeleteAppUser(userID, currentUser) {
		c.Errorf("%v cannot delete user %v.", currentUser.ID, userID)
		http.Error(w, "You cannot delete another user.", http.StatusForbidden)
		return
	}

	c.Infof("Deleting user %v...", userID)

	err = deleteAppUser(userID, c)
	if err != nil {
		c.Errorf("Failed to delete user %v: %v", userID, err)
		http.Error(w, "Failed to delete user.", http.StatusInternalServerError)
		return
	}

	c.Infof("Deleted user %v.", userID)

	resp := OkResponse{true}
	sendJsonResponse(w, resp)
}
Beispiel #20
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)
	}
}
Beispiel #21
0
func FeedHistory(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	cu := user.Current(c)
	gn := goon.FromContext(c)
	u := User{Id: cu.ID}
	uk := gn.Key(&u)
	if v := r.FormValue("v"); len(v) == 0 {
		q := datastore.NewQuery(gn.Key(&UserOpml{}).Kind()).Ancestor(uk).KeysOnly()
		keys, err := gn.GetAll(q, nil)
		if err != nil {
			serveError(w, err)
			return
		}
		times := make([]string, len(keys))
		for i, k := range keys {
			times[i] = strconv.FormatInt(k.IntID(), 10)
		}
		b, _ := json.Marshal(&times)
		w.Write(b)
	} else {
		a, _ := strconv.ParseInt(v, 10, 64)
		uo := UserOpml{Id: a, Parent: uk}
		if err := gn.Get(&uo); err != nil {
			serveError(w, err)
			return
		}
		downloadOpml(w, uo.opml(), cu.Email)
	}
}
Beispiel #22
0
// uploadHandler handles the image upload and stores a new Overlay in the
// datastore. If successful, it writes the Overlay's key to the response.
func uploadHandler(c appengine.Context, w http.ResponseWriter, r *http.Request) *appError {
	// Handle the upload, and get the image's BlobKey.
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		return appErrorf(err, "could not parse blobs from blobstore upload")
	}
	b := blobs["overlay"]
	if len(b) < 1 {
		return appErrorf(nil, "could not find overlay blob")
	}
	bk := b[0].BlobKey

	// Fetch image from blob store to find its width and height.
	m, err := imageBlob(c, bk)
	if err != nil {
		return appErrorf(err, "could not get image")
	}

	// Create and store a new Overlay in the datastore.
	o := &Overlay{
		Owner:  user.Current(c).ID,
		Image:  bk,
		Width:  m.Bounds().Dx(),
		Height: m.Bounds().Dy(),
	}
	k := datastore.NewIncompleteKey(c, "Overlay", nil)
	k, err = datastore.Put(c, k, o)
	if err != nil {
		return appErrorf(err, "could not save new overlay to datastore")
	}

	// It will be known hereafter by its datastore-provided key.
	fmt.Fprintf(w, "%s", k.Encode())
	return nil
}
Beispiel #23
0
func ByTags(c appengine.Context, tags []string) (bms []Bookmark, err os.Error) {
	q := datastore.NewQuery("Bookmark").Filter("UserId=", user.Current(c).Id).Order("Title")

	// Build query
	var negTags []string
	for _, tag := range tags {
		if tag != "" {
			op := tag[0:1]
			switch op {
			case "-":
				negTags = append(negTags, tag[1:])
			case "!":
				q.Filter("Tags=", tag[1:])
			default:
				q.Filter("Tags=", tag)
			}
		}
	}

	count, err := q.Count(c)
	if err != nil {
		return
	}
	bms = make([]Bookmark, 0, count)
	_, err = q.GetAll(c, &bms)

	bms = FilterTags(bms, negTags)

	return bms, err
}
Beispiel #24
0
func join(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.String(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	r.ParseForm()
	// TODO check table arg
	state, err := joinTable(c, r.Form["table"][0], u.String())
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	var b []byte
	b, err = json.Marshal(state)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "%s", b)
}
Beispiel #25
0
func doUncheckout(c mpg.Context) (*UserCharge, error) {
	cu := user.Current(c)
	gn := goon.FromContext(c)
	u := User{Id: cu.ID}
	uc := UserCharge{Id: 1, Parent: gn.Key(&u)}
	if err := gn.Get(&u); err != nil {
		return nil, err
	}
	if err := gn.Get(&uc); err != nil || len(uc.Customer) == 0 {
		return nil, err
	}
	resp, err := stripe(c, "DELETE", "customers/"+uc.Customer, "")
	if err != nil {
		return nil, err
	} else if resp.StatusCode != http.StatusOK {
		c.Errorf("%s", resp.Body)
		c.Errorf("stripe delete error, but proceeding")
	}
	if err := gn.RunInTransaction(func(gn *goon.Goon) error {
		if err := gn.Get(&u); err != nil && err != datastore.ErrNoSuchEntity {
			return err
		}
		u.Account = AFree
		u.Until = uc.Next
		if err := gn.Delete(gn.Key(&uc)); err != nil {
			return err
		}
		_, err := gn.Put(&u)
		return err
	}, nil); err != nil {
		return nil, err
	}
	return &uc, nil
}
Beispiel #26
0
func MarkRead(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	cu := user.Current(c)
	gn := goon.FromContext(c)
	read := make(Read)
	var stories []readStory
	if r.FormValue("stories") != "" {
		json.Unmarshal([]byte(r.FormValue("stories")), &stories)
	}
	if r.FormValue("feed") != "" {
		stories = append(stories, readStory{
			Feed:  r.FormValue("feed"),
			Story: r.FormValue("story"),
		})
	}

	gn.RunInTransaction(func(gn *goon.Goon) error {
		u := &User{Id: cu.ID}
		ud := &UserData{
			Id:     "data",
			Parent: gn.Key(u),
		}
		gn.Get(ud)
		gob.NewDecoder(bytes.NewReader(ud.Read)).Decode(&read)
		for _, s := range stories {
			read[s] = true
		}
		var b bytes.Buffer
		gob.NewEncoder(&b).Encode(&read)
		ud.Read = b.Bytes()
		_, err := gn.Put(ud)
		return err
	}, nil)
}
Beispiel #27
0
func CheckPerm(w http.ResponseWriter, r *http.Request, op byte) (err error) {

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

	if u == nil {
		redirectLogin(w, r)
		return errors.New("user not exits")
	}

	if !user.IsAdmin(c) {
		// Si no es admin, deberiamos buscarlo en nuestra base
		// de datos de usuarios permitidos y comprobar si
		// con su rol puede hacer dicha operación
		// De esa busqueda calculamos la variable perm y la comparamos
		// con op

		/*if !IsAllowed(perm,op){
		redirectLogin(w,r)
		return
		}*/

		redirectLogin(w, r)
		return errors.New("user has not perm for the operation")
	}

	// Si es admin puede cualquier cosa
	return nil
}
Beispiel #28
0
func Index(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "GET request only", http.StatusMethodNotAllowed)
		return
	}

	c := appengine.NewContext(r)

	q := datastore.NewQuery("Greeting").Ancestor(models.GuestBookKey(c)).Order("-Date").Limit(10)
	greetings := make([]models.Greeting, 0, 10)
	if _, err := q.GetAll(c, &greetings); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	type exec struct {
		Author    string
		Greetings []models.Greeting
	}
	e := exec{
		Greetings: greetings,
	}
	if u := user.Current(c); u != nil {
		e.Author = u.String()
	}

	if err := views.GuestBookTemplate.Execute(w, e); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Beispiel #29
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
}
Beispiel #30
0
func webuserOK(c appengine.Context, w http.ResponseWriter, r *http.Request) bool {
	if !userauthenticated(c) {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return false
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return false
	}
	u := user.Current(c)
	authzed, err := userauthorized(c, u.Email)
	if err != nil {
		c.Errorf("authorization error: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return false
	}
	if !authzed {
		c.Warningf("authorization failure: %v", u.Email)
		w.WriteHeader(http.StatusForbidden)
		err = templates.ExecuteTemplate(w, "unauthorized.html", nil)
		if err != nil {
			c.Errorf("unauthorized user and got err on template: %v", err)
		}
		return false
	}
	return true
}