Exemple #1
0
func (fs *dsFileSys) Remove(name string) error {

	// log.Printf("trying to remove %-20v", name)
	f, err := fs.fileByPath(name)
	if err == nil {
		// log.Printf("   found file %v", f.Dir+f.BName)
		// log.Printf("   fkey %-26v", f.Key)
		err = datastore.Delete(fs.Ctx(), f.Key)
		if err != nil {
			return fmt.Errorf("error removing file %v", err)
		}
	}

	d, err := fs.dirByPath(name)
	if err == nil {
		// log.Printf("   dkey %v", d.Key)
		err = datastore.Delete(fs.Ctx(), d.Key)
		d.MemCacheDelete()
		if err != nil {
			return fmt.Errorf("error removing dir %v", err)
		}
	}

	return nil

}
Exemple #2
0
func deleteHandler(w http.ResponseWriter, r *http.Request) {
	strThread := r.FormValue("thread")
	c := appengine.NewContext(r)
	threadId, _ := strconv.Atoi(strThread)

	q := datastore.NewQuery(WebSubmissionEntityName).
		Filter("Thread =", int64(threadId))

	//TODO cleanup checks whatever for emtpy or otherwise other than 1 result
	t := q.Run(c)

	var x WebSubmission
	key, err := t.Next(&x)
	if err != nil {
		serveError(c, w, err)
		fmt.Fprintf(w, "nope %v", err.Error())
		return
	}

	err2 := datastore.Delete(c, key)
	if err != nil {
		serveError(c, w, err2)
		return
	}

	http.Redirect(w, r, "/", http.StatusFound)
}
// revert modifies Idiom and deletes IdiomHistory, but not in a transaction (for now)
func (a *GaeDatastoreAccessor) revert(c context.Context, idiomID int, version int) (*Idiom, error) {
	q := datastore.NewQuery("IdiomHistory").
		Filter("Id =", idiomID).
		Order("-Version").
		Limit(2)
	histories := make([]*IdiomHistory, 0)
	historyKeys, err := q.GetAll(c, &histories)
	if err != nil {
		return nil, err
	}
	if len(histories) == 0 {
		return nil, PiError{ErrorText: fmt.Sprintf("No history found for idiom %v", idiomID), Code: 400}
	}
	if len(histories) == 1 {
		return nil, PiError{ErrorText: fmt.Sprintf("Can't revert the only version of idiom %v", idiomID), Code: 400}
	}
	if histories[0].Version != version {
		return nil, PiError{ErrorText: fmt.Sprintf("Can't revert idiom %v: last version is not %v", idiomID, version), Code: 400}
	}
	log.Infof(c, "Reverting idiom %v from version %v to version %v", idiomID, histories[0].Version, histories[1].Version)
	idiomKey := newIdiomKey(c, idiomID)
	idiom := &histories[1].Idiom
	_, err = datastore.Put(c, idiomKey, idiom)
	if err != nil {
		return nil, err
	}
	return idiom, datastore.Delete(c, historyKeys[0])
}
Exemple #4
0
func unfollow(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	ctx := appengine.NewContext(req)
	// get session
	memItem, err := getSession(req)
	if err != nil {
		log.Infof(ctx, "Attempt to unfollow from logged out user")
		http.Error(res, "You must be logged in", http.StatusForbidden)
		return
	}
	// declare a variable of type user
	// initialize user with values from memcache item
	var user User
	json.Unmarshal(memItem.Value, &user)
	// get the datastore key for the follower
	followerKey := datastore.NewKey(ctx, "Users", user.UserName, 0, nil)
	// get a datastore key for the followee
	followeeKey := datastore.NewKey(ctx, "Follows", ps.ByName("user"), 0, followerKey)
	// delete entry in datastore
	err = datastore.Delete(ctx, followeeKey)
	if err != nil {
		log.Errorf(ctx, "error deleting followee: %v", err)
		http.Error(res, err.Error(), 500)
		return
	}
	http.Redirect(res, req, "/user/"+ps.ByName("user"), 302)
}
Exemple #5
0
func serveDocumentsDelete(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
	serveAPI(res, req, func() interface{} {
		ctx := appengine.NewContext(req)
		session, _ := sessionStore.Get(req, "session")

		email, ok := session.Values["email"].(string)
		if !ok {
			return HTTPError{403, "access denied"}
		}

		id := params.ByName("id")
		userKey := datastore.NewKey(ctx, "User", email, 0, nil)
		docKey := datastore.NewKey(ctx, "Document", id, 0, userKey)
		var document Document
		err := datastore.Get(ctx, docKey, &document)
		if err != nil {
			return err
		}
		err = datastore.Delete(ctx, docKey)
		if err != nil {
			return err
		}
		return true
	})
}
Exemple #6
0
func deleteData(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)
	keyVal := req.FormValue("keyVal")
	key, err := datastore.DecodeKey(keyVal)
	if err != nil {
		http.Error(res, "Invalid data", http.StatusBadRequest)
		log.Warningf(ctx, err.Error())
		return
	}
	var l list
	err = datastore.Get(ctx, key, &l)
	if err != nil {
		http.Error(res, "Invalid data", http.StatusBadRequest)
		log.Warningf(ctx, err.Error())
		return
	}
	if l.Owner != u.Email {
		http.Error(res, "Not authorized to delete this entry", http.StatusUnauthorized)
		log.Warningf(ctx, err.Error())
		return
	}
	err = datastore.Delete(ctx, key)
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}
}
func (s *DatastoreStorage) RemoveAuthorize(code string) error {
	log.Infof(s.ctx, "RemoveAuthorize(%s)\n", code)

	k := datastore.NewKey(s.ctx, "Authorize", code, 0, nil)
	if err := datastore.Delete(s.ctx, k); err != nil {
		return err
	}
	return nil
}
//Remove removes a card from the datastore, memcache, and stripe
func Remove(w http.ResponseWriter, r *http.Request) {
	//get form values
	datastoreId := r.FormValue("customerId")
	datastoreIdInt, _ := strconv.ParseInt(datastoreId, 10, 64)

	//make sure an id was given
	if len(datastoreId) == 0 {
		output.Error(ErrMissingInput, "A customer's datastore ID must be given but was missing. This value is different from your \"Customer ID\" and should have been submitted automatically.", w, r)
		return
	}

	//init stripe
	c := appengine.NewContext(r)
	sc := createAppengineStripeClient(c)

	//delete customer on stripe
	custData, err := findByDatastoreId(c, datastoreIdInt)
	if err != nil {
		output.Error(err, "An error occured while trying to look up customer's Stripe information.", w, r)
	}
	stripeCustId := custData.StripeCustomerToken
	sc.Customers.Del(stripeCustId)

	//delete custome from datastore
	completeKey := getCustomerKeyFromId(c, datastoreIdInt)
	err = datastore.Delete(c, completeKey)
	if err != nil {
		output.Error(err, "There was an error while trying to delete this customer. Please try again.", w, r)
		return
	}

	//delete customer from memcache
	//delete list of cards in memcache since this list is now stale
	//all memcache.Delete operations are listed first so error handling doesn't return if one fails...each call does not depend on another so this is safe
	//obviously, if the card is not in the cache it cannot be removed
	err1 := memcache.Delete(c, datastoreId)
	err2 := memcache.Delete(c, custData.CustomerId)
	err3 := memcache.Delete(c, listOfCardsKey)
	if err1 != nil && err1 != memcache.ErrCacheMiss {
		output.Error(err1, "There was an error flushing this card's data from the cache (by datastore id). Please contact an administrator and have them flush the cache manually.", w, r)
		return
	}
	if err2 != nil && err2 != memcache.ErrCacheMiss {
		output.Error(err2, "There was an error flushing this card's data from the cache (by customer id). Please contact an administrator and have them flush the cache manually.", w, r)
		return
	}
	if err3 != nil && err3 != memcache.ErrCacheMiss {
		output.Error(err3, "There was an error flushing the cached list of cards.", w, r)
		return
	}

	//customer removed
	//return to client
	output.Success("removeCustomer", nil, w)
	return
}
Exemple #9
0
func deleteTask(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	c := appengine.NewContext(r)
	id, _ := strconv.ParseInt(params.ByName("id"), 10, 64)
	key := datastore.NewKey(c, "tasks", "", id, nil)
	if err := datastore.Delete(c, key); err != nil {
		sendJSONResponse(w, http.StatusNotModified, nil)
	} else {
		sendJSONResponse(w, http.StatusAccepted, nil)
	}
}
Exemple #10
0
func submissionsAddHandler(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	if err := r.ParseForm(); err != nil {
		serveErr(ctx, err, w)
		return
	}

	ID, _, err := datastore.AllocateIDs(ctx, "Podcast", nil, 1)
	if err != nil {
		serveErr(ctx, err, w)
		return
	}

	date, err := time.Parse(yyyymmdd, r.FormValue("date"))
	if err != nil {
		serveErr(ctx, err, w)
		return
	}

	podcast := Podcast{
		ID:         ID,
		Show:       r.FormValue("show"),
		Title:      r.FormValue("title"),
		Desc:       r.FormValue("desc"),
		URL:        template.URL(r.FormValue("url")),
		MediaURL:   template.URL(r.FormValue("media_url")),
		RuntimeSec: r.FormValue("runtime"),
		Size:       r.FormValue("size"),
		Date:       date,
		Added:      time.Now(),
	}

	if _, err := datastore.Put(ctx, datastore.NewKey(ctx, "Podcast", "", ID, nil), &podcast); err != nil {
		serveErr(ctx, err, w)
		return
	}

	key, err := datastore.DecodeKey(r.FormValue("key"))
	if err != nil {
		serveErr(ctx, err, w)
		return
	}

	if err := datastore.Delete(ctx, key); err != nil {
		serveErr(ctx, err, w)
		return
	}

	if err := memcache.Delete(ctx, cacheKey); err != nil {
		log.Errorf(ctx, "memcache delete error %v", err)
	}

	successTmpl.ExecuteTemplate(w, "base", nil)
}
Exemple #11
0
// Delete deletes the record based on the provided key.
//
func (goal *Goal) Delete(c context.Context) (err error) {
	// TODO: need to check for existance before deleting. if NOT exists, then throw ErrorNoMatch error (err = ErrorNoMatch)
	if err = goal.Get(c); err == types.ErrorNoMatch {
		return
	}

	key := datastore.NewKey(c, "Goal", util.StringKey(goal.Name), 0, nil)

	err = datastore.Delete(c, key)

	return
}
func (a *GaeDatastoreAccessor) deleteIdiom(c context.Context, idiomID int, why string) error {
	key, _, err := a.getIdiom(c, idiomID)
	if err != nil {
		return err
	}
	// Remove from text search index
	err = a.unindex(c, idiomID)
	if err != nil {
		log.Errorf(c, "Failed to unindex idiom %d: %v", idiomID, err)
	}
	return datastore.Delete(c, key)
	// The why param is ignored for now, because idiom doesn't exist anymore.
}
Exemple #13
0
func adminDeleteTask(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	tid := r.FormValue("taskKey")

	k, err := datastore.DecodeKey(tid)
	if err != nil {
		panic(err)
	}

	if err := datastore.Delete(c, k); err != nil {
		panic(err)
	}

	w.WriteHeader(204)
}
Exemple #14
0
func TestPostCompany(t *testing.T) {
	company := model.Company{
		Address: mail.Address{
			Name:    "companyName",
			Address: "*****@*****.**",
		},
	}

	r, err := http.NewRequest("POST", "/companies", requestBody(t, company))
	if err != nil {
		t.Fatal(err)
	}
	loginAsCompanyUser(r)
	rr := record(t, r)
	testRequestStatus(t, rr, 200, "Should be okay.")

	// Check the entity the client recieves was indeed saved in the datastore.
	var companyResponse = struct {
		Name, Address, Nick, Key string
	}{}

	if err = json.NewDecoder(rr.Body).Decode(&companyResponse); err != nil {
		t.Fatal(err)
	}

	var key *datastore.Key
	key, err = datastore.DecodeKey(companyResponse.Key)
	if err != nil {
		t.Fatal(err)
	}

	ctx := backgroundContext()

	var savedCompany model.Company

	err = datastore.Get(ctx, key, &savedCompany)
	if err != nil {
		t.Fatal(err)
	}

	if savedCompany.Address != company.Address {
		t.Fatal("Saved company is wrong")
	}

	datastore.Delete(ctx, key)
}
Exemple #15
0
func DeleteProfile(ctx context.Context, w http.ResponseWriter, r *http.Request) (int, error) {
	if r.Method != "DELETE" {
		return http.StatusMethodNotAllowed, nil
	}

	key, err := datastore.DecodeKey(mux.Vars(r)["key"])

	if err != nil {
		return http.StatusBadRequest, err
	}

	if err = datastore.Delete(ctx, key); err != nil {
		return http.StatusInternalServerError, err
	}

	return http.StatusOK, nil
}
// 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(`{}`)
}
Exemple #17
0
func deleteHandler(w http.ResponseWriter, r *http.Request) {

	urls := strings.Split(r.URL.Path, "/")
	keyId := urls[4]

	c := appengine.NewContext(r)
	k := datastore.NewKey(c, "Slide", keyId, 0, nil)

	//err
	err := datastore.Delete(c, k)
	if err != nil {
		errorPage(w, "Delete Error", "Slide Delete", err.Error(), 500)
		return
	}

	http.Redirect(w, r, "/me/", 301)
	return
}
Exemple #18
0
func handleFilesItem(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Path
	if id == "" {
		w.WriteHeader(404)
		return
	}
	c := appengine.NewContext(r)
	key := datastore.NewKey(c, "File", id, 0, nil)
	switch r.Method {
	case "GET":
		var file File
		err := datastore.Get(c, key, &file)
		if err == datastore.ErrNoSuchEntity {
			http.NotFound(w, r)
			return
		}
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			log.Errorf(c, "query file: %s", err.Error())
			return
		}
		w.Header().Set("Content-Type", "application/json")
		err = json.NewEncoder(w).Encode(&file)
		if err != nil {
			log.Errorf(c, "json encode: %s", err.Error())
		}
	case "DELETE":
		err := datastore.Delete(c, key)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			log.Errorf(c, "delete file: %s", err.Error())
			return
		}
		err = blobstore.Delete(c, appengine.BlobKey(id))
		if err != nil {
			log.Warningf(c, "delete file '%s': %s", id, err.Error())
		}
		w.WriteHeader(204)
	default:
		http.Error(w, "Valid methods are GET and DELETE", http.StatusMethodNotAllowed)
		return
	}
}
Exemple #19
0
func delete(w http.ResponseWriter, r *http.Request) {
	address, err := mail.ParseAddress(r.FormValue("email"))

	if err != nil {
		http.Error(w, "Invalid email address: "+err.Error(), 422)
		return
	}

	token, err := hex.DecodeString(r.FormValue("token"))

	if err != nil {
		http.Error(w, "Invalid token: "+err.Error(), 422)
		return
	}

	c := appengine.NewContext(r)
	q := datastore.NewQuery("subscription").Filter("Address =", address.Address).Limit(1)

	var subs []Subscription
	keys, err := q.GetAll(c, &subs)

	if len(subs) != 1 {
		http.Error(w, "Unable to identify your subscription. Got "+fmt.Sprintf("%d", len(subs))+" matches on "+address.Address, http.StatusInternalServerError)
		return
	}

	sub := subs[0]

	if !bytes.Equal(sub.Token, token) {
		http.Error(w, "Forbidden", http.StatusUnauthorized)
		return
	}

	err = datastore.Delete(c, keys[0])

	if err != nil {
		http.Error(w, "Failed to delete your subscription. Please contact [email protected].", http.StatusInternalServerError)
		return
	}

	w.Write([]byte("Your subscription was removed, we're sorry to see you go :("))
}
Exemple #20
0
func submissionsDelHandler(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	if err := r.ParseForm(); err != nil {
		serveErr(ctx, err, w)
		return
	}

	key, err := datastore.DecodeKey(r.FormValue("key"))
	if err != nil {
		serveErr(ctx, err, w)
		return
	}

	if err := datastore.Delete(ctx, key); err != nil {
		serveErr(ctx, err, w)
		return
	}

	successTmpl.ExecuteTemplate(w, "base", nil)
}
Exemple #21
0
func deletepost(rw http.ResponseWriter, req *http.Request) {
	c := appengine.NewContext(req)
	u := user.Current(c)
	s := req.FormValue("encoded_key")
	k, err := datastore.DecodeKey(s)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}
	mypost := Post{}
	err = datastore.Get(c, k, &mypost)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}
	if mypost.Author == u.String() {
		if mypost.OP {
			q := datastore.NewQuery("post").Ancestor(k).KeysOnly()
			keys, err := q.GetAll(c, struct{}{})
			if err != nil {
				http.Error(rw, err.Error(), http.StatusInternalServerError)
				return
			}
			err = datastore.DeleteMulti(c, keys)
			if err != nil {
				http.Error(rw, err.Error(), http.StatusInternalServerError)
				return
			}
		} else {
			err := datastore.Delete(c, k)
			if err != nil {
				http.Error(rw, err.Error(), http.StatusInternalServerError)
				return
			}
		}
		// 	http.Redirect(rw, req, "/view", http.StatusTemporaryRedirect)
		// } else {
		http.Redirect(rw, req, "/", http.StatusTemporaryRedirect)
	}
}
Exemple #22
0
func (mp *AppEngineProvider) SessionDestroy(c context.Context, sid string) error {
	done := make(chan bool, 2)

	go func() {
		k := datastore.NewKey(c, "BeegoSessionStore", sid, 0, nil)
		if ds_err := datastore.Delete(c, k); ds_err != nil {
			log.Errorf(c, "session-appengine: error deleting session data from datastore: %v", ds_err)
		}
		done <- true
	}()

	go func() {
		mem_err := memcache.Delete(c, sid)
		if mem_err != nil {
			log.Errorf(c, "session-appengine: error deleting session data from memcache: %v", mem_err)
		}
		done <- true
	}()

	_, _ = <-done, <-done
	return nil
}
Exemple #23
0
func unfollow(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	ctx := appengine.NewContext(req)
	memItem, err := getSession(req)
	if err != nil {
		http.Redirect(res, req, "/form/login", http.StatusFound)
		return
	}
	var user User
	json.Unmarshal(memItem.Value, &user)
	Following := ps.ByName("user")
	if Following == user.UserName {
		http.Redirect(res, req, "/", http.StatusFound)
		return
	}
	key := datastore.NewKey(ctx, "Relation", user.UserName+Following, 0, nil)
	err = datastore.Delete(ctx, key)
	if err != nil {
		log.Errorf(ctx, "error deleting todo: %v", err)
		http.Error(res, err.Error(), 500)
		return
	}
	http.Redirect(res, req, "/", http.StatusFound)
}
Exemple #24
0
// DELETE http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM
//
func (u *ProfileApi) remove(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
	}

	// 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 delete 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
	}

	// Delete the entity.
	if err := datastore.Delete(c, k); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	// Success notification.
	w.WriteHeader(http.StatusNoContent)
}
func (va GaeVotesAccessor) saveIdiomVoteOrRemove(c context.Context, vote IdiomVoteLog, nickname string) (delta int, key *datastore.Key, storedVote *IdiomVoteLog, err error) {
	key, existing, err := va.getIdiomVote(c, nickname, vote.IdiomId)
	if err != nil {
		return
	}
	if existing != nil {
		// Well, this means the user has decided to click it again, it order to take back her vote
		err = datastore.Delete(c, key)
		if err == nil {
			delta = -existing.Value
			storedVote = nil
		} else {
			storedVote = existing
		}
	} else {
		key = datastore.NewIncompleteKey(c, "IdiomVoteLog", va.createVoteIdiomLogNicknameAncestorKey(c, nickname))
		key, err = datastore.Put(c, key, &vote)
		if err == nil {
			delta = vote.Value
			storedVote = &vote
		}
	}
	return
}
Exemple #26
0
func handleTodos(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)

	todos := make([]ToDo, 0)

	switch req.Method {
	case "GET":
		q := datastore.NewQuery("ToDo").Filter("Email =", u.Email)
		iterator := q.Run(ctx)
		for {
			var todo ToDo
			key, err := iterator.Next(&todo)
			if err == datastore.Done {
				break
			} else if err != nil {
				log.Errorf(ctx, "error retrieving todos: %v", err)
				http.Error(res, err.Error(), 500)
				return
			}
			todo.ID = key.IntID()
			todos = append(todos, todo)
		}
		err := json.NewEncoder(res).Encode(todos)
		if err != nil {
			log.Errorf(ctx, "error marshalling todos: %v", err)
			return
		}
	case "POST":
		// get todo from user
		var todo ToDo
		err := json.NewDecoder(req.Body).Decode(&todo)
		if err != nil {
			log.Errorf(ctx, "error unmarshalling todos: %v", err)
			http.Error(res, err.Error(), 500)
			return
		}
		todo.Email = u.Email
		// add to datastore
		key := datastore.NewIncompleteKey(ctx, "ToDo", nil)
		key, err = datastore.Put(ctx, key, &todo)
		if err != nil {
			log.Errorf(ctx, "error adding todo: %v", err)
			http.Error(res, err.Error(), 500)
			return
		}
		todo.ID = key.IntID()
		// send back to user
		err = json.NewEncoder(res).Encode(todo)
		if err != nil {
			log.Errorf(ctx, "error marshalling todo: %v", err)
			return
		}
	case "DELETE":
		id, _ := strconv.ParseInt(req.FormValue("id"), 10, 64)
		if id == 0 {
			http.Error(res, "not found", 404)
			return
		}
		key := datastore.NewKey(ctx, "ToDo", "", id, nil)
		var todo ToDo
		err := datastore.Get(ctx, key, &todo)
		if err != nil {
			log.Errorf(ctx, "error getting todo: %v", err)
			http.Error(res, err.Error(), 500)
			return
		}
		if todo.Email != u.Email {
			http.Error(res, "access denied", 401)
			return
		}
		err = datastore.Delete(ctx, key)
		if err != nil {
			log.Errorf(ctx, "error deleting todo: %v", err)
			return
		}

	default:
		http.Error(res, "Method Not Allowed", 405)
	}
}
Exemple #27
0
//RemoveAccess removes access token from the datastore
func (s *AEStorage) RemoveAccess(c context.Context, code string) error {
	key := datastore.NewKey(c, AccessDataKind, code, 0, nil)
	return datastore.Delete(c, key)
}
Exemple #28
0
// adminHandler serves an administrative interface.
func adminHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	if !user.IsAdmin(c) {
		http.Error(w, "forbidden", http.StatusForbidden)
		return
	}

	var newLink *Link
	var doErr error
	if r.Method == "POST" {
		key := r.FormValue("key")
		switch r.FormValue("do") {
		case "Add":
			newLink = &Link{key, r.FormValue("target")}
			doErr = putLink(c, newLink)
		case "Delete":
			k := datastore.NewKey(c, kind, key, 0, nil)
			doErr = datastore.Delete(c, k)
		default:
			http.Error(w, "unknown action", http.StatusBadRequest)
		}
		err := memcache.Delete(c, cacheKey(key))
		if err != nil && err != memcache.ErrCacheMiss {
			log.Warningf(c, "%q: %v", key, err)
		}
	}

	var links []*Link
	_, err := datastore.NewQuery(kind).Order("Key").GetAll(c, &links)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		log.Errorf(c, "%v", err)
		return
	}

	// Put the new link in the list if it's not there already.
	// (Eventual consistency means that it might not show up
	// immediately, which might be confusing for the user.)
	if newLink != nil && doErr == nil {
		found := false
		for i := range links {
			if links[i].Key == newLink.Key {
				found = true
				break
			}
		}
		if !found {
			links = append([]*Link{newLink}, links...)
		}
		newLink = nil
	}

	var data = struct {
		BaseURL string
		Prefix  string
		Links   []*Link
		New     *Link
		Error   error
	}{baseURL, prefix, links, newLink, doErr}
	if err := adminTemplate.Execute(w, &data); err != nil {
		log.Criticalf(c, "adminTemplate: %v", err)
	}
}
Exemple #29
0
func (query Query) deleteByKey(key *datastore.Key) error {
	return datastore.Delete(query.Context, key)
}
func example2() {
	// [START delete]
	key := datastore.NewKey(ctx, "Employee", "asalieri", 0, nil)
	err = datastore.Delete(ctx, key)
	// [END delete]
}