// handlePostAuthorization is the HTTP handler for the POST /api/v2/authorizations route.
178481
func (h *AuthorizationHandler) handlePostAuthorization(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodePostAuthorizationRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	user, err := getAuthorizedUser(r, h.UserService)
	if err != nil {
		EncodeError(ctx, platform.ErrUnableToCreateToken, w)
		return
	}

	auth := req.toPlatform(user.ID)

	org, err := h.OrganizationService.FindOrganizationByID(ctx, auth.OrgID)
	if err != nil {
		EncodeError(ctx, platform.ErrUnableToCreateToken, w)
		return
	}

	if err := h.AuthorizationService.CreateAuthorization(ctx, auth); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	perms, err := newPermissionsResponse(ctx, auth.Permissions, h.LookupService)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusCreated, newAuthResponse(auth, org, user, perms)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
654722
func (s *AuthorizationService) CreateAuthorization(ctx context.Context, authorization *platform.Authorization) error {
	return s.CreateAuthorizationFn(ctx, authorization)
}
487498
func (h *SourceHandler) handlePostSource(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodePostSourceRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := h.SourceService.CreateSource(ctx, req.Source); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	res := newSourceResponse(req.Source)

	if err := encodeResponse(ctx, w, http.StatusCreated, res); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
618279
func (sa *StorageAuthority) GetAuthorizations(ctx context.Context, req *sapb.GetAuthorizationsRequest) (*sapb.Authorizations, error) {
	return &sapb.Authorizations{}, nil
}
541190
func (h *DocumentHandler) handlePostDocument(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodePostDocumentRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}
	s, err := h.DocumentService.FindDocumentStore(ctx, req.Namespace)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	a, err := pcontext.GetAuthorizer(ctx)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	opts := []influxdb.DocumentOptions{}
	if req.OrgID.Valid() {
		opts = append(opts, influxdb.AuthorizedWithOrgID(a, req.OrgID))
	} else {
		opts = append(opts, influxdb.AuthorizedWithOrg(a, req.Org))
	}
	for _, label := range req.Labels {
		// TODO(desa): make these AuthorizedWithLabel eventually
		opts = append(opts, influxdb.WithLabel(label))
	}

	if err := s.CreateDocument(ctx, req.Document, opts...); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusCreated, newDocumentResponse(req.Namespace, req.Document)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
674101
func (a *Core) GetKeyAuthorization(token string) (string, error) {
	return a.jws.GetKeyAuthorization(token)
}
270537
func PostLock() echo.HandlerFunc {

	// swagger:route GET /me/posts/{pid}/locks me post locks GetMePostLock
	//
	// List the locks of the post
	//
	//
	//	Produces:
	//	- application/json
	//
	//	Security:
	//		oauth: profile_messages:read
	//
	//	Responses:
	//		default: MePostsPidLocks

	return func(c echo.Context) error {
		return user.PostLock()(c)
	}
}
174104
func (s *Service) DeleteAuthorization(ctx context.Context, id platform.ID) error {
	if _, err := s.FindAuthorizationByID(ctx, id); err != nil {
		return &platform.Error{
			Err: err,
			Op:  OpPrefix + platform.OpDeleteAuthorization,
		}
	}

	s.authorizationKV.Delete(id.String())
	return nil
}
751480
func (s *AuthorizationService) CreateAuthorization(ctx context.Context, a *platform.Authorization) error {
	u, err := newURL(s.Addr, authorizationPath)
	if err != nil {
		return err
	}
	if err != nil {
		return err
	}

	newAuth, err := newPostAuthorizationRequest(a)
	if err != nil {
		return err
	}
	octets, err := json.Marshal(newAuth)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", u.String(), bytes.NewReader(octets))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")
	SetToken(s.Token, req)

	hc := newClient(u.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// TODO(jsternberg): Should this check for a 201 explicitly?
	if err := CheckError(resp); err != nil {
		return err
	}

	if err := json.NewDecoder(resp.Body).Decode(a); err != nil {
		return err
	}

	return nil
}
191590
func (sa *StorageAuthority) FinalizeAuthorization(_ context.Context, authz core.Authorization) (err error) {
	return
}
847387
func (m *Manager) saveAuthorizationRequest(ar *authorizationRequest) (err error) {
	// TODO: Validation!

	err = m.getAuthorizationRequestCollection().Insert(ar)

	return
}
1097464
func (m *MockAuthorizeEndpointHandler) HandleAuthorizeEndpointRequest(arg0 context.Context, arg1 fosite.AuthorizeRequester, arg2 fosite.AuthorizeResponder) error {
	ret := m.ctrl.Call(m, "HandleAuthorizeEndpointRequest", arg0, arg1, arg2)
	ret0, _ := ret[0].(error)
	return ret0
}
756309
func (s *PutMethodInput) SetAuthorizationType(v string) *PutMethodInput {
	s.AuthorizationType = &v
	return s
}
203663
func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) {
	a, err := s.s.FindAuthorizationByID(ctx, id)
	if err != nil {
		return nil, err
	}

	if err := authorizeWriteAuthorization(ctx, a.UserID); err != nil {
		return nil, err
	}

	return s.s.UpdateAuthorization(ctx, id, upd)
}
991282
func PostHandler(w http.ResponseWriter, r *http.Request) {
	h, _, _ := net.SplitHostPort(r.RemoteAddr)

	data, err := parseData(r)
	if err != nil {
		writeErrorJSON(w, errors.Wrap(err, "failed to read body"))
		return
	}

	var jsonPayload interface{}
	if strings.Contains(r.Header.Get("Content-Type"), "json") {
		err := json.Unmarshal(data, &jsonPayload)
		if err != nil {
			writeErrorJSON(w, errors.Wrap(err, "failed to read body"))
			return
		}
	}

	v := postResponse{
		headersResponse: headersResponse{getHeaders(r)},
		ipResponse:      ipResponse{h},
		Args:            flattenValues(r.URL.Query()),
		Data:            string(data),
		JSON:            jsonPayload,
	}

	if err := writeJSON(w, v); err != nil {
		writeErrorJSON(w, errors.Wrap(err, "failed to write json"))
	}
}
590838
func (wfe *WebFrontEndImpl) Authorization(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
	var requestAccount *core.Registration
	var requestBody []byte
	// If the request is a POST it is either:
	//   A) an update to an authorization to deactivate it
	//   B) a POST-as-GET to query the authorization details
	if request.Method == "POST" {
		// Both POST options need to be authenticated by an account
		body, _, acct, prob := wfe.validPOSTForAccount(request, ctx, logEvent)
		addRequesterHeader(response, logEvent.Requester)
		if prob != nil {
			wfe.sendError(response, logEvent, prob, nil)
			return
		}
		requestAccount = acct
		requestBody = body
	}

	// Requests to this handler should have a path that leads to a known authz
	id := request.URL.Path
	var authz core.Authorization
	var err error
	if features.Enabled(features.NewAuthorizationSchema) && strings.HasPrefix(id, "/v2/") {
		authzID, err := strconv.ParseInt(id[4:], 10, 64)
		if err != nil {
			wfe.sendError(response, logEvent, probs.NotFound("No such authorization"), nil)
			return
		}
		authzPB, err := wfe.SA.GetAuthorization2(ctx, &sapb.AuthorizationID2{Id: &authzID})
		if err != nil {
			if berrors.Is(err, berrors.NotFound) {
				wfe.sendError(response, logEvent, probs.NotFound("No such authorization"), nil)
			} else {
				wfe.sendError(response, logEvent, probs.ServerInternal("Problem getting authorization"), err)
			}
			return
		}
		authz, err = bgrpc.PBToAuthz(authzPB)
		if err != nil {
			wfe.sendError(response, logEvent, probs.ServerInternal("Problem getting authorization"), err)
			return
		}
	} else {
		authz, err = wfe.SA.GetAuthorization(ctx, id)
		if err != nil {
			if berrors.Is(err, berrors.NotFound) {
				wfe.sendError(response, logEvent, probs.NotFound("No such authorization"), nil)
			} else {
				wfe.sendError(response, logEvent, probs.ServerInternal("Problem getting authorization"), err)
			}
			return
		}
	}
	if authz.Identifier.Type == core.IdentifierDNS {
		logEvent.DNSName = authz.Identifier.Value
	}
	logEvent.Status = string(authz.Status)

	// After expiring, authorizations are inaccessible
	if authz.Expires == nil || authz.Expires.Before(wfe.clk.Now()) {
		wfe.sendError(response, logEvent, probs.NotFound("Expired authorization"), nil)
		return
	}

	// If this was a POST that has an associated requestAccount and that account
	// doesn't own the authorization, abort before trying to deactivate the authz
	// or return its details
	if requestAccount != nil && requestAccount.ID != authz.RegistrationID {
		wfe.sendError(response, logEvent,
			probs.Unauthorized("Account ID doesn't match ID for authorization"), nil)
		return
	}

	// If the body isn't empty we know it isn't a POST-as-GET and must be an
	// attempt to deactivate an authorization.
	if string(requestBody) != "" && wfe.AllowAuthzDeactivation {
		// If the deactivation fails return early as errors and return codes
		// have already been set. Otherwise continue so that the user gets
		// sent the deactivated authorization.
		if !wfe.deactivateAuthorization(ctx, &authz, logEvent, response, requestBody) {
			return
		}
	}

	wfe.prepAuthorizationForDisplay(request, &authz)

	err = wfe.writeJsonResponse(response, logEvent, http.StatusOK, authz)
	if err != nil {
		// InternalServerError because this is a failure to decode from our DB.
		wfe.sendError(response, logEvent, probs.ServerInternal("Failed to JSON marshal authz"), err)
		return
	}
}
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)
	}
}