本文整理汇总了Golang中github.com/tsuru/tsuru/auth.Token.GetUserName方法的典型用法代码示例。如果您正苦于以下问题:Golang Token.GetUserName方法的具体用法?Golang Token.GetUserName怎么用?Golang Token.GetUserName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/tsuru/tsuru/auth.Token
的用法示例。
在下文中一共展示了Token.GetUserName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: serviceInstanceStatus
func serviceInstanceStatus(w http.ResponseWriter, r *http.Request, t auth.Token) error {
instanceName := r.URL.Query().Get(":instance")
serviceName := r.URL.Query().Get(":service")
serviceInstance, err := getServiceInstanceOrError(serviceName, instanceName)
if err != nil {
return err
}
permissionValue := serviceName + "/" + instanceName
allowed := permission.Check(t, permission.PermServiceInstanceReadStatus,
append(permission.Contexts(permission.CtxTeam, serviceInstance.Teams),
permission.Context(permission.CtxServiceInstance, permissionValue),
)...,
)
if !allowed {
return permission.ErrUnauthorized
}
rec.Log(t.GetUserName(), "service-instance-status", serviceName, instanceName)
var b string
if b, err = serviceInstance.Status(); err != nil {
msg := fmt.Sprintf("Could not retrieve status of service instance, error: %s", err)
return &errors.HTTP{Code: http.StatusInternalServerError, Message: msg}
}
b = fmt.Sprintf(`Service instance "%s" is %s`, instanceName, b)
n, err := w.Write([]byte(b))
if n != len(b) {
return &errors.HTTP{Code: http.StatusInternalServerError, Message: "Failed to write response body"}
}
return nil
}
示例2: deployRollback
func deployRollback(w http.ResponseWriter, r *http.Request, t auth.Token) error {
appName := r.URL.Query().Get(":appname")
instance, err := app.GetByName(appName)
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: fmt.Sprintf("App %s not found.", appName)}
}
image := r.PostFormValue("image")
if image == "" {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: "you cannot rollback without an image name",
}
}
w.Header().Set("Content-Type", "application/json")
keepAliveWriter := io.NewKeepAliveWriter(w, 30*time.Second, "")
defer keepAliveWriter.Stop()
writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
if !regexp.MustCompile(":v[0-9]+$").MatchString(image) {
img, err := getImage(appName, image)
//err is not handled because it is treated in funcion app.Deploy()
if err == nil {
image = img
}
}
err = app.Deploy(app.DeployOptions{
App: instance,
OutputStream: writer,
Image: image,
User: t.GetUserName(),
})
if err != nil {
writer.Encode(io.SimpleJsonMessage{Error: err.Error()})
}
return nil
}
示例3: serviceDelete
func serviceDelete(w http.ResponseWriter, r *http.Request, t auth.Token) error {
s, err := getService(r.URL.Query().Get(":name"))
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermServiceDelete,
append(permission.Contexts(permission.CtxTeam, s.OwnerTeams),
permission.Context(permission.CtxService, s.Name),
)...,
)
if !allowed {
return permission.ErrUnauthorized
}
rec.Log(t.GetUserName(), "delete-service", r.URL.Query().Get(":name"))
instances, err := service.GetServiceInstancesByServices([]service.Service{s})
if err != nil {
return err
}
if len(instances) > 0 {
msg := "This service cannot be removed because it has instances.\nPlease remove these instances before removing the service."
return &errors.HTTP{Code: http.StatusForbidden, Message: msg}
}
err = s.Delete()
if err != nil {
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
示例4: regenerateAPIToken
// title: regenerate token
// path: /users/api-key
// method: POST
// produce: application/json
// responses:
// 200: OK
// 401: Unauthorized
// 404: User not found
func regenerateAPIToken(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
r.ParseForm()
email := r.URL.Query().Get("user")
if email == "" {
email = t.GetUserName()
}
allowed := permission.Check(t, permission.PermUserUpdateToken,
permission.Context(permission.CtxUser, email),
)
if !allowed {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: userTarget(email),
Kind: permission.PermUserUpdateToken,
Owner: t,
CustomData: event.FormToCustomData(r.Form),
Allowed: event.Allowed(permission.PermUserReadEvents, permission.Context(permission.CtxUser, email)),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
u, err := auth.GetUserByEmail(email)
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
apiKey, err := u.RegenerateAPIKey()
if err != nil {
return err
}
w.Header().Add("Content-Type", "application/json")
return json.NewEncoder(w).Encode(apiKey)
}
示例5: servicePlans
func servicePlans(w http.ResponseWriter, r *http.Request, t auth.Token) error {
serviceName := r.URL.Query().Get(":name")
s, err := getService(serviceName)
if err != nil {
return err
}
if s.IsRestricted {
allowed := permission.Check(t, permission.PermServiceReadPlans,
append(permission.Contexts(permission.CtxTeam, s.Teams),
permission.Context(permission.CtxService, s.Name),
)...,
)
if !allowed {
return permission.ErrUnauthorized
}
}
rec.Log(t.GetUserName(), "service-plans", serviceName)
plans, err := service.GetPlansByServiceName(serviceName)
if err != nil {
return err
}
b, err := json.Marshal(plans)
if err != nil {
return nil
}
w.Write(b)
return nil
}
示例6: getTeam
func getTeam(w http.ResponseWriter, r *http.Request, t auth.Token) error {
teamName := r.URL.Query().Get(":name")
_, err := auth.GetTeam(teamName)
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: "Team not found"}
}
permsForTeam := permission.PermissionRegistry.PermissionsWithContextType(permission.CtxTeam)
var permissions []string
for _, p := range permsForTeam {
if permission.Check(t, p, permission.Context(permission.CtxTeam, teamName)) {
permissions = append(permissions, p.FullName())
}
}
if len(permissions) == 0 {
return &errors.HTTP{Code: http.StatusNotFound, Message: "Team not found"}
}
rec.Log(t.GetUserName(), "get-team", teamName)
result := map[string]interface{}{
"name": teamName,
"permissions": permissions,
}
w.Header().Set("Content-Type", "application/json")
b, err := json.Marshal(result)
if err != nil {
return err
}
n, err := w.Write(b)
if err != nil {
return err
}
if n != len(b) {
return &errors.HTTP{Code: http.StatusInternalServerError, Message: "Failed to write response body."}
}
return nil
}
示例7: grantServiceAccess
func grantServiceAccess(w http.ResponseWriter, r *http.Request, t auth.Token) error {
serviceName := r.URL.Query().Get(":service")
s, err := getService(serviceName)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermServiceUpdateGrantAccess,
append(permission.Contexts(permission.CtxTeam, s.OwnerTeams),
permission.Context(permission.CtxService, s.Name),
)...,
)
if !allowed {
return permission.ErrUnauthorized
}
teamName := r.URL.Query().Get(":team")
team, err := auth.GetTeam(teamName)
if err != nil {
if err == auth.ErrTeamNotFound {
return &errors.HTTP{Code: http.StatusNotFound, Message: "Team not found"}
}
return err
}
rec.Log(t.GetUserName(), "grant-service-access", "service="+serviceName, "team="+teamName)
err = s.GrantAccess(team)
if err != nil {
return &errors.HTTP{Code: http.StatusConflict, Message: err.Error()}
}
return s.Update()
}
示例8: deployRollback
func deployRollback(w http.ResponseWriter, r *http.Request, t auth.Token) error {
appName := r.URL.Query().Get(":appname")
instance, err := app.GetByName(appName)
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: fmt.Sprintf("App %s not found.", appName)}
}
image := r.PostFormValue("image")
if image == "" {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: "you cannot rollback without an image name",
}
}
w.Header().Set("Content-Type", "application/json")
writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(w)}
err = app.Deploy(app.DeployOptions{
App: instance,
OutputStream: writer,
Image: image,
User: t.GetUserName(),
})
if err != nil {
writer.Encode(io.SimpleJsonMessage{Error: err.Error()})
}
return nil
}
示例9: revokeServiceAccess
func revokeServiceAccess(w http.ResponseWriter, r *http.Request, t auth.Token) error {
serviceName := r.URL.Query().Get(":service")
s, err := getService(serviceName)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermServiceUpdateRevokeAccess,
append(permission.Contexts(permission.CtxTeam, s.OwnerTeams),
permission.Context(permission.CtxService, s.Name),
)...,
)
if !allowed {
return permission.ErrUnauthorized
}
teamName := r.URL.Query().Get(":team")
team, err := auth.GetTeam(teamName)
if err != nil {
if err == auth.ErrTeamNotFound {
return &errors.HTTP{Code: http.StatusNotFound, Message: "Team not found"}
}
return err
}
if len(s.Teams) < 2 {
msg := "You can not revoke the access from this team, because it is the unique team with access to this service, and a service can not be orphaned"
return &errors.HTTP{Code: http.StatusForbidden, Message: msg}
}
rec.Log(t.GetUserName(), "revoke-service-access", "service="+serviceName, "team="+teamName)
err = s.RevokeAccess(team)
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
return s.Update()
}
示例10: swap
func swap(w http.ResponseWriter, r *http.Request, t auth.Token) error {
u, err := t.User()
if err != nil {
return err
}
app1Name := r.URL.Query().Get("app1")
app2Name := r.URL.Query().Get("app2")
locked1, err := app.AcquireApplicationLock(app1Name, t.GetUserName(), "/swap")
if err != nil {
return err
}
defer app.ReleaseApplicationLock(app1Name)
locked2, err := app.AcquireApplicationLock(app2Name, t.GetUserName(), "/swap")
if err != nil {
return err
}
defer app.ReleaseApplicationLock(app2Name)
app1, err := getApp(app1Name, u)
if err != nil {
return err
}
if !locked1 {
return &errors.HTTP{Code: http.StatusConflict, Message: fmt.Sprintf("%s: %s", app1.Name, &app1.Lock)}
}
app2, err := getApp(app2Name, u)
if err != nil {
return err
}
if !locked2 {
return &errors.HTTP{Code: http.StatusConflict, Message: fmt.Sprintf("%s: %s", app2.Name, &app2.Lock)}
}
rec.Log(u.Email, "swap", app1Name, app2Name)
return app.Swap(&app1, &app2)
}
示例11: serviceInstanceInfo
func serviceInstanceInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error {
instanceName := r.URL.Query().Get(":instance")
serviceName := r.URL.Query().Get(":service")
serviceInstance, err := getServiceInstanceOrError(serviceName, instanceName)
if err != nil {
return err
}
permissionValue := serviceName + "/" + instanceName
allowed := permission.Check(t, permission.PermServiceInstanceRead,
append(permission.Contexts(permission.CtxTeam, serviceInstance.Teams),
permission.Context(permission.CtxServiceInstance, permissionValue),
)...,
)
if !allowed {
return permission.ErrUnauthorized
}
rec.Log(t.GetUserName(), "service-instance-info", serviceName, instanceName)
info, err := serviceInstance.Info()
if err != nil {
return err
}
sInfo := ServiceInstanceInfo{
Apps: serviceInstance.Apps,
Teams: serviceInstance.Teams,
TeamOwner: serviceInstance.TeamOwner,
Description: serviceInstance.Description,
CustomInfo: info,
}
b, err := json.Marshal(sInfo)
if err != nil {
return nil
}
w.Write(b)
return nil
}
示例12: deployRollback
// title: rollback
// path: /apps/{appname}/deploy/rollback
// method: POST
// consume: application/x-www-form-urlencoded
// produce: application/x-json-stream
// responses:
// 200: OK
// 400: Invalid data
// 403: Forbidden
// 404: Not found
func deployRollback(w http.ResponseWriter, r *http.Request, t auth.Token) error {
appName := r.URL.Query().Get(":appname")
instance, err := app.GetByName(appName)
if err != nil {
return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: fmt.Sprintf("App %s not found.", appName)}
}
image := r.FormValue("image")
if image == "" {
return &tsuruErrors.HTTP{
Code: http.StatusBadRequest,
Message: "you cannot rollback without an image name",
}
}
origin := r.FormValue("origin")
if origin != "" {
if !app.ValidateOrigin(origin) {
return &tsuruErrors.HTTP{
Code: http.StatusBadRequest,
Message: "Invalid deployment origin",
}
}
}
w.Header().Set("Content-Type", "application/x-json-stream")
keepAliveWriter := io.NewKeepAliveWriter(w, 30*time.Second, "")
defer keepAliveWriter.Stop()
writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
opts := app.DeployOptions{
App: instance,
OutputStream: writer,
Image: image,
User: t.GetUserName(),
Origin: origin,
Rollback: true,
}
opts.GetKind()
canRollback := permission.Check(t, permSchemeForDeploy(opts), contextsForApp(instance)...)
if !canRollback {
return &tsuruErrors.HTTP{Code: http.StatusForbidden, Message: permission.ErrUnauthorized.Error()}
}
var imageID string
evt, err := event.New(&event.Opts{
Target: appTarget(appName),
Kind: permission.PermAppDeploy,
Owner: t,
CustomData: opts,
Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(instance)...),
AllowedCancel: event.Allowed(permission.PermAppUpdateEvents, contextsForApp(instance)...),
Cancelable: true,
})
if err != nil {
return err
}
defer func() { evt.DoneCustomData(err, map[string]string{"image": imageID}) }()
opts.Event = evt
imageID, err = app.Deploy(opts)
if err != nil {
writer.Encode(io.SimpleJsonMessage{Error: err.Error()})
}
return nil
}
示例13: changePassword
func changePassword(w http.ResponseWriter, r *http.Request, t auth.Token) error {
managed, ok := app.AuthScheme.(auth.ManagedScheme)
if !ok {
return &errors.HTTP{Code: http.StatusBadRequest, Message: nonManagedSchemeMsg}
}
var body map[string]string
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: "Invalid JSON.",
}
}
if body["old"] == "" || body["new"] == "" {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: "Both the old and the new passwords are required.",
}
}
err = managed.ChangePassword(t, body["old"], body["new"])
if err != nil {
return handleAuthError(err)
}
rec.Log(t.GetUserName(), "change-password")
return nil
}
示例14: changePassword
func changePassword(w http.ResponseWriter, r *http.Request, t auth.Token) error {
managed, ok := app.AuthScheme.(auth.ManagedScheme)
if !ok {
return &errors.HTTP{Code: http.StatusBadRequest, Message: nonManagedSchemeMsg}
}
oldPassword := r.FormValue("old")
newPassword := r.FormValue("new")
confirmPassword := r.FormValue("confirm")
if oldPassword == "" || newPassword == "" {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: "Both the old and the new passwords are required.",
}
}
if newPassword != confirmPassword {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: "New password and password confirmation didn't match.",
}
}
err := managed.ChangePassword(t, oldPassword, newPassword)
if err != nil {
return handleAuthError(err)
}
rec.Log(t.GetUserName(), "change-password")
return nil
}
示例15: eventCancel
// title: event cancel
// path: /events/{uuid}/cancel
// method: POST
// produce: application/json
// responses:
// 200: OK
// 400: Invalid uuid or empty reason
// 404: Not found
func eventCancel(w http.ResponseWriter, r *http.Request, t auth.Token) error {
uuid := r.URL.Query().Get(":uuid")
if !bson.IsObjectIdHex(uuid) {
msg := fmt.Sprintf("uuid parameter is not ObjectId: %s", uuid)
return &errors.HTTP{Code: http.StatusBadRequest, Message: msg}
}
objID := bson.ObjectIdHex(uuid)
e, err := event.GetByID(objID)
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
reason := r.FormValue("reason")
if reason == "" {
return &errors.HTTP{Code: http.StatusBadRequest, Message: "reason is mandatory"}
}
scheme, err := permission.SafeGet(e.AllowedCancel.Scheme)
if err != nil {
return err
}
allowed := permission.Check(t, scheme, e.AllowedCancel.Contexts...)
if !allowed {
return permission.ErrUnauthorized
}
err = e.TryCancel(reason, t.GetUserName())
if err != nil {
if err == event.ErrNotCancelable {
return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
}
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}