本文整理匯總了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
}
示例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
}
示例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")
}
}
示例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)
}
示例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)
}
示例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
}
示例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))
}
示例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)
}
示例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
}
}
示例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)
}
}
示例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)
}
}
示例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
}
示例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)
}
}
示例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)
}
示例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)
}