当前位置: 首页>>代码示例>>Golang>>正文


Golang user.Current函数代码示例

本文整理汇总了Golang中appengine/user.Current函数的典型用法代码示例。如果您正苦于以下问题:Golang Current函数的具体用法?Golang Current怎么用?Golang Current使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Current函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: HandleSign

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
}
开发者ID:kunnig,项目名称:roegebeern,代码行数:27,代码来源:buriggies.go

示例2: saveToken

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
}
开发者ID:pcarleton,项目名称:vensplit,代码行数:28,代码来源:app.go

示例3: TestContext

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("[email protected]", 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("[email protected]", 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")
	}
}
开发者ID:icub3d,项目名称:appenginetesting,代码行数:58,代码来源:context_test.go

示例4: handleSign

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)
}
开发者ID:DeanSinaean,项目名称:csnuts,代码行数:57,代码来源:handleSign.go

示例5: update

// 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)
}
开发者ID:CNDonny,项目名称:scope,代码行数:57,代码来源:main.go

示例6: Authenticate

// 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
}
开发者ID:scotch,项目名称:aego,代码行数:38,代码来源:appengine_openid.go

示例7: ExportOpml

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))
}
开发者ID:jgasteiz,项目名称:irakurrigo,代码行数:29,代码来源:user.go

示例8: MarkUnread

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)
}
开发者ID:jgasteiz,项目名称:irakurrigo,代码行数:25,代码来源:user.go

示例9: Donate

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
	}
}
开发者ID:nillchopra,项目名称:goread,代码行数:28,代码来源:charge.go

示例10: admin

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)
	}
}
开发者ID:aaronlindsey,项目名称:tamu-student-senate-app,代码行数:28,代码来源:admin.go

示例11: AppOps

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)
	}
}
开发者ID:danielfireman,项目名称:isumm,代码行数:26,代码来源:handler_app_ops.go

示例12: DeleteTag

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
}
开发者ID:xconstruct,项目名称:bin-o-bookmarks,代码行数:30,代码来源:bookmarks.go

示例13: UploadOpml

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)
	}
}
开发者ID:JesseLivingston,项目名称:goread,代码行数:34,代码来源:user.go

示例14: MarkRead

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)
}
开发者ID:JesseLivingston,项目名称:goread,代码行数:31,代码来源:user.go

示例15: AddSubscription

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)
}
开发者ID:JesseLivingston,项目名称:goread,代码行数:33,代码来源:user.go


注:本文中的appengine/user.Current函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。