// UserHasAuthorizedScopes checks if all labels from an authorization scope mapping are still present on the user
327765
func UserHasAuthorizedScopes(r *http.Request, authorization *user.Authorization) (bool, error) {
	log.Debug("Checking if user still has all mapped scopes")
	user, err := user.NewManager(r).GetByName(authorization.Username)
	if err != nil {
		return false, err
	}

	found := false
	if authorization.Addresses != nil {
		for _, am := range authorization.Addresses {
			for _, a := range user.Addresses {
				if am.RealLabel == a.Label {
					found = true
					break
				}
			}
			if !found {
				log.Debug("Authorized real label not found for address")
				return false, nil
			}
		}
	}

	found = false
	if authorization.BankAccounts != nil {
		for _, ba := range authorization.BankAccounts {
			for _, b := range user.BankAccounts {
				if ba.RealLabel == b.Label {
					found = true
					break
				}
			}
			if !found {
				log.Debug("Authorized real label not found for bank account")
				return false, nil
			}
		}
	}

	found = false
	if authorization.DigitalWallet != nil {
		for _, dw := range authorization.DigitalWallet {
			for _, d := range user.DigitalWallet {
				if dw.RealLabel == d.Label {
					found = true
					break
				}
			}
			if !found {
				log.Debug("Authorized real label not found for digital wallet")
				return false, nil
			}
		}
	}

	found = false
	if authorization.EmailAddresses != nil {
		for _, ea := range authorization.EmailAddresses {
			for _, e := range user.EmailAddresses {
				if ea.RealLabel == e.Label {
					found = true
					break
				}
			}
			if !found {
				log.Debug("Authorized real label not found for email address")
				return false, nil
			}
		}
	}

	found = false
	if authorization.Phonenumbers != nil {
		for _, ep := range authorization.Phonenumbers {
			for _, p := range user.Phonenumbers {
				if ep.RealLabel == p.Label {
					found = true
					break
				}
			}
			if !found {
				log.Debug("Authorized real label not found for phone number")
				return false, nil
			}
		}
	}

	found = false
	if authorization.PublicKeys != nil {
		for _, pk := range authorization.PublicKeys {
			for _, p := range user.PublicKeys {
				if pk.RealLabel == p.Label {
					found = true
					break
				}
			}
			if !found {
				log.Debug("Authorized real label not found for public key")
				return false, nil
			}
		}
	}

	found = false
	valMgr := validation.NewManager(r)
	if authorization.ValidatedEmailAddresses != nil {
		for _, vea := range authorization.ValidatedEmailAddresses {
			for _, e := range user.EmailAddresses {
				if vea.RealLabel == e.Label {
					// Check that the email address is actually validated by the user in the authorization
					validatedEmail, err := valMgr.GetByEmailAddressValidatedEmailAddress(e.EmailAddress)
					if err != nil && !db.IsNotFound(err) {
						return false, err
					}
					if db.IsNotFound(err) {
						return false, nil
					}
					if validatedEmail.Username == authorization.Username {
						found = true
						break
					}
				}
			}
			if !found {
				log.Debug("Validated email address in authorization does not belong to the user")
				return false, nil
			}
		}
	}

	found = false
	if authorization.ValidatedPhonenumbers != nil {
		for _, vpn := range authorization.ValidatedPhonenumbers {
			for _, p := range user.Phonenumbers {
				if vpn.RealLabel == p.Label {
					// Check that the phone is actually validated by the user in the authorization
					validatedPhone, err := valMgr.GetByPhoneNumber(p.Phonenumber)
					if err != nil && !db.IsNotFound(err) {
						return false, err
					}
					if db.IsNotFound(err) {
						return false, nil
					}
					if validatedPhone.Username == authorization.Username {
						found = true
						break
					}
				}
			}
			if !found {
				log.Debug("Validated phone number in authorization does not belong to the user")
				return false, nil
			}
		}
	}
	return true, nil
}
574499
func hasAuthorization(r *http.Request, username string, globalid string) (bool, error) {
	userMgr := user.NewManager(r)

	authorization, err := userMgr.GetAuthorization(username, globalid)
	if err != nil && !db.IsNotFound(err) {
		return false, err
	}
	if authorization == nil || db.IsNotFound(err) {
		return false, nil
	}
	return true, nil
}
1317570
func NewUserAuthorizer(username string, identity services.UserGetter, access services.Access) (Authorizer, error) {
	authContext, err := contextForLocalUser(username, identity, access)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &contextAuthorizer{authContext: *authContext}, nil
}
4537
func (api UsersAPI) UpdateAuthorization(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	grantedTo := mux.Vars(r)["grantedTo"]

	authorization := &user.Authorization{}

	if err := json.NewDecoder(r.Body).Decode(authorization); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	userMgr := user.NewManager(r)
	userobj, err := userMgr.GetByName(username)
	if handleServerError(w, "getting user by name", err) {
		return
	}
	verifiedEmails := []user.EmailAddress{}
	if len(authorization.OwnerOf.EmailAddresses) != 0 || len(authorization.ValidatedEmailAddresses) > 0 {
		verifiedEmails, err = api.getValidatedEmails(r, *userobj)
		if handleServerError(w, "getting verified emails", err) {
			return
		}
	}

	verifiedPhones := []user.Phonenumber{}
	if len(authorization.ValidatedPhonenumbers) > 0 {
		verifiedPhones, err = api.getValidatedPhones(r, *userobj)
		if handleServerError(w, "getting verified phone numbers", err) {
			return
		}
	}

	authorization.Username = username
	authorization.GrantedTo = grantedTo
	authorization.Addresses = FilterAuthorizationMaps(authorization.Addresses)
	authorization.EmailAddresses = FilterAuthorizationMaps(authorization.EmailAddresses)
	authorization.ValidatedEmailAddresses = FilterValidatedEmails(FilterAuthorizationMaps(authorization.ValidatedEmailAddresses), verifiedEmails)
	authorization.Phonenumbers = FilterAuthorizationMaps(authorization.Phonenumbers)
	authorization.ValidatedPhonenumbers = FilterValidatedPhones(FilterAuthorizationMaps(authorization.ValidatedPhonenumbers), verifiedPhones)
	authorization.BankAccounts = FilterAuthorizationMaps(authorization.BankAccounts)
	authorization.PublicKeys = FilterAuthorizationMaps(authorization.PublicKeys)
	authorization.DigitalWallet = FilterDigitalWallet(authorization.DigitalWallet)
	authorization.OwnerOf = FilterOwnerOf(authorization.OwnerOf, verifiedEmails)
	authorization.Avatars = FilterAuthorizationMaps(authorization.Avatars)

	existingAuth, err := userMgr.GetAuthorization(username, grantedTo)
	if handleServerError(w, "getting existing authorization", err) {
		return
	}
	if existingAuth != nil {
		// Merge authorizations
		authorization.Merge(existingAuth)
	}

	err = userMgr.UpdateAuthorization(authorization)
	if handleServerError(w, "updating authorization", err) {
		return
	}
	w.Header().Set("Content-type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(authorization)
}
967468
func (s *Route) SetAuthorizationScopes(v []*string) *Route {
	s.AuthorizationScopes = v
	return s
}
479090
func verifyScopes(scopeString string, username string, clientID string, orgMgr *organization.Manager) (string, error) {
	scopes := strings.Split(scopeString, ",")
	for i, scope := range scopes {
		// If the scope is memberof:clientid, where clientid is the globalid of the
		// organization requesting authorization, verify if we really have this scope
		// or if we have the scope on one or more children. In case of the latter, replace
		// the scopes by the appropriate ones
		if scope == "user:memberof:"+clientID {
			inOrg, err := orgMgr.IsInOrgs(username, clientID)
			if err != nil {
				return scopeString, err
			}
			// Should only have 1 result, and result MUST be clientID
			if len(inOrg) == 1 && inOrg[0] == clientID {
				return scopeString, nil
			}

			log.Debugf("Access token contains scope %v, but user is not a member of %v - parse suborganizations",
				scope, clientID)
			// Remove the memberof:parentOrg scope
			scopes = append(scopes[:i], scopes[i+1:]...)
			var subOrgScopes []string
			subOrgScopes, err = findSuborgScopes(clientID, username, orgMgr)
			if err != nil {
				return scope, err
			}
			// Add the correct memberof scopes
			scopes = append(scopes, subOrgScopes...)
			scopeString = strings.Join(scopes, ",")
		}
	}
	return scopeString, nil
}
600002
func asUserHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) {
	cfg := getConfig(c)
	if cfg == nil || cfg.AccessTokenProvider == nil {
		return nil, nil, ErrNotConfigured
	}

	delegationToken := ""
	if opts.delegationToken != "" {
		delegationToken = opts.delegationToken // WithDelegationToken was used
	} else {
		// Outbound RPC calls in the context of a request from anonymous caller are
		// anonymous too. No need to use any authentication headers.
		userIdent := CurrentIdentity(c)
		if userIdent == identity.AnonymousIdentity {
			return nil, nil, nil
		}

		// Grab root URL of the destination service. Only https:// are allowed.
		uri = strings.ToLower(uri)
		if !strings.HasPrefix(uri, "https://") {
			return nil, nil, fmt.Errorf("auth: refusing to use delegation tokens with non-https URL")
		}
		host := uri[len("https://"):]
		if idx := strings.IndexRune(host, '/'); idx != -1 {
			host = host[:idx]
		}

		// Grab a token that's good enough for at least 10 min. Outbound RPCs
		// shouldn't last longer than that.
		mintTokenCall := MintDelegationToken
		if opts.rpcMocks != nil && opts.rpcMocks.MintDelegationToken != nil {
			mintTokenCall = opts.rpcMocks.MintDelegationToken
		}
		tok, err := mintTokenCall(c, DelegationTokenParams{
			TargetHost: host,
			Tags:       opts.delegationTags,
			MinTTL:     10 * time.Minute,
		})
		if err != nil {
			return nil, nil, err
		}
		delegationToken = tok.Token
	}

	// Use our own OAuth token too, since the delegation token is bound to us.
	oauthTok, err := cfg.AccessTokenProvider(c, []string{auth.OAuthScopeEmail})
	if err != nil {
		return nil, nil, err
	}

	logging.Fields{
		"fingerprint": tokenFingerprint(delegationToken),
	}.Debugf(c, "auth: Sending delegation token")
	return oauthTok, map[string]string{delegation.HTTPHeaderName: delegationToken}, nil
}
576079
func (app *App) apiHostForScope(scope Scope) (string, error) {
	if scope == ScopePublic {
		return app.Config.PublicAPIHost, nil
	} else if scope == ScopeProtected {
		return app.Config.ProtectedAPIHost, nil
	} else {
		return "", fmt.Errorf("unknown scope value: %v", scope)
	}
}
766176
func (st *State) isUserSuperuser(user names.UserTag) (bool, error) {
	access, err := st.UserAccess(user, st.controllerTag)
	if err != nil {
		// TODO(jam): 2017-11-27 We weren't suppressing NotFound here so that we would know when someone asked for
		// the list of models of a user that doesn't exist.
		// However, now we will not even check if its a known user if they aren't asking for all=true.
		return false, errors.Trace(err)
	}
	isControllerSuperuser := (access.Access == permission.SuperuserAccess)
	return isControllerSuperuser, nil
}
1331264
func (st *State) userPermission(objectGlobalKey, subjectGlobalKey string) (*userPermission, error) {
	result := &userPermission{}
	permissions, closer := st.db().GetCollection(permissionsC)
	defer closer()

	id := permissionID(objectGlobalKey, subjectGlobalKey)
	err := permissions.FindId(id).One(&result.doc)
	if err == mgo.ErrNotFound {
		return nil, errors.NotFoundf("user permission for %q on %q", subjectGlobalKey, objectGlobalKey)
	}
	return result, nil
}
959166
func (r *apiHandler) UserHasPermission(user names.UserTag, operation permission.Access, target names.Tag) (bool, error) {
	return common.HasPermission(r.state.UserPermission, user, operation, target)
}
541152
func (a *Account) RemoveAuthorizedClient(name string) error {
	return a.del(a.auth, fmt.Sprintf("/api/v2/users/me/authorized-clients/%s", name))
}
567834
func (c *ResourceRolesController) HasScope(ctx *app.HasScopeResourceRolesContext) error {
	// retrieve the current user's identity from the request token
	currentIdentity, err := manager.ContextIdentity(ctx)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_id": ctx.ResourceID,
		}, "error getting identity information from token")
		return jsonapi.JSONErrorResponse(ctx, errors.NewUnauthorizedError(err.Error()))
	}
	// check that the resource exists
	if err := c.app.ResourceService().CheckExists(ctx, ctx.ResourceID); err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	//
	r, err := c.app.PermissionService().HasScope(ctx, *currentIdentity, ctx.ResourceID, ctx.ScopeName)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_id": ctx.ResourceID,
			"scope_name":  ctx.ScopeName,
			"err":         err,
		}, "error checking if the user has the given scope in the requested resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	return ctx.OK(&app.IdentityResourceScope{
		Data: &app.IdentityResourceScopeData{
			ScopeName: ctx.ScopeName,
			HasScope:  r,
		},
	})
}
422833
func (m *Middleware) IsAuthorized(r *http.Request) bool {
	return m.GetAuthorizationToken(r) != nil
}
848369
func (st *State) usersPermissions(objectGlobalKey string) ([]*userPermission, error) {
	permissions, closer := st.db().GetCollection(permissionsC)
	defer closer()

	var matchingPermissions []permissionDoc
	findExpr := fmt.Sprintf("^%s#.*$", objectGlobalKey)
	if err := permissions.Find(
		bson.D{{"_id", bson.D{{"$regex", findExpr}}}},
	).All(&matchingPermissions); err != nil {
		return nil, err
	}
	var result []*userPermission
	for _, pDoc := range matchingPermissions {
		result = append(result, &userPermission{doc: pDoc})
	}
	return result, nil
}
574474
func (s *UserPoolClientType) SetAllowedOAuthScopes(v []*string) *UserPoolClientType {
	s.AllowedOAuthScopes = v
	return s
}
708542
func (mr *MockAuthorizeRequesterMockRecorder) GetRequestedScopes() *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestedScopes", reflect.TypeOf((*MockAuthorizeRequester)(nil).GetRequestedScopes))
}