Esempio n. 1
1
// Should store the given user, after encrypting its password
func TestStoreUser(t *testing.T) {
	ctx, done, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer done()

	user := &models.User{Username: "******", FirstName: "Tim", Email: "*****@*****.**", Password: []byte("I <3 golang")}
	err = repositories.StoreUser(ctx, user)

	if err != nil {
		t.Fatal(err)
	}

	key := datastore.NewKey(ctx, "User", "testertim", 0, nil)
	var storedUser models.User
	err = datastore.Get(ctx, key, &storedUser)
	if err != nil {
		t.Fatal(err)
	}

	if storedUser.FirstName != user.FirstName {
		t.Errorf("FirstName %d, want %d", storedUser.FirstName, user.FirstName)
	}

	if storedUser.Username != "" {
		t.Errorf("Username %d should be derived from the key, not stored", storedUser.Username)
	}

	if string(storedUser.Password) == "I <3 golang" {
		t.Errorf("Password %d should be hashed and not %d", string(storedUser.Password), "I <3 golang")
	}
}
Esempio n. 2
1
// Creates a user with the given username, so long as that username is not already taken
func StoreUser(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	user := &models.User{Username: params.ByName("username")}
	ctx := appengine.NewContext(r)

	_, err := repositories.GetUser(ctx, user)
	if err == nil {
		http.Error(w, "Username already exists!", http.StatusConflict)
		return
	}

	user = &models.User{
		Username:  username,
		FirstName: r.FormValue("firstName"),
		LastName:  r.FormValue("lastName"),
		Email:     r.FormValue("email"),
	}
	err = repositories.StoreUser(ctx, user)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)

	response, err := json.Marshal(user)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(response)
}