Esempio n. 1
0
func NewUser(r *http.Request, id string, email string, name string, provider string) (*User, error) {
	c := appengine.NewContext(r)
	// create new user
	userId, _, _ := datastore.AllocateIDs(c, "User", nil, 1)
	key := datastore.NewKey(c, "User", "", userId, nil)

	user := User{userId, email, name, time.Now()}

	_, err := datastore.Put(c, key, &user)
	if err != nil {
		return nil, err
	}
	// create external authentication
	externalAuthId, _, _ := datastore.AllocateIDs(c, "ExternalAuth", nil, 1)
	key = datastore.NewKey(c, "ExternalAuth", "", externalAuthId, nil)

	externalAuth := ExternalAuth{externalAuthId, id, userId, provider}

	_, err = datastore.Put(c, key, &externalAuth)
	if err != nil {
		return nil, err
	}

	return &user, err
}
Esempio n. 2
0
func TestTestbed(t *testing.T) {
	bed := NewTestbed(PYTHON, TESTBED, APPENGINE)
	bed.Start()
	defer bed.Close()

	// create a dummy context
	r, _ := http.NewRequest("GET", "http://example.com/", nil)
	c := bed.NewContext(r)

	low, high, err := datastore.AllocateIDs(c, "Test", nil, 10)
	if err != nil {
		t.Errorf("got error: %v", err)
	}
	if high-low != 10 {
		t.Errorf("wrong values: %d, %d", low, high)
	}
	fmt.Printf("low=%d, high=%d\n", low, high)

	low2, high2, err := datastore.AllocateIDs(c, "Test", nil, 10)
	if err != nil {
		t.Errorf("got error: %v", err)
	}
	if high2-low2 != 10 {
		t.Errorf("wrong values: %d, %d", low2, high2)
	}
	if low2 < high {
		t.Errorf("wrong values: %d, %d", high, low2)
	}
	fmt.Printf("low=%d, high=%d\n", low2, high2)

	bed.Reset()

	low3, high3, _ := datastore.AllocateIDs(c, "Test", nil, 10)
	fmt.Printf("low=%d, high=%d\n", low3, high3)
}
Esempio n. 3
0
func save(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	id, _, err := datastore.AllocateIDs(c, "Dare", parentProject(c), 1)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	key := datastore.NewKey(c, "Dare", "", id, parentProject(c))

	d := Dare{
		OptionA: r.FormValue("OptionA"),
		OptionB: r.FormValue("OptionB"),
		AmountA: 0,
		AmountB: 0,
		Id:      int(id),
	}

	_, err = datastore.Put(c, key, &d)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	url := fmt.Sprintf("/question/%d", id)
	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
Esempio n. 4
0
File: ds.go Progetto: gaego/ds
func AllocateIDs(c appengine.Context, kind string, parent *datastore.Key, n int) (low, high int64, err error) {
	// TODO: added for testing. Allocating IDs for mememache and memory
	// should not be used in production.
	sc := getConfig(kind)
	if sc.Datastore {
		return datastore.AllocateIDs(c, kind, parent, n)
	}
	t := time.Now()
	//var l int64
	l := t.UnixNano()
	return l, l + int64(n), nil
}
Esempio n. 5
0
func (dao *gaeAccountingDao) NewAccountMovementKey(participant string) (string, error) {
	parent := AccountKey(dao.c, participant)
	if dao.low == dao.high {
		if l, h, err := datastore.AllocateIDs(dao.c, "AccountMovement", parent, 2); err != nil {
			return "", err
		} else {
			dao.low, dao.high = l, h
		}
	}
	r := dao.low
	dao.low++
	return datastore.NewKey(dao.c, "AccountMovement", "", r, parent).Encode(), nil
}
Esempio n. 6
0
// NewKey is a helper function that allocates a new id and uses it to
// make a new key. It returns both the string and struct version fo
// the key. If a failure occured, false is returned and a response was
// returned to the request. This case should be terminal.
func NewKey(c appengine.Context, w http.ResponseWriter, r *http.Request,
	kind string, parent *datastore.Key) (string, *datastore.Key, bool) {

	// Generate a new key for this kind.
	id, _, err := datastore.AllocateIDs(c, kind, parent, 1)
	if err != nil {
		LogAndUnexpected(c, w, r, err)
		return "", nil, false
	}
	key := datastore.NewKey(c, kind, "", id, parent)

	return key.Encode(), key, true
}
Esempio n. 7
0
func AddPage(r *http.Request, name string, content string) error {
	// create new page
	c := appengine.NewContext(r)
	pageID, _, _ := datastore.AllocateIDs(c, "Page", nil, 1)
	key := datastore.NewKey(c, "Page", "", pageID, nil)

	page := Page{pageID, name, content, time.Now()}

	_, err := datastore.Put(c, key, &page)
	if err != nil {
		return err
	}
	// Add the item to the memcache
	err = cache(r, page)

	return err
}
Esempio n. 8
0
// NewPostHandler is the HTTP handler to create a new Post
func NewPostHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	c.Infof("cs253: Requested URL: %v", r.URL)
	c.Infof("cs253: Method: %v", r.Method)

	if r.Method == "GET" {
		writeNewPostForm(c, w, &NewPostForm{})
	} else if r.Method == "POST" {
		postForm := NewPostForm{
			r.FormValue("subject"),
			r.FormValue("content"),
			"",
		}
		if !(tools.IsStringValid(postForm.Subject) &&
			tools.IsStringValid(postForm.Content)) {

			postForm.Error = "We need to set both a subject and some content"
			writeNewPostForm(c, w, &postForm)
		} else {
			c.Infof("cs253: Blog new post:")

			postID, _, _ := datastore.AllocateIDs(c, "Post", nil, 1)
			key := datastore.NewKey(c, "Post", "", postID, nil)
			p := models.Post{
				postID,
				postForm.Subject,
				postForm.Content,
				time.Now(),
			}
			key, err := datastore.Put(c, key, &p)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			c.Infof("cs253: Blog Key: %v", key.IntID())

			// build url and redirect
			permalinkURL := "/blog/" + strconv.FormatInt(p.Id, 10)
			http.Redirect(w, r, permalinkURL, http.StatusFound)
		}
	} else {
		tools.Error404(w)
		return
	}
}
Esempio n. 9
0
func (dao *LeagueDao) SaveLeague(league domain.League) (*domain.League, error) {
	if league.ID == 0 {
		leagueID, _, _ := datastore.AllocateIDs(dao.Context, EntityLeague, nil, 1)
		league.ID = leagueID
	}

	key := datastore.NewKey(dao.Context, EntityLeague, "", league.ID, nil)

	l, err := dao.save(key, &league)

	if err != nil {
		return nil, err
	}

	savedLeague := l.(*domain.League)

	return savedLeague, err
}
Esempio n. 10
0
func (dao *PlayerDao) SavePlayer(player domain.Player) (*domain.Player, error) {
	if player.ID == 0 {
		playerID, _, _ := datastore.AllocateIDs(dao.Context, EntityPlayer, nil, 1)
		player.ID = playerID
	}

	key := datastore.NewKey(dao.Context, EntityPlayer, "", player.ID, nil)

	p, err := dao.save(key, &player)

	if err != nil {
		return nil, err
	}

	savedPlayer := p.(*domain.Player)

	return savedPlayer, err
}
Esempio n. 11
0
func (dao *GameDao) SaveGame(game domain.Game) (*domain.Game, error) {
	if game.ID == 0 {
		gameID, _, _ := datastore.AllocateIDs(dao.Context, EntityGame, nil, 1)
		game.ID = gameID
	}

	leagueKey := datastore.NewKey(dao.Context, EntityLeague, "", game.LeagueID, nil)
	game.League = leagueKey
	key := datastore.NewKey(dao.Context, EntityGame, "", game.ID, leagueKey)

	g, err := dao.save(key, &game)

	if err != nil {
		return nil, err
	}

	savedGame := g.(*domain.Game)

	return savedGame, err
}
Esempio n. 12
0
func (d *Driver) Insert(m driver.Model, data interface{}) (driver.Result, error) {
	var id int64
	fields := m.Fields()
	var pkVal *reflect.Value
	// TODO: If the PK is supplied by the user rather than auto-assigned, it
	// might conflict with PKs generated by datastore.AllocateIDs().
	if fields.PrimaryKey >= 0 {
		p := d.primaryKey(fields, data)
		if p.IsValid() && types.Kind(p.Kind()) == types.Int {
			id = p.Int()
			if id == 0 {
				// Must assign PK field value after calling AllocateIDs
				pkVal = &p
			}
		}
	}
	name := m.Table()
	// Make all objects of a given kind ancestors of the same key. While
	// this hurts scalability, it makes all reads strongly consistent.
	parent := d.parentKey(m)
	var err error
	if id == 0 {
		id, _, err = datastore.AllocateIDs(d.c, name, parent, 1)
		if err != nil {
			return nil, err
		}
	}
	if fields.AutoincrementPk && pkVal != nil {
		pkVal.SetInt(int64(id))
	}
	key := datastore.NewKey(d.c, name, "", id, parent)
	log.Debugf("DATASTORE: put %s %v", key, data)
	_, err = datastore.Put(d.c, key, data)
	if err != nil {
		return nil, err
	}
	return &result{key: key, count: 1}, nil
}
Esempio n. 13
0
func getChannelToken(c appengine.Context, w http.ResponseWriter, req *http.Request) (string, error) {
	tokenCookie, err := req.Cookie("token")
	if err != nil {
		low, _, err := datastore.AllocateIDs(c, "Endpoint", nil, 1)
		if err != nil {
			return "", err
		}
		browserId := strconv.FormatInt(low, 10)
		token, err := channel.Create(c, browserId)
		if err != nil {
			return "", err
		}
		cookie := http.Cookie{Name: "token", Value: token, MaxAge: 7200} /* two hours */
		http.SetCookie(w, &cookie)

		epkey := datastore.NewKey(c, "EndpointUser", "", low, nil)
		if _, err := datastore.Put(c, epkey, &EndpointUser{Token: token, CreatedOn: time.Now()}); err != nil {
			return "", err
		}

		return token, nil
	}
	return tokenCookie.Value, nil
}
Esempio n. 14
0
func makeKey(c appengine.Context, parent *datastore.Key) *datastore.Key {
	id, _, _ := datastore.AllocateIDs(c, "Item", parent, 1)
	return datastore.NewKey(c, "Item", "", id, parent)
}
Esempio n. 15
0
func unit4Signup(w http.ResponseWriter, r *http.Request) {

	if r.Method == "GET" {
		form := struct {
			Username      string
			Password      string
			Verify        string
			Email         string
			ErrorUsername string
			ErrorPassword string
			ErrorVerify   string
			ErrorEmail    string
		}{
			"", "", "", "", "", "", "", "",
		}
		writeForm(w, form)
	}
	if r.Method == "POST" {
		errorUsername := ""
		errorPassword := ""
		errorVerify := ""
		errorEmail := ""
		// Get form field values
		username := r.FormValue("username")
		password := r.FormValue("password")
		verify := r.FormValue("verify")
		email := r.FormValue("email")
		// Validate form fields
		if !(validUsername(username) && validPassword(password) && (password == verify) && validEmail(email)) {
			if !validUsername(username) {
				errorUsername = "******"
			}
			if !validPassword(password) {
				errorPassword = "******"
			}
			if password != verify {
				errorVerify = "Your passwords didn't match"
			}
			if !validEmail(email) {
				errorEmail = "That's not a valid email"
			}

			password = ""
			verify = ""

			form := struct {
				Username      string
				Password      string
				Verify        string
				Email         string
				ErrorUsername string
				ErrorPassword string
				ErrorVerify   string
				ErrorEmail    string
			}{
				username,
				password,
				verify,
				email,
				errorUsername,
				errorPassword,
				errorVerify,
				errorEmail,
			}

			writeForm(w, form)
		} else {
			user := models.UserByUsername(r, username)

			if len(user.Username) > 0 {
				errorUsername = "******"

				form := struct {
					Username      string
					Password      string
					Verify        string
					Email         string
					ErrorUsername string
					ErrorPassword string
					ErrorVerify   string
					ErrorEmail    string
				}{
					username,
					password,
					verify,
					email,
					errorUsername,
					errorPassword,
					errorVerify,
					errorEmail,
				}

				writeForm(w, form)
			} else {
				c := appengine.NewContext(r)

				userID, _, _ := datastore.AllocateIDs(c, "User", nil, 1)
				key := datastore.NewKey(c, "WikiUser", "", userID, nil)
				u := models.User{userID, username, password, verify, email, time.Now()}
				_, err := datastore.Put(c, key, &u)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}

				userIdCookie = securecookie.New(secret, nil)

				stringID := fmt.Sprintf("%d", key.IntID())
				tools.StoreCookie(w, r, userIdCookie, "user_id", stringID)

				// redirect to the page of the newly registered user
				http.Redirect(w, r, "/unit4/welcome", http.StatusFound)
				return
			}
		}
	}
}
Esempio n. 16
0
func blogNewPost(w http.ResponseWriter, r *http.Request) {

	if r.Method == "GET" {
		// Display empty form
		data := struct {
			Subject string
			Content string
			Error   string
		}{"", "", ""}

		renderNewPostForm(w, data)
	}
	if r.Method == "POST" {
		subject := r.FormValue("subject")
		content := r.FormValue("content")

		if len(subject) <= 0 || len(content) <= 0 {
			error := "subject and content, please!"

			data := struct {
				Subject string
				Content string
				Error   string
			}{
				subject,
				content,
				error,
			}

			renderNewPostForm(w, data)
		} else {
			// create new post
			c := appengine.NewContext(r)
			postID, _, _ := datastore.AllocateIDs(c, "Post", nil, 1)
			key := datastore.NewKey(c, "Post", "", postID, nil)

			post := models.Post{postID, subject, content, time.Now()}

			_, err := datastore.Put(c, key, &post)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			// Encode post
			encodedPost, _ := json.Marshal(post)
			// Create an Item
			item := &memcache.Item{
				Key:   fmt.Sprintf("post%d", post.Id),
				Value: encodedPost,
			}
			// Add the item to the memcache
			if err := memcache.Set(c, item); err == memcache.ErrNotStored {
				c.Infof("item with key %q already exists", item.Key)
			} else if err != nil {
				c.Errorf("error adding item: %v", err)
			}
			// redirect to the page of the newly created post
			stringID := fmt.Sprintf("%d", post.Id)
			http.Redirect(w, r, "/blog/"+stringID, http.StatusFound)
			return
		}

	}
}
Esempio n. 17
0
func (d *Driver) AllocateIDs(parent *datastore.Key, n int) (low, high int64, err error) {
	return datastore.AllocateIDs(d.ctx, d.kind, parent, n)
}