// Authorizer gets the authorizer from a username and a password.
974109
func (ups UsernamePasswordConfig) Authorizer() (autorest.Authorizer, error) {
	spToken, err := ups.ServicePrincipalToken()
	if err != nil {
		return nil, fmt.Errorf("failed to get oauth token from username and password auth: %v", err)
	}
	return autorest.NewBearerAuthorizer(spToken), nil
}
160061
func NewAuthorizeAuthenticator(request authenticator.Request, handler AuthenticationHandler, errorHandler AuthenticationErrorHandler) osinserver.AuthorizeHandler {
	return &authorizeAuthenticator{request: request, handler: handler, errorHandler: errorHandler}
}
335131
func (settings FileSettings) ClientCredentialsAuthorizerWithResource(resource string) (autorest.Authorizer, error) {
	spToken, err := settings.ServicePrincipalTokenFromClientCredentialsWithResource(resource)
	if err != nil {
		return nil, err
	}
	return autorest.NewBearerAuthorizer(spToken), nil
}
19810
func (settings FileSettings) ClientCredentialsAuthorizer(baseURI string) (autorest.Authorizer, error) {
	resource, err := settings.getResourceForToken(baseURI)
	if err != nil {
		return nil, err
	}
	return settings.ClientCredentialsAuthorizerWithResource(resource)
}
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
}
791948
func (a *awsNodeAuthorizer) Authorize(ctx context.Context, r *server.NodeRegistration) error {
	identity := &ec2metadata.EC2InstanceIdentityDocument{}

	// @step: decode the request
	request, err := decodeRequest(r.Spec.Request)
	if err != nil {
		return err
	}

	// @step: extract and validate the document
	if reason, err := func() (string, error) {
		if a.config.UseFeature(CheckSignature) {
			if reason, err := a.validateIdentityDocument(ctx, request.Document, identity); err != nil {
				return "", err
			} else if reason != "" {
				return reason, nil
			}
		}

		if reason, err := a.validateNodeInstance(ctx, identity, r); err != nil {
			return "", err
		} else if reason != "" {
			return reason, nil
		}

		r.Status.Allowed = true

		return "", nil
	}(); err != nil {
		return err
	} else if reason != "" {
		r.Deny(reason)
	}

	return nil
}
1061829
func (m *Manager) GetAuthorization(username, organization string) (authorization *Authorization, err error) {
	err = m.getAuthorizationCollection().Find(bson.M{"username": username, "grantedto": organization}).One(&authorization)
	if err == mgo.ErrNotFound {
		err = nil
	} else if err != nil {
		authorization = nil
	}
	return
}
109076
func (a Authorizer) AuthorizeRole(rw http.ResponseWriter, req *http.Request, role string, redirectWithMessage bool) error {
	r, ok := a.roles[role]
	if !ok {
		return mkerror("role not found")
	}
	if err := a.Authorize(rw, req, redirectWithMessage); err != nil {
		return mkerror(err.Error())
	}
	authSession, _ := a.cookiejar.Get(req, "auth") // should I check err? I've already checked in call to Authorize
	username := authSession.Values["username"]
	if user, err := a.backend.User(username.(string)); err == nil {
		if a.roles[user.Role] >= r {
			return nil
		}
		a.addMessage(rw, req, "You don't have sufficient privileges.")
		return mkerror("user doesn't have high enough role")
	}
	return mkerror("user not found")
}
1178338
func NewRoleAuthorizer(clusterName string, clusterConfig services.ClusterConfig, r teleport.Role) (Authorizer, error) {
	authContext, err := contextForBuiltinRole(clusterName, clusterConfig, r, fmt.Sprintf("%v", r))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &contextAuthorizer{authContext: *authContext}, nil
}
109687
func (c *Client) AuthorizeRedirect(scope, state string) string {
	// add required parameters
	params := make(url.Values)
	params.Add("response_type", ResponseTypeCode)
	//params.Set("redirect_uri", c.RedirectURL)
	params.Set("client_id", c.ClientId)

	// add optional redirect param
	// NOTE: this is optional for some providers, but not for others
	if len(c.RedirectURL) > 0 {
		params.Set("redirect_uri", c.RedirectURL)
	}

	// add optional scope param
	if len(scope) > 0 {
		params.Set("scope", scope)
	}

	// add optional state param
	if len(state) > 0 {
		params.Set("state", state)
	}

	// HACK: for google we must add access_type=offline in order
	//       to obtain a refresh token
	if strings.HasPrefix(c.AuthorizationURL, "https://accounts.google.com") {
		params.Set("access_type", "offline")
		//params.Set("approval_prompt","force")
	}

	// generate the URL
	endpoint, _ := url.Parse(c.AuthorizationURL)
	endpoint.RawQuery = params.Encode()

	//HACK: Google separates scopes using a "+", however, these get
	//      encoded and for some reason cause Google to fail the request.
	//      So we will decode all plus signs to make the Google happy
	endpoint.RawQuery = strings.Replace(endpoint.RawQuery, "%2B", "+", -1)
	return endpoint.String()
}
535753
func (mc MSIConfig) Authorizer() (autorest.Authorizer, error) {
	msiEndpoint, err := adal.GetMSIVMEndpoint()
	if err != nil {
		return nil, err
	}

	var spToken *adal.ServicePrincipalToken
	if mc.ClientID == "" {
		spToken, err = adal.NewServicePrincipalTokenFromMSI(msiEndpoint, mc.Resource)
		if err != nil {
			return nil, fmt.Errorf("failed to get oauth token from MSI: %v", err)
		}
	} else {
		spToken, err = adal.NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, mc.Resource, mc.ClientID)
		if err != nil {
			return nil, fmt.Errorf("failed to get oauth token from MSI for user assigned identity: %v", err)
		}
	}

	return autorest.NewBearerAuthorizer(spToken), nil
}
1060527
func GetToken(ctx context.Context) (string, error) {
	a, ok := ctx.Value(authorizerCtxKey).(platform.Authorizer)
	if !ok {
		return "", &platform.Error{
			Msg:  "authorizer not found on context",
			Code: platform.EInternal,
		}
	}

	auth, ok := a.(*platform.Authorization)
	if !ok {
		return "", &platform.Error{
			Msg:  fmt.Sprintf("authorizer not an authorization but a %T", a),
			Code: platform.EInternal,
		}
	}

	return auth.Token, nil
}
879856
func Auth(authorizer Authorizer, next http.Handler) http.HandlerFunc {
	// Heavily inspired by:
	// https://github.com/syncthing/syncthing/blob/161326c5489d000972a6846564f0ce12779bd8f2/cmd/syncthing/gui_auth.go
	return func(w http.ResponseWriter, r *http.Request) {
		cookie, err := r.Cookie(authCookieName)
		if err == nil && cookie != nil {
			// FIXME use RWMutex
			sessionsMut.Lock()
			_, ok := sessions[cookie.Value]
			sessionsMut.Unlock()
			if ok {
				next.ServeHTTP(w, r)
				return
			}
		}
		error := func() {
			// Mitigate risk of timing attacks.
			// https://en.wikipedia.org/wiki/Timing_attack
			// FIXME use crypto/rand
			time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
			w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		}
		username, passwd, ok := r.BasicAuth()
		if !ok {
			error()
			return
		}
		if !authorizer.Verify(username, passwd) {
			error()
			return
		}
		sessionid := randomString(32)
		sessionsMut.Lock()
		sessions[sessionid] = struct{}{}
		sessionsMut.Unlock()
		http.SetCookie(w, &http.Cookie{
			Name:   authCookieName,
			Value:  sessionid,
			MaxAge: 0,
		})
		next.ServeHTTP(w, r)
	}
}
1140811
func (dfc DeviceFlowConfig) Authorizer() (autorest.Authorizer, error) {
	spToken, err := dfc.ServicePrincipalToken()
	if err != nil {
		return nil, fmt.Errorf("failed to get oauth token from device flow: %v", err)
	}
	return autorest.NewBearerAuthorizer(spToken), nil
}
1188285
func (p Protos) AuthUser(username string, password string) (auth.UserInfo, error) {
	userInfo := auth.UserInfo{}
	url := p.createURL("user/auth")
	login := struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}{
		Username: username,
		Password: password,
	}
	loginJSON, err := json.Marshal(login)
	if err != nil {
		return userInfo, err
	}

	req, err := http.NewRequest("GET", url, bytes.NewBuffer(loginJSON))
	if err != nil {
		return userInfo, err
	}
	req.Header.Set("Content-Type", "application/json")

	res, err := p.makeRequest(req)
	if err != nil {
		return userInfo, err
	}

	err = json.Unmarshal(res, &userInfo)
	if err != nil {
		return userInfo, err
	}
	return userInfo, nil
}
822810
func (a controllerAdminAuthorizer) Authorize(authInfo httpcontext.AuthInfo) error {
	userTag, ok := authInfo.Entity.Tag().(names.UserTag)
	if !ok {
		return errors.Errorf("%s is not a user", names.ReadableString(authInfo.Entity.Tag()))
	}
	admin, err := a.st.IsControllerAdmin(userTag)
	if err != nil {
		return errors.Trace(err)
	}
	if !admin {
		return errors.Errorf("%s is not a controller admin", names.ReadableString(authInfo.Entity.Tag()))
	}
	return nil
}
1345449
func NewAuthorizer(graph *Graph, identifier nodeidentifier.NodeIdentifier, rules []rbacv1.PolicyRule) authorizer.Authorizer {
	return &NodeAuthorizer{
		graph:      graph,
		identifier: identifier,
		nodeRules:  rules,
		features:   utilfeature.DefaultFeatureGate,
	}
}