// Authorization is used by clients to submit an update to one of their
// authorizations.
480060
func (wfe *WebFrontEndImpl) Authorization(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
	// 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 wfe.AllowAuthzDeactivation && request.Method == "POST" {
		// 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, request) {
			return
		}
	}

	wfe.prepAuthorizationForDisplay(request, &authz)

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

	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
	}
}
1148887
func RoleEscalationAuthorized(ctx context.Context, a authorizer.Authorizer) bool {
	if a == nil {
		return false
	}

	user, ok := genericapirequest.UserFrom(ctx)
	if !ok {
		return false
	}

	requestInfo, ok := genericapirequest.RequestInfoFrom(ctx)
	if !ok {
		return false
	}

	if !requestInfo.IsResourceRequest {
		return false
	}

	requestResource := schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}
	if !roleResources[requestResource] {
		return false
	}

	attrs := authorizer.AttributesRecord{
		User:            user,
		Verb:            "escalate",
		APIGroup:        requestInfo.APIGroup,
		Resource:        requestInfo.Resource,
		Name:            requestInfo.Name,
		Namespace:       requestInfo.Namespace,
		ResourceRequest: true,
	}

	decision, _, err := a.Authorize(attrs)
	if err != nil {
		utilruntime.HandleError(fmt.Errorf(
			"error authorizing user %#v to escalate %#v named %q in namespace %q: %v",
			user, requestResource, requestInfo.Name, requestInfo.Namespace, err,
		))
	}
	return decision == authorizer.DecisionAllow
}
438758
func (s *Service) UpdateAuthorization(ctx context.Context, id platform.ID, upd *platform.AuthorizationUpdate) (*platform.Authorization, error) {
	op := OpPrefix + platform.OpUpdateAuthorization
	a, err := s.FindAuthorizationByID(ctx, id)
	if err != nil {
		return nil, &platform.Error{
			Err: err,
			Op:  op,
		}
	}

	if upd.Status != nil {
		status := *upd.Status
		switch status {
		case platform.Active, platform.Inactive:
		default:
			return nil, &platform.Error{
				Code: platform.EInvalid,
				Msg:  "unknown authorization status",
				Op:   op,
			}
		}
		a.Status = status
	}

	if upd.Description != nil {
		a.Description = *upd.Description
	}

	return a, s.PutAuthorization(ctx, a)
}
291899
func (b *BasicAuth) Authorize(c *Client, method string, path string) {
	a := b.user + ":" + b.pw
	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(a))
	c.headers.Set("Authorization", auth)
}
284198
func (ctx *Context) Unauthorized() {
	ctx.Abort(http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
}
260664
func (c *Clientset) AuthorizationV1() authorizationv1.AuthorizationV1Interface {
	return &fakeauthorizationv1.FakeAuthorizationV1{Fake: &c.Fake}
}
868263
func (c *Client) NewAuthorization(accountKey interface{}, typ, val string) (auth Authorization, authURL string, err error) {
	type Identifier struct {
		Type  string `json:"type"`
		Value string `json:"value"`
	}

	data := struct {
		Resource   string     `json:"resource"`
		Identifier Identifier `json:"identifier"`
	}{
		resourceNewAuthorization,
		Identifier{typ, val},
	}
	payload, err := c.signObject(accountKey, &data)
	if err != nil {
		return auth, "", err
	}
	resp, err := c.client.Post(c.resources.NewAuthorization, jwsContentType, strings.NewReader(payload))
	if err != nil {
		return auth, "", err
	}
	defer resp.Body.Close()
	if err = checkHTTPError(resp, http.StatusCreated); err != nil {
		return auth, "", err
	}

	if err := json.NewDecoder(resp.Body).Decode(&auth); err != nil {
		return auth, "", fmt.Errorf("decoding response body: %v", err)
	}
	return auth, resp.Header.Get("Location"), nil
}
1160420
func (b BasicAuthorization) Authorization() string {
	auth := b.username + ":" + b.password
	return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth)))
}
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
}
900250
func Authorize() echo.HandlerFunc {
	return func(c echo.Context) error {
		resp := oauth.NewResponse()
		defer resp.Close()

		if ar := oauth.HandleAuthorizeRequest(resp, c.Request()); ar != nil {
			if c.QueryParam("authorized") == "" || c.QueryParam("authorized_code") == "" {
				c.Redirect(http.StatusFound, fmt.Sprintf("%s/oauth2/authorize.php?client_id=%s&response_type=%s&redirect_uri=%s&scope=%s",
					nerdz.Configuration.NERDZURL().String(),
					url.QueryEscape(c.QueryParam("client_id")),
					url.QueryEscape(c.QueryParam("response_type")),
					url.QueryEscape(c.QueryParam("redirect_uri")),
					url.QueryEscape(c.QueryParam("scope"))))
				return nil
			} else {
				var e error
				var userID uint64
				if userID, e = strconv.ParseUint(c.QueryParam("authorized"), 10, 64); e != nil {
					return c.JSON(http.StatusInternalServerError, &rest.Response{
						HumanMessage: "Invalid authorized (user id) value",
						Message:      e.Error(),
						Status:       http.StatusInternalServerError,
						Success:      false,
					})
				}

				var user *nerdz.User
				if user, e = nerdz.NewUser(userID); e != nil {
					return c.JSON(http.StatusInternalServerError, &rest.Response{
						HumanMessage: "Problem retrieving specified user",
						Message:      e.Error(),
						Status:       http.StatusInternalServerError,
						Success:      false,
					})
				}
				sha1_sum := fmt.Sprintf("%x", sha1.Sum([]byte(user.Username+user.Password+user.Email)))
				if sha1_sum != c.QueryParam("authorized_code") {
					message := "Invalid authorization code"
					return c.JSON(http.StatusInternalServerError, &rest.Response{
						HumanMessage: message,
						Message:      message,
						Status:       http.StatusInternalServerError,
						Success:      false,
					})
				}

				ar.UserData = user.Counter
				ar.Authorized = true
				oauth.FinishAuthorizeRequest(resp, c.Request(), ar)
			}
		}

		if resp.IsError && resp.InternalError != nil {
			return c.JSON(http.StatusInternalServerError, &rest.Response{
				HumanMessage: "Internal Server error",
				Message:      resp.InternalError.Error(),
				Status:       http.StatusInternalServerError,
				Success:      false,
			})
		}

		return osin.OutputJSON(resp, c.Response(), c.Request())
	}
}
1257575
func (m *Middleware) Authorize(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion) {
	secretBlock := x509.MarshalPKCS1PrivateKey(m.ServiceProvider.Key)

	redirectURI := "/"
	if relayState := r.Form.Get("RelayState"); relayState != "" {
		stateValue := m.ClientState.GetState(r, relayState)
		if stateValue == "" {
			m.ServiceProvider.Logger.Printf("cannot find corresponding state: %s", relayState)
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		jwtParser := jwt.Parser{
			ValidMethods: []string{jwtSigningMethod.Name},
		}
		state, err := jwtParser.Parse(stateValue, func(t *jwt.Token) (interface{}, error) {
			return secretBlock, nil
		})
		if err != nil || !state.Valid {
			m.ServiceProvider.Logger.Printf("Cannot decode state JWT: %s (%s)", err, stateValue)
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}
		claims := state.Claims.(jwt.MapClaims)
		redirectURI = claims["uri"].(string)

		// delete the cookie
		m.ClientState.DeleteState(w, r, relayState)
	}

	now := saml.TimeNow()
	claims := AuthorizationToken{}
	claims.Audience = m.ServiceProvider.Metadata().EntityID
	claims.IssuedAt = now.Unix()
	claims.ExpiresAt = now.Add(m.TokenMaxAge).Unix()
	claims.NotBefore = now.Unix()
	if sub := assertion.Subject; sub != nil {
		if nameID := sub.NameID; nameID != nil {
			claims.StandardClaims.Subject = nameID.Value
		}
	}
	for _, attributeStatement := range assertion.AttributeStatements {
		claims.Attributes = map[string][]string{}
		for _, attr := range attributeStatement.Attributes {
			claimName := attr.FriendlyName
			if claimName == "" {
				claimName = attr.Name
			}
			for _, value := range attr.Values {
				claims.Attributes[claimName] = append(claims.Attributes[claimName], value.Value)
			}
		}
	}
	signedToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256,
		claims).SignedString(secretBlock)
	if err != nil {
		panic(err)
	}

	m.ClientToken.SetToken(w, r, signedToken, m.TokenMaxAge)
	http.Redirect(w, r, redirectURI, http.StatusFound)
}
126962
func (c *FakeOAuthClients) Update(oAuthClient *oauth.OAuthClient) (result *oauth.OAuthClient, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(oauthclientsResource, oAuthClient), &oauth.OAuthClient{})
	if obj == nil {
		return nil, err
	}
	return obj.(*oauth.OAuthClient), err
}
1000867
func Update(id string, params *stripe.IssuingAuthorizationParams) (*stripe.IssuingAuthorization, error) {
	return getC().Update(id, params)
}
299839
func (s *OauthService) AuthorizeURL(clientID string, options *AuthorizationOptions) string {
	uri, _ := url.Parse(strings.Replace(s.client.BaseURL, "api.", "", 1))
	uri.Path = "/oauth/authorize"
	query := uri.Query()
	query.Add("client_id", clientID)
	query.Add("response_type", "code")
	uri.RawQuery = query.Encode()

	path, _ := addURLQueryOptions(uri.String(), options)
	return path
}
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
	}
}
1319677
func (s *Service) PutAuthorization(ctx context.Context, a *influxdb.Authorization) error {
	return s.kv.Update(ctx, func(tx Tx) error {
		return s.putAuthorization(ctx, tx, a)
	})
}
881741
func (a *Authenticator) Authorize(ctx context.Context, w http.ResponseWriter, p oauth2.Principal) error {
	cookie := http.Cookie{}

	http.SetCookie(w, &cookie)
	return nil
}