// NewAuthorizationHandler returns a new instance of AuthorizationHandler.
558053
func NewAuthorizationHandler(userService platform.UserService) *AuthorizationHandler {
	h := &AuthorizationHandler{
		Router:      NewRouter(),
		Logger:      zap.NewNop(),
		UserService: userService,
	}

	h.HandlerFunc("POST", "/api/v2/authorizations", h.handlePostAuthorization)
	h.HandlerFunc("GET", "/api/v2/authorizations", h.handleGetAuthorizations)
	h.HandlerFunc("GET", "/api/v2/authorizations/:id", h.handleGetAuthorization)
	h.HandlerFunc("PATCH", "/api/v2/authorizations/:id", h.handleSetAuthorizationStatus)
	h.HandlerFunc("DELETE", "/api/v2/authorizations/:id", h.handleDeleteAuthorization)
	return h
}
37966
func (s *HttpDataSourceConfig) SetAuthorizationConfig(v *AuthorizationConfig) *HttpDataSourceConfig {
	s.AuthorizationConfig = v
	return s
}
1071246
func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) {
	authReq, err := s.parseAuthorizationRequest(r)
	if err != nil {
		s.logger.Errorf("Failed to parse authorization request: %v", err)
		if handler, ok := err.Handle(); ok {
			// client_id and redirect_uri checked out and we can redirect back to
			// the client with the error.
			handler.ServeHTTP(w, r)
			return
		}

		// Otherwise render the error to the user.
		//
		// TODO(ericchiang): Should we just always render the error?
		s.renderError(w, err.Status(), err.Error())
		return
	}

	// TODO(ericchiang): Create this authorization request later in the login flow
	// so users don't hit "not found" database errors if they wait at the login
	// screen too long.
	//
	// See: https://github.com/dexidp/dex/issues/646
	authReq.Expiry = s.now().Add(s.authRequestsValidFor)
	if err := s.storage.CreateAuthRequest(authReq); err != nil {
		s.logger.Errorf("Failed to create authorization request: %v", err)
		s.renderError(w, http.StatusInternalServerError, "Failed to connect to the database.")
		return
	}

	connectors, e := s.storage.ListConnectors()
	if e != nil {
		s.logger.Errorf("Failed to get list of connectors: %v", err)
		s.renderError(w, http.StatusInternalServerError, "Failed to retrieve connector list.")
		return
	}

	if len(connectors) == 1 {
		for _, c := range connectors {
			// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter
			// on create the auth request.
			http.Redirect(w, r, s.absPath("/auth", c.ID)+"?req="+authReq.ID, http.StatusFound)
			return
		}
	}

	connectorInfos := make([]connectorInfo, len(connectors))
	i := 0
	for _, conn := range connectors {
		connectorInfos[i] = connectorInfo{
			ID:   conn.ID,
			Name: conn.Name,
			// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter
			// on create the auth request.
			URL: s.absPath("/auth", conn.ID) + "?req=" + authReq.ID,
		}
		i++
	}

	if err := s.templates.login(w, connectorInfos); err != nil {
		s.logger.Errorf("Server template error: %v", err)
	}
}
426902
func (ssa *SQLStorageAuthority) NewPendingAuthorization(ctx context.Context, authz core.Authorization) (core.Authorization, error) {
	var output core.Authorization

	tx, err := ssa.dbMap.Begin()
	if err != nil {
		return output, err
	}
	txWithCtx := tx.WithContext(ctx)

	// Create a random ID and check that it doesn't exist already
	authz.ID = core.NewToken()
	for existingPending(txWithCtx, authz.ID) ||
		existingFinal(txWithCtx, authz.ID) {
		authz.ID = core.NewToken()
	}

	// Insert a stub row in pending
	pendingAuthz := pendingauthzModel{Authorization: authz}
	err = txWithCtx.Insert(&pendingAuthz)
	if err != nil {
		err = Rollback(tx, err)
		return output, err
	}

	for i, c := range authz.Challenges {
		challModel, err := challengeToModel(&c, pendingAuthz.ID)
		if err != nil {
			err = Rollback(tx, err)
			return output, err
		}
		// Magic happens here: Gorp will modify challModel, setting challModel.ID
		// to the auto-increment primary key. This is important because we want
		// the challenge objects inside the Authorization we return to know their
		// IDs, so they can have proper URLs.
		// See https://godoc.org/github.com/coopernurse/gorp#DbMap.Insert
		err = txWithCtx.Insert(challModel)
		if err != nil {
			err = Rollback(tx, err)
			return output, err
		}
		challenge, err := modelToChallenge(challModel)
		if err != nil {
			err = Rollback(tx, err)
			return output, err
		}
		authz.Challenges[i] = challenge
	}

	err = tx.Commit()
	output = pendingAuthz.Authorization
	output.Challenges = authz.Challenges
	return output, err
}
331985
func (s *CreateRouteInput) SetAuthorizationType(v string) *CreateRouteInput {
	s.AuthorizationType = &v
	return s
}
770592
func WithAuthorization(handler http.Handler, a authorizer.Authorizer, s runtime.NegotiatedSerializer) http.Handler {
	if a == nil {
		klog.Warningf("Authorization is disabled")
		return handler
	}
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := req.Context()
		ae := request.AuditEventFrom(ctx)

		attributes, err := GetAuthorizerAttributes(ctx)
		if err != nil {
			responsewriters.InternalError(w, req, err)
			return
		}
		authorized, reason, err := a.Authorize(attributes)
		// an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here.
		if authorized == authorizer.DecisionAllow {
			audit.LogAnnotation(ae, decisionAnnotationKey, decisionAllow)
			audit.LogAnnotation(ae, reasonAnnotationKey, reason)
			handler.ServeHTTP(w, req)
			return
		}
		if err != nil {
			audit.LogAnnotation(ae, reasonAnnotationKey, reasonError)
			responsewriters.InternalError(w, req, err)
			return
		}

		klog.V(4).Infof("Forbidden: %#v, Reason: %q", req.RequestURI, reason)
		audit.LogAnnotation(ae, decisionAnnotationKey, decisionForbid)
		audit.LogAnnotation(ae, reasonAnnotationKey, reason)
		responsewriters.Forbidden(ctx, attributes, w, req, reason, s)
	})
}
1265699
func (sa *StorageAuthority) NewAuthorizations2(ctx context.Context, req *sapb.AddPendingAuthorizationsRequest) (*sapb.Authorization2IDs, error) {
	return &sapb.Authorization2IDs{}, nil
}
93060
func (wfe *WebFrontEndImpl) NewAuthorization(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
	body, _, currReg, prob := wfe.verifyPOST(ctx, logEvent, request, true, core.ResourceNewAuthz)
	addRequesterHeader(response, logEvent.Requester)
	if prob != nil {
		// verifyPOST handles its own setting of logEvent.Errors
		wfe.sendError(response, logEvent, prob, nil)
		return
	}
	// Any version of the agreement is acceptable here. Version match is enforced in
	// wfe.Registration when agreeing the first time. Agreement updates happen
	// by mailing subscribers and don't require a registration update.
	if currReg.Agreement == "" {
		wfe.sendError(response, logEvent, probs.Unauthorized("Must agree to subscriber agreement before any further actions"), nil)
		return
	}

	var init core.Authorization
	if err := json.Unmarshal(body, &init); err != nil {
		wfe.sendError(response, logEvent, probs.Malformed("Error unmarshaling JSON"), err)
		return
	}
	if init.Identifier.Type == core.IdentifierDNS {
		logEvent.DNSName = init.Identifier.Value
	}

	// Create new authz and return
	authz, err := wfe.RA.NewAuthorization(ctx, init, currReg.ID)
	if err != nil {
		wfe.sendError(response, logEvent, web.ProblemDetailsForError(err, "Error creating new authz"), err)
		return
	}
	logEvent.Created = authz.ID

	// Make a URL for this authz, then blow away the ID and RegID before serializing
	authzURL := web.RelativeEndpoint(request, authzPath+string(authz.ID))
	wfe.prepAuthorizationForDisplay(request, &authz)

	response.Header().Add("Location", authzURL)
	response.Header().Add("Link", link(web.RelativeEndpoint(request, newCertPath), "next"))

	err = wfe.writeJsonResponse(response, logEvent, http.StatusCreated, authz)
	if err != nil {
		// ServerInternal because we generated the authz, it should be OK
		wfe.sendError(response, logEvent, probs.ServerInternal("Error marshaling authz"), err)
		return
	}
}
284910
func BasicAuthHandler(w http.ResponseWriter, r *http.Request) {
	basicAuthHandler(w, r, http.StatusUnauthorized)
}
826226
func NewBasicAuthorization(username, password string) BasicAuthorization {
	return BasicAuthorization{
		username: username,
		password: password,
	}
}
496835
func (s *Method) SetAuthorizationType(v string) *Method {
	s.AuthorizationType = &v
	return s
}
1129498
func NewHandler(n *centrifuge.Node, c Config) *Handler {
	return &Handler{
		node:   n,
		config: c,
		api:    newAPIExecutor(n, "http"),
	}
}
69353
func NewAuthorizedConfig(token string, secret string) *UserConfig {
	return &UserConfig{AccessTokenKey: token, AccessTokenSecret: secret}
}
202346
func NewAuthenticationHandler() *AuthenticationHandler {
	return &AuthenticationHandler{
		Logger:       zap.NewNop(),
		Handler:      http.DefaultServeMux,
		noAuthRouter: httprouter.New(),
	}
}
711267
func (s *CreateRouteOutput) SetAuthorizationType(v string) *CreateRouteOutput {
	s.AuthorizationType = &v
	return s
}
1163012
func NewMockAuthorizeRequester(ctrl *gomock.Controller) *MockAuthorizeRequester {
	mock := &MockAuthorizeRequester{ctrl: ctrl}
	mock.recorder = &MockAuthorizeRequesterMockRecorder{mock}
	return mock
}
450991
func (s *Service) CreateAuthorization(ctx context.Context, a *platform.Authorization) error {
	op := OpPrefix + platform.OpCreateAuthorization

	_, pErr := s.FindUserByID(ctx, a.UserID)
	if pErr != nil {
		return platform.ErrUnableToCreateToken
	}

	_, pErr = s.FindOrganizationByID(ctx, a.OrgID)
	if pErr != nil {
		return platform.ErrUnableToCreateToken
	}

	var err error
	a.Token, err = s.TokenGenerator.Token()
	if err != nil {
		return &platform.Error{
			Err: err,
			Op:  op,
		}
	}

	a.ID = s.IDGenerator.ID()
	a.Status = platform.Active

	return s.PutAuthorization(ctx, a)
}