// FindAuthorizationByToken returns a authorization by token for a particular authorization.
321000
func (s *Service) FindAuthorizationByToken(ctx context.Context, n string) (*influxdb.Authorization, error) {
	var a *influxdb.Authorization
	err := s.kv.View(ctx, func(tx Tx) error {
		auth, err := s.findAuthorizationByToken(ctx, tx, n)
		if err != nil {
			return err
		}

		a = auth

		return nil
	})

	if err != nil {
		return nil, err
	}

	return a, nil
}
511877
func (s *AuthorizationService) FindAuthorizations(ctx context.Context, filter platform.AuthorizationFilter, opt ...platform.FindOptions) ([]*platform.Authorization, int, error) {
	u, err := newURL(s.Addr, authorizationPath)
	if err != nil {
		return nil, 0, err
	}

	query := u.Query()

	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, 0, err
	}

	if filter.ID != nil {
		query.Add("id", filter.ID.String())
	}

	if filter.UserID != nil {
		query.Add("userID", filter.UserID.String())
	}

	if filter.User != nil {
		query.Add("user", *filter.User)
	}

	if filter.OrgID != nil {
		query.Add("orgID", filter.OrgID.String())
	}

	if filter.Org != nil {
		query.Add("org", *filter.Org)
	}

	req.URL.RawQuery = query.Encode()
	SetToken(s.Token, req)

	hc := newClient(u.Scheme, s.InsecureSkipVerify)
	resp, err := hc.Do(req)
	if err != nil {
		return nil, 0, err
	}
	defer resp.Body.Close()

	if err := CheckError(resp); err != nil {
		return nil, 0, err
	}

	var as authsResponse
	if err := json.NewDecoder(resp.Body).Decode(&as); err != nil {
		return nil, 0, err
	}

	auths := make([]*platform.Authorization, 0, len(as.Auths))
	for _, a := range as.Auths {
		auths = append(auths, a.toPlatform())
	}

	return auths, len(auths), nil
}
765280
func (api UsersAPI) GetAuthorization(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	grantedTo := mux.Vars(r)["grantedTo"]

	userMgr := user.NewManager(r)

	authorization, err := userMgr.GetAuthorization(username, grantedTo)
	if handleServerError(w, "Getting authorization by user", err) {
		return
	}
	if authorization == nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}
	w.Header().Set("Content-type", "application/json")
	json.NewEncoder(w).Encode(authorization)
}
84893
func (ssa *SQLStorageAuthority) GetAuthorization2(ctx context.Context, id *sapb.AuthorizationID2) (*corepb.Authorization, error) {
	obj, err := ssa.dbMap.Get(authz2Model{}, *id.Id)
	if err != nil {
		return nil, err
	}
	if obj == nil {
		return nil, berrors.NotFoundError("authorization %d not found", *id.Id)
	}
	return modelToAuthzPB(obj.(*authz2Model))
}
301457
func (a *preAuthorizer) PreAuthorize(ctx context.Context, ast *ast.Package, auth platform.Authorizer, orgID *platform.ID) error {
	readBuckets, writeBuckets, err := BucketsAccessed(ast, orgID)
	if err != nil {
		return errors.Wrap(err, "could not retrieve buckets for query.Spec")
	}

	for _, readBucketFilter := range readBuckets {
		bucket, err := a.bucketService.FindBucket(ctx, readBucketFilter)
		if err != nil {
			return errors.Wrapf(err, "could not find read bucket with filter: %s", readBucketFilter)
		}

		if bucket == nil {
			return errors.New("bucket service returned nil bucket")
		}

		reqPerm, err := platform.NewPermissionAtID(bucket.ID, platform.ReadAction, platform.BucketsResourceType, bucket.OrgID)
		if err != nil {
			return errors.Wrapf(err, "could not create read bucket permission")
		}

		if !auth.Allowed(*reqPerm) {
			return errors.New("no read permission for bucket: \"" + bucket.Name + "\"")
		}
	}

	for _, writeBucketFilter := range writeBuckets {
		bucket, err := a.bucketService.FindBucket(ctx, writeBucketFilter)
		if err != nil {
			return errors.Wrapf(err, "could not find write bucket with filter: %s", writeBucketFilter)
		}

		reqPerm, err := platform.NewPermissionAtID(bucket.ID, platform.WriteAction, platform.BucketsResourceType, bucket.OrgID)
		if err != nil {
			return errors.Wrapf(err, "could not create write bucket permission")
		}
		if !auth.Allowed(*reqPerm) {
			return errors.New("no write permission for bucket: \"" + bucket.Name + "\"")
		}
	}

	return nil
}
1359460
func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken(data *AuthorizeData) (ret string, err error) {
	token := uuid.NewRandom()
	return base64.RawURLEncoding.EncodeToString([]byte(token)), nil
}
548631
func (server *HTTPServer) GetUserAuthTokens(c *models.ReqContext) Response {
	return server.getUserAuthTokensInternal(c, c.UserId)
}
1233638
func TokenAuthorizedWithOrg(a *Authorization, org string) func(ID, DocumentIndex) error {
	return func(id ID, idx DocumentIndex) error {
		if !a.IsActive() {
			return &Error{
				Code: EUnauthorized,
				Msg:  "authorization cannot add org as document owner",
			}
		}

		oid, err := idx.FindOrganizationByName(org)
		if err != nil {
			return err
		}

		p := Permission{
			Action: WriteAction,
			Resource: Resource{
				Type:  DocumentsResourceType,
				OrgID: &oid,
			},
		}

		if !a.Allowed(p) {
			return &Error{
				Code: EUnauthorized,
				Msg:  "authorization cannot add org as document owner",
			}
		}

		return idx.AddDocumentOwner(id, "org", oid)
	}
}
8502
func (s *service) AuthorizeToken(ctx context.Context, hostname, path, token string) (*sessions.Session, error) {
	resourceCh, resourceErrCh := make(chan *resources.Resource, 1), make(chan error, 1)
	sessionCh, sessionErrCh := make(chan *sessions.Session, 1), make(chan error, 1)
	go func() {
		session, err := s.sessionRepo.FindByToken(ctx, token)
		if err != nil {
			sessionErrCh <- err
			close(sessionCh)
			return
		}
		sessionCh <- session
		close(sessionErrCh)
	}()
	go func() {
		resource, err := s.resourceRepo.FindByHostname(ctx, hostname)
		if err != nil {
			resourceErrCh <- err
			close(resourceCh)
			return
		}
		resourceCh <- resource
		close(resourceErrCh)
	}()
	// If we can't find a resource, we deny the access
	// Otherwise, the access is denied with an error
	if err := <-resourceErrCh; err != nil {
		if isErrNotFound(err) {
			return nil, withErrDeniedAccess(err)
		}
		return nil, err

	}
	resource := <-resourceCh
	// If the found resource is marked as public, we allow the access without condition
	if resource.Public != nil && *resource.Public {
		return nil, nil
	}
	// If no session is found for the token, we initiate a guest session
	// Otherwise, the access is denied with an error
	if err := <-sessionErrCh; err != nil {
		if isErrNotFound(err) {
			return s.authorizeGuestSession(ctx, path, resource.Name)
		}
		return nil, err
	}
	foundSession := <-sessionCh
	// If a session is found, we try to authorize it
	session, err := s.authorizeSession(ctx, path, resource.Name, foundSession)
	if err != nil {
		// If denied, we at least try to authorize as guest
		if isErrDeniedAccess(err) {
			if _, err := s.authorizeGuestSession(ctx, path, resource.Name); err != nil {
				return nil, err
			}
			return foundSession, nil
		}
		return nil, err
	}
	// If found, we return it
	return session, nil
}
618279
func (sa *StorageAuthority) GetAuthorizations(ctx context.Context, req *sapb.GetAuthorizationsRequest) (*sapb.Authorizations, error) {
	return &sapb.Authorizations{}, nil
}
1037753
func (c *BasicAuth) GetAuthorization() string {
	return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", c.Username, c.Password))))
}
701573
func (m *Manager) getAuthorizationRequest(authorizationcode string) (ar *authorizationRequest, err error) {
	ar = &authorizationRequest{}

	err = m.getAuthorizationRequestCollection().Find(bson.M{"authorizationcode": authorizationcode}).One(ar)
	if err != nil && err == mgo.ErrNotFound {
		ar = nil
		err = nil
		return
	}
	return
}
1039761
func (c *Client) VoidAuthorization(authID string) (*Authorization, error) {
	buf := bytes.NewBuffer([]byte(""))
	req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", c.APIBase, "/v2/payments/authorization/"+authID+"/void"), buf)
	if err != nil {
		return &Authorization{}, err
	}

	auth := &Authorization{}
	err = c.SendWithAuth(req, auth)
	return auth, err
}
759161
func (a *Authenticator) ValidAuthorization(ctx context.Context, serializedAuthorization string) (oauth2.Principal, error) {
	return oauth2.Principal{}, nil
}
423591
func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.AuthorizationFilter, opt ...influxdb.FindOptions) ([]*influxdb.Authorization, int, error) {
	if filter.ID != nil {
		a, err := s.FindAuthorizationByID(ctx, *filter.ID)
		if err != nil {
			return nil, 0, &influxdb.Error{
				Err: err,
			}
		}

		return []*influxdb.Authorization{a}, 1, nil
	}

	if filter.Token != nil {
		a, err := s.FindAuthorizationByToken(ctx, *filter.Token)
		if err != nil {
			return nil, 0, &influxdb.Error{
				Err: err,
			}
		}

		return []*influxdb.Authorization{a}, 1, nil
	}

	as := []*influxdb.Authorization{}
	err := s.kv.View(ctx, func(tx Tx) error {
		auths, err := s.findAuthorizations(ctx, tx, filter)
		if err != nil {
			return err
		}
		as = auths
		return nil
	})

	if err != nil {
		return nil, 0, &influxdb.Error{
			Err: err,
		}
	}

	return as, len(as), nil
}
484411
func (sa *StorageAuthority) GetAuthorization2(ctx context.Context, id *sapb.AuthorizationID2) (*corepb.Authorization, error) {
	authz := core.Authorization{
		Status:         core.StatusValid,
		RegistrationID: 1,
		Identifier:     core.AcmeIdentifier{Type: "dns", Value: "not-an-example.com"},
		V2:             true,
		Challenges: []core.Challenge{
			{
				ID:    23,
				Token: "token",
				Type:  "dns",
			},
		},
	}

	switch *id.Id {
	case authzIdValid:
		exp := sa.clk.Now().AddDate(100, 0, 0)
		authz.Expires = &exp
		authz.ID = fmt.Sprintf("%d", authzIdValid)
		return bgrpc.AuthzToPB(authz)
	case authzIdPending:
		exp := sa.clk.Now().AddDate(100, 0, 0)
		authz.Expires = &exp
		authz.ID = fmt.Sprintf("%d", authzIdPending)
		authz.Status = core.StatusPending
		return bgrpc.AuthzToPB(authz)
	case authzIdExpired:
		exp := sa.clk.Now().AddDate(0, -1, 0)
		authz.Expires = &exp
		authz.ID = fmt.Sprintf("%d", authzIdExpired)
		return bgrpc.AuthzToPB(authz)
	case authzIdErrorResult:
		return nil, fmt.Errorf("Unspecified database error")
	case authzIdDiffAccount:
		exp := sa.clk.Now().AddDate(100, 0, 0)
		authz.RegistrationID = 2
		authz.Expires = &exp
		authz.ID = fmt.Sprintf("%d", authzIdDiffAccount)
		return bgrpc.AuthzToPB(authz)
	}

	return nil, berrors.NotFoundError("no authorization found with id %q", id)
}
860938
func (self *OAuth1Mixin) AuthorizeToken(w http.ResponseWriter, r *http.Request) (*oauth1.AccessToken, error) {

	//Get the presisted request token
	cookie, err := r.Cookie("_token")
	if err != nil {
		return nil, nil
	}

	//Parse the persisted request token
	requestToken, err := oauth1.ParseRequestTokenStr(cookie.Value)
	if err != nil {
		return nil, err
	}

	//Delete the request Token ...don't need it anymore
	DeleteUserCookieName(w,r,"_token")

	//Parse the verification code from the Redirect URL
	verifier := r.URL.Query().Get("oauth_verifier")

	//Upgrade to an Authorization Token
	accessToken, err := self.Consumer.AuthorizeToken(requestToken, verifier)
	if err != nil {
		return nil, err
	}

	return accessToken, nil
}