本文整理汇总了Golang中go/skia/org/infra/go/login.LoggedInAs函数的典型用法代码示例。如果您正苦于以下问题:Golang LoggedInAs函数的具体用法?Golang LoggedInAs怎么用?Golang LoggedInAs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了LoggedInAs函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: polyIgnoresAddHandler
// polyIgnoresAddHandler is for adding a new ignore rule.
func polyIgnoresAddHandler(w http.ResponseWriter, r *http.Request) {
user := login.LoggedInAs(r)
if user == "" {
util.ReportError(w, r, fmt.Errorf("Not logged in."), "You must be logged in to add an ignore rule.")
return
}
req := &IgnoresRequest{}
if err := parseJson(r, req); err != nil {
util.ReportError(w, r, err, "Failed to parse submitted data.")
return
}
if req.Filter == "" {
util.ReportError(w, r, fmt.Errorf("Invalid Filter: %q", req.Filter), "Filters can't be empty.")
return
}
d, err := human.ParseDuration(req.Duration)
if err != nil {
util.ReportError(w, r, err, "Failed to parse duration")
return
}
ignoreRule := ignore.NewIgnoreRule(user, time.Now().Add(d), req.Filter, req.Note)
if err != nil {
util.ReportError(w, r, err, "Failed to create ignore rule.")
return
}
if err = storages.IgnoreStore.Create(ignoreRule); err != nil {
util.ReportError(w, r, err, "Failed to create ignore rule.")
return
}
polyIgnoresJSONHandler(w, r)
}
示例2: triageUndoHandler
// triageUndoHandler performs an "undo" for a given change id.
// The change id's are returned in the result of polyTriageLogHandler.
// It accepts one query parameter 'id' which is the id if the change
// that should be reversed.
// If successful it retunrs the same result as a call to polyTriageLogHandler
// to reflect the changed triagelog.
func triageUndoHandler(w http.ResponseWriter, r *http.Request) {
// Get the user and make sure they are logged in.
user := login.LoggedInAs(r)
if user == "" {
util.ReportError(w, r, fmt.Errorf("Not logged in."), "You must be logged in to change expectations.")
return
}
// Extract the id to undo.
changeID, err := strconv.Atoi(r.URL.Query().Get("id"))
if err != nil {
util.ReportError(w, r, err, "Invalid change id.")
return
}
// Do the undo procedure.
_, err = storages.ExpectationsStore.UndoChange(changeID, user)
if err != nil {
util.ReportError(w, r, err, "Unable to undo.")
return
}
// Send the same response as a query for the first page.
polyTriageLogHandler(w, r)
}
示例3: AddTaskHandler
func AddTaskHandler(w http.ResponseWriter, r *http.Request, task AddTaskVars) {
if !ctfeutil.UserHasEditRights(r) {
skutil.ReportError(w, r, fmt.Errorf("Must have google or chromium account to add tasks"), "")
return
}
if task.IsAdminTask() && !ctfeutil.UserHasAdminRights(r) {
skutil.ReportError(w, r, fmt.Errorf("Must be admin to add admin tasks; contact [email protected]"), "")
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewDecoder(r.Body).Decode(&task); err != nil {
skutil.ReportError(w, r, err, fmt.Sprintf("Failed to add %T task", task))
return
}
defer skutil.Close(r.Body)
task.GetAddTaskCommonVars().Username = login.LoggedInAs(r)
task.GetAddTaskCommonVars().TsAdded = ctutil.GetCurrentTs()
if len(task.GetAddTaskCommonVars().Username) > 255 {
skutil.ReportError(w, r, fmt.Errorf("Username is too long, limit 255 bytes"), "")
return
}
if _, err := AddTask(task); err != nil {
skutil.ReportError(w, r, err, fmt.Sprintf("Failed to insert %T task", task))
return
}
}
示例4: RedoTaskHandler
func RedoTaskHandler(prototype Task, w http.ResponseWriter, r *http.Request) {
if !ctfeutil.UserHasEditRights(r) {
skutil.ReportError(w, r, fmt.Errorf("Must have google or chromium account to redo tasks"), "")
return
}
w.Header().Set("Content-Type", "application/json")
vars := struct{ Id int64 }{}
if err := json.NewDecoder(r.Body).Decode(&vars); err != nil {
skutil.ReportError(w, r, err, "Failed to parse redo request")
return
}
defer skutil.Close(r.Body)
rowQuery := fmt.Sprintf("SELECT * FROM %s WHERE id = ? AND ts_completed IS NOT NULL", prototype.TableName())
binds := []interface{}{vars.Id}
data, err := prototype.Select(rowQuery, binds...)
if err != nil {
skutil.ReportError(w, r, err, "Unable to find requested task.")
return
}
tasks := AsTaskSlice(data)
if len(tasks) != 1 {
skutil.ReportError(w, r, err, "Unable to find requested task.")
return
}
addTaskVars := tasks[0].GetPopulatedAddTaskVars()
// Replace the username with the new requester.
addTaskVars.GetAddTaskCommonVars().Username = login.LoggedInAs(r)
if _, err := AddTask(addTaskVars); err != nil {
skutil.ReportError(w, r, err, "Could not redo the task.")
return
}
}
示例5: makeBugChomperPage
// makeBugChomperPage builds and serves the BugChomper page.
func makeBugChomperPage(w http.ResponseWriter, r *http.Request) {
// Redirect for login if needed.
user := login.LoggedInAs(r)
if user == "" {
http.Redirect(w, r, login.LoginURL(w, r), http.StatusFound)
return
}
glog.Infof("Logged in as %s", user)
issueTracker := issue_tracker.New(login.GetHttpClient(r))
w.Header().Set("Content-Type", "text/html")
glog.Info("Loading bugs for " + user)
bugList, err := issueTracker.GetBugs(PROJECT_NAME, user)
if err != nil {
reportError(w, err.Error(), http.StatusInternalServerError)
return
}
bugsById := make(map[string]*issue_tracker.Issue)
bugsByPriority := make(map[string][]*issue_tracker.Issue)
for _, bug := range bugList.Items {
bugsById[strconv.Itoa(bug.Id)] = bug
var bugPriority string
for _, label := range bug.Labels {
if strings.HasPrefix(label, PRIORITY_PREFIX) {
bugPriority = label[len(PRIORITY_PREFIX):]
}
}
if _, ok := bugsByPriority[bugPriority]; !ok {
bugsByPriority[bugPriority] = make(
[]*issue_tracker.Issue, 0)
}
bugsByPriority[bugPriority] = append(
bugsByPriority[bugPriority], bug)
}
bugsJson, err := json.Marshal(bugsById)
if err != nil {
reportError(w, err.Error(), http.StatusInternalServerError)
return
}
data := struct {
Title string
User string
BugsJson template.JS
BugsByPriority *map[string][]*issue_tracker.Issue
Priorities []string
PriorityPrefix string
}{
Title: "BugChomper",
User: user,
BugsJson: template.JS(string(bugsJson)),
BugsByPriority: &bugsByPriority,
Priorities: issue_tracker.BugPriorities,
PriorityPrefix: PRIORITY_PREFIX,
}
if err := templates.ExecuteTemplate(w, "bug_chomper.html", data); err != nil {
reportError(w, err.Error(), http.StatusInternalServerError)
return
}
}
示例6: addBuildCommentHandler
func addBuildCommentHandler(w http.ResponseWriter, r *http.Request) {
defer timer.New("addBuildCommentHandler").Stop()
if !userHasEditRights(r) {
util.ReportError(w, r, fmt.Errorf("User does not have edit rights."), "User does not have edit rights.")
return
}
w.Header().Set("Content-Type", "application/json")
cache, err := getCommitCache(w, r)
if err != nil {
return
}
buildId, err := strconv.ParseInt(mux.Vars(r)["buildId"], 10, 32)
if err != nil {
util.ReportError(w, r, err, fmt.Sprintf("Invalid build id: %v", err))
return
}
comment := struct {
Comment string `json:"comment"`
}{}
if err := json.NewDecoder(r.Body).Decode(&comment); err != nil {
util.ReportError(w, r, err, fmt.Sprintf("Failed to add comment: %v", err))
return
}
defer util.Close(r.Body)
c := buildbot.BuildComment{
BuildId: int(buildId),
User: login.LoggedInAs(r),
Timestamp: float64(time.Now().UTC().Unix()),
Message: comment.Comment,
}
if err := cache.AddBuildComment(int(buildId), &c); err != nil {
util.ReportError(w, r, err, fmt.Sprintf("Failed to add comment: %v", err))
return
}
}
示例7: changeHandler
// changeHandler handles actions on individual services.
//
// The actions are forwarded off to the pulld service
// running on the machine hosting that service.
func changeHandler(w http.ResponseWriter, r *http.Request) {
if login.LoggedInAs(r) == "" {
util.ReportError(w, r, fmt.Errorf("You must be logged on to push."), "")
return
}
if err := r.ParseForm(); err != nil {
util.ReportError(w, r, err, "Failed to parse form.")
return
}
action := r.Form.Get("action")
name := r.Form.Get("name")
machine := ip.Resolve(r.Form.Get("machine"))
url := fmt.Sprintf("http://%s:10114/_/change?name=%s&action=%s", machine, name, action)
resp, err := client.Post(url, "", nil)
if err != nil {
util.ReportError(w, r, err, fmt.Sprintf("Failed to reach %s: %v %s", machine, resp, err))
return
}
defer util.Close(resp.Body)
if resp.StatusCode != 200 {
util.ReportError(w, r, err, fmt.Sprintf("Failed to reach %s: %v %s", machine, resp, err))
return
}
w.Header().Set("Content-Type", "application/json")
if _, err := io.Copy(w, resp.Body); err != nil {
glog.Errorf("Failed to copy JSON error out: %s", err)
}
}
示例8: addCommitCommentHandler
func addCommitCommentHandler(w http.ResponseWriter, r *http.Request) {
defer timer.New("addCommitCommentHandler").Stop()
if !userHasEditRights(r) {
util.ReportError(w, r, fmt.Errorf("User does not have edit rights."), "User does not have edit rights.")
return
}
w.Header().Set("Content-Type", "application/json")
commit := mux.Vars(r)["commit"]
comment := struct {
Comment string `json:"comment"`
}{}
if err := json.NewDecoder(r.Body).Decode(&comment); err != nil {
util.ReportError(w, r, err, fmt.Sprintf("Failed to add comment: %v", err))
return
}
defer util.Close(r.Body)
c := buildbot.CommitComment{
Commit: commit,
User: login.LoggedInAs(r),
Timestamp: time.Now().UTC(),
Message: comment.Comment,
}
if err := db.PutCommitComment(&c); err != nil {
util.ReportError(w, r, err, fmt.Sprintf("Failed to add commit comment: %v", err))
return
}
}
示例9: redirectHandler
// redirectHandler handles redirecting to the correct tradefed page.
func redirectHandler(w http.ResponseWriter, r *http.Request) {
if login.LoggedInAs(r) == "" {
r.Header.Set("Referer", r.URL.String())
http.Redirect(w, r, login.LoginURL(w, r), 302)
return
}
vars := mux.Vars(r)
codename := vars["codename"]
buildNumberStr := vars["buildNumber"]
target, err := codenameDB.Get([]byte(codename), nil)
if err != nil {
util.ReportError(w, r, err, "Not a valid target codename.")
return
}
buildNumber, err := strconv.Atoi(buildNumberStr)
if err != nil {
util.ReportError(w, r, err, "Not a valid build number.")
return
}
build, err := buildbot.GetBuildFromDB(string(codename), FAKE_MASTER, buildNumber)
if err != nil {
util.ReportError(w, r, err, "Could not find a matching build.")
}
id, ok := build.GetProperty("androidinternal_buildid").([]interface{})[1].(string)
if !ok {
util.ReportError(w, r, fmt.Errorf("Got %#v", id), "Could not find a matching build id.")
return
}
w.Header().Set("Content-Type", "text/html")
if _, err := w.Write([]byte(fmt.Sprintf(REDIRECT_TEMPLATE, codename, target, id, id, target, id, id, target))); err != nil {
glog.Errorf("Failed to write response: %s", err)
}
}
示例10: handleAlert
func handleAlert(alertId int64, comment string, until int, w http.ResponseWriter, r *http.Request) {
email := login.LoggedInAs(r)
if !userHasEditRights(email) {
util.ReportError(w, r, fmt.Errorf("User does not have edit rights."), "You must be logged in to an account with edit rights to do that.")
return
}
action, ok := mux.Vars(r)["action"]
if !ok {
util.ReportError(w, r, fmt.Errorf("No action provided."), "No action provided.")
return
}
if action == "dismiss" {
glog.Infof("%s %d", action, alertId)
if err := alertManager.Dismiss(alertId, email, comment); err != nil {
util.ReportError(w, r, err, "Failed to dismiss alert.")
return
}
return
} else if action == "snooze" {
if until == 0 {
util.ReportError(w, r, fmt.Errorf("Invalid snooze time."), fmt.Sprintf("Invalid snooze time"))
return
}
until := time.Unix(int64(until), 0)
glog.Infof("%s %d until %v", action, alertId, until.String())
if err := alertManager.Snooze(alertId, until, email, comment); err != nil {
util.ReportError(w, r, err, "Failed to snooze alert.")
return
}
return
} else if action == "unsnooze" {
glog.Infof("%s %d", action, alertId)
if err := alertManager.Unsnooze(alertId, email, comment); err != nil {
util.ReportError(w, r, err, "Failed to unsnooze alert.")
return
}
return
} else if action == "addcomment" {
if !StringIsInteresting(comment) {
util.ReportError(w, r, fmt.Errorf("Invalid comment text."), comment)
return
}
glog.Infof("%s %d: %s", action, alertId, comment)
if err := alertManager.AddComment(alertId, email, comment); err != nil {
util.ReportError(w, r, err, "Failed to add comment.")
return
}
return
} else {
util.ReportError(w, r, fmt.Errorf("Invalid action %s", action), "The requested action is invalid.")
return
}
}
示例11: UserHasAdminRights
func UserHasAdminRights(r *http.Request) bool {
// TODO(benjaminwagner): Add this list to GCE project level metadata and retrieve from there.
admins := map[string]bool{
"[email protected]": true,
"[email protected]": true,
"[email protected]": true,
"[email protected]": true,
"[email protected]": true,
}
return UserHasEditRights(r) && admins[login.LoggedInAs(r)]
}
示例12: polyTriageHandler
// polyTriageHandler handles a request to change the triage status of one or more
// digests of one test.
//
// It accepts a POST'd JSON serialization of PolyTriageRequest and updates
// the expectations.
func polyTriageHandler(w http.ResponseWriter, r *http.Request) {
req := &PolyTriageRequest{}
if err := parseJson(r, req); err != nil {
util.ReportError(w, r, err, "Failed to parse JSON request.")
return
}
glog.Infof("Triage request: %#v", req)
user := login.LoggedInAs(r)
if user == "" {
util.ReportError(w, r, fmt.Errorf("Not logged in."), "You must be logged in to triage.")
return
}
// Build the expecations change request from the list of digests passed in.
digests := req.Digest
// Or build the expectations change request from filter, query, and include.
if req.All {
exp, err := storages.ExpectationsStore.Get()
if err != nil {
util.ReportError(w, r, err, "Failed to load expectations.")
return
}
e := exp.Tests[req.Test]
ii, _, err := imgInfo(req.Filter, req.Query, req.Test, e, -1, req.Include, false, "", "", req.Head)
digests = []string{}
for _, d := range ii {
digests = append(digests, d.Digest)
}
}
// Label the digests.
labelledDigests := map[string]types.Label{}
for _, d := range digests {
labelledDigests[d] = types.LabelFromString(req.Status)
}
tc := map[string]types.TestClassification{
req.Test: labelledDigests,
}
// Otherwise update the expectations directly.
if err := storages.ExpectationsStore.AddChange(tc, user); err != nil {
util.ReportError(w, r, err, "Failed to store the updated expectations.")
return
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
if err := enc.Encode(map[string]string{}); err != nil {
glog.Errorf("Failed to write or encode result: %s", err)
}
}
示例13: canDeleteTask
// Returns true if the given task can be deleted by the logged-in user; otherwise false and an error
// describing the problem.
func canDeleteTask(task Task, r *http.Request) (bool, error) {
if !ctfeutil.UserHasAdminRights(r) {
username := login.LoggedInAs(r)
taskUser := task.GetCommonCols().Username
if taskUser != username {
return false, fmt.Errorf("Task is owned by %s but you are logged in as %s", taskUser, username)
}
}
if task.GetCommonCols().TsStarted.Valid && !task.GetCommonCols().TsCompleted.Valid {
return false, fmt.Errorf("Cannot delete currently running tasks.")
}
return true, nil
}
示例14: DeleteTaskHandler
func DeleteTaskHandler(prototype Task, w http.ResponseWriter, r *http.Request) {
if !ctfeutil.UserHasEditRights(r) {
skutil.ReportError(w, r, fmt.Errorf("Must have google or chromium account to delete tasks"), "")
return
}
w.Header().Set("Content-Type", "application/json")
vars := struct{ Id int64 }{}
if err := json.NewDecoder(r.Body).Decode(&vars); err != nil {
skutil.ReportError(w, r, err, "Failed to parse delete request")
return
}
defer skutil.Close(r.Body)
requireUsernameMatch := !ctfeutil.UserHasAdminRights(r)
username := login.LoggedInAs(r)
// Put all conditions in delete request; only if the delete fails, do a select to determine the cause.
deleteQuery := fmt.Sprintf("DELETE FROM %s WHERE id = ? AND (ts_started IS NULL OR ts_completed IS NOT NULL)", prototype.TableName())
binds := []interface{}{vars.Id}
if requireUsernameMatch {
deleteQuery += " AND username = ?"
binds = append(binds, username)
}
result, err := db.DB.Exec(deleteQuery, binds...)
if err != nil {
skutil.ReportError(w, r, err, "Failed to delete")
return
}
// Check result to ensure that the row was deleted.
if rowsDeleted, _ := result.RowsAffected(); rowsDeleted == 1 {
glog.Infof("%s task with ID %d deleted by %s", prototype.GetTaskName(), vars.Id, username)
return
}
// The code below determines the reason that no rows were deleted.
rowQuery := fmt.Sprintf("SELECT * FROM %s WHERE id = ?", prototype.TableName())
data, err := prototype.Select(rowQuery, vars.Id)
if err != nil {
skutil.ReportError(w, r, err, "Unable to validate request.")
return
}
tasks := AsTaskSlice(data)
if len(tasks) != 1 {
// Row already deleted; return success.
return
}
if ok, err := canDeleteTask(tasks[0], r); !ok {
skutil.ReportError(w, r, err, "")
} else {
skutil.ReportError(w, r, fmt.Errorf("Failed to delete; reason unknown"), "")
return
}
}
示例15: alertResetHandler
// alertResetHandler deletes all the non-Bug alerts.
//
func alertResetHandler(w http.ResponseWriter, r *http.Request) {
glog.Infof("AlertResetHandler: %q\n", r.URL.Path)
if login.LoggedInAs(r) == "" {
util.ReportError(w, r, fmt.Errorf("Not logged in."), "You must be logged in to change an alert status.")
return
}
if r.Method != "POST" {
http.NotFound(w, r)
return
}
if err := alerting.Reset(); err != nil {
glog.Errorln("Failed to delete all non-Bug alerts:", err)
}
http.Redirect(w, r, "/alerts/", 303)
}