// LoadAuthorize looks up AuthorizeData by a code.
// Client information MUST be loaded together.
// Optionally can return error if expired.
486721
func (s *Storage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {
	var data osin.AuthorizeData
	var extra string
	var cid string
	if err := s.db.QueryRow("SELECT client, code, expires_in, scope, redirect_uri, state, created_at, extra FROM authorize WHERE code=$1 LIMIT 1", code).Scan(&cid, &data.Code, &data.ExpiresIn, &data.Scope, &data.RedirectUri, &data.State, &data.CreatedAt, &extra); err == sql.ErrNoRows {
		return nil, pkg.ErrNotFound
	} else if err != nil {
		return nil, errors.New(err)
	}
	data.UserData = extra

	c, err := s.GetClient(cid)
	if err != nil {
		return nil, err
	}

	if data.ExpireAt().Before(time.Now()) {
		return nil, errors.Errorf("Token expired at %s.", data.ExpireAt().String())
	}

	data.Client = c
	return &data, nil
}
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())
	}
}
85511
func (s *Storage) SaveAuthorize(data *osin.AuthorizeData) (err error) {
	userId, ok := data.UserData.(uint)
	if !ok {
		return errors.New("cannot assert user_id is uint")
	}

	var authorize service.Authorize
	copier.Copy(&authorize, &data)
	authorize.UserId = userId
	authorize.Client = data.Client.GetId()

	if !dbconn.DB.NewRecord(authorize) {
		return errors.New("authorize already exist")
	} else if err := dbconn.DB.Create(&authorize).Error; err != nil {
		return err
	} else if dbconn.DB.NewRecord(authorize) {
		return errors.New("authorize was not created")
	}
	return nil
}
1204931
func (controllerAuthorizer) Authorize(authInfo httpcontext.AuthInfo) error {
	if authInfo.Controller {
		return nil
	}
	return errors.Errorf("%s is not a controller", names.ReadableString(authInfo.Entity.Tag()))
}
1006216
func TokenAuthorized(a *Authorization) func(ID, DocumentIndex) error {
	return func(id ID, idx DocumentIndex) error {
		if !a.IsActive() {
			return &Error{
				Code: EUnauthorized,
				Msg:  "authorizer cannot access document",
			}
		}

		oids, err := idx.GetDocumentsAccessors(id)
		if err != nil {
			return err
		}
		orgs := map[ID]bool{}
		for _, oid := range oids {
			orgs[oid] = true
		}

		for _, p := range a.Permissions {
			if p.Action == ReadAction {
				continue
			}

			// If the authz has a direct permission to access the resource
			if p.Resource.Type == DocumentsResourceType && p.Resource.ID != nil && *p.Resource.ID == id {
				return nil
			}
			// If the authz has a direct permission to access the class of resources
			if p.Resource.Type == DocumentsResourceType && p.Resource.ID == nil && p.Resource.OrgID == nil {
				return nil
			}

			if p.Resource.Type == DocumentsResourceType && p.Resource.OrgID != nil && orgs[*p.Resource.OrgID] {
				return nil
			}

		}

		return &Error{
			Code: EUnauthorized,
			Msg:  "authorization cannot access document",
		}
	}
}
988461
func (s *OAuth2Storage) LoadAccess(token string) (*osin.AccessData, error) {
	oad := new(OAuth2AccessData)
	if err := Db().Model(OAuth2AccessData{}).Where(&OAuth2AccessData{AccessToken: token}).Scan(oad); err != nil {
		return nil, errors.New("LoadAccess: AccessToken not found")
	}

	var ret osin.AccessData

	ret.CreatedAt = oad.CreatedAt
	ret.ExpiresIn = int32(oad.ExpiresIn)
	if ret.IsExpired() {
		return nil, errors.New("Access token expired")
	}

	if client, err := s.GetClient(strconv.FormatUint(oad.ClientID, 10)); err == nil {
		ret.Client = client
	} else {
		return nil, err
	}

	ret.AccessToken = token
	ret.Scope = oad.Scope
	ret.RedirectUri = oad.RedirectURI
	ret.UserData = oad.UserID

	if oad.RefreshTokenID.Valid {
		var refreshToken OAuth2RefreshToken
		if err := Db().First(&refreshToken, uint64(oad.RefreshTokenID.Int64)); err != nil {
			return nil, err
		}
		ret.RefreshToken = refreshToken.Token
	}

	return &ret, nil
}
1304512
func (a tagKindAuthorizer) Authorize(authInfo httpcontext.AuthInfo) error {
	tagKind := authInfo.Entity.Tag().Kind()
	for _, kind := range a {
		if tagKind == kind {
			return nil
		}
	}
	return errors.NotValidf("tag kind %v", tagKind)
}
958611
func (s *OAuth2Storage) SaveAuthorize(data *osin.AuthorizeData) error {
	var clientID uint64
	var err error
	if clientID, err = strconv.ParseUint(data.Client.GetId(), 10, 64); err != nil {
		return err
	}

	if err = s.isValidScope(data.Scope); err != nil {
		return fmt.Errorf("Saving Authorize: " + err.Error())
	}

	d := &OAuth2AuthorizeData{
		ClientID: clientID,
		Code:     data.Code,
		// CreatedAt field is automatically filled by the dbms
		ExpiresIn:   uint64(data.ExpiresIn),
		RedirectURI: data.RedirectUri,
		Scope:       data.Scope,
		//State:       data.State,
		UserID: data.UserData.(uint64)}

	return Db().Create(d)
}
655446
func (s *Server) WithAuthorization(scheme AuthorizationScheme) *Server {
	s.authorization = scheme
	return s
}
269307
func (a *preAuthorizer) PreAuthorize(ctx context.Context, spec *flux.Spec, auth platform.Authorizer) error {
	readBuckets, writeBuckets, err := BucketsAccessed(spec)

	if err != nil {
		return errors.Wrap(err, "could not retrieve buckets for query.Spec")
	}

	for _, readBucketItem := range readBuckets {
		bucket, err := a.bucketService.FindBucket(ctx, readBucketItem)
		if err != nil {
			return errors.Wrapf(err, "bucket does not exist")
		}

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

		reqPerm, err := platform.NewPermissionAtID(bucket.ID, platform.ReadAction, platform.BucketsResource)
		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 bucket %v", writeBucketFilter)
		}

		reqPerm, err := platform.NewPermissionAtID(bucket.ID, platform.WriteAction, platform.BucketsResource)
		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
}
907631
func (resource *Resource) NewAuthorizedMethod(httpMethod string,
	authorizerID gocf.Stringable,
	defaultHTTPStatusCode int,
	possibleHTTPStatusCodeResponses ...int) (*Method, error) {
	if authorizerID == nil {
		return nil, fmt.Errorf("authorizerID must not be `nil` for Authorized Method")
	}
	method, methodErr := resource.NewMethod(httpMethod,
		defaultHTTPStatusCode,
		possibleHTTPStatusCodeResponses...)
	if methodErr == nil {
		method.authorizationID = authorizerID
	}
	return method, methodErr
}
398757
func (ssa *SQLStorageAuthority) GetAuthorization(ctx context.Context, id string) (core.Authorization, error) {
	authz := core.Authorization{}
	tx, err := ssa.dbMap.Begin()
	if err != nil {
		return authz, err
	}
	txWithCtx := tx.WithContext(ctx)

	pa, err := selectPendingAuthz(txWithCtx, "WHERE id = ?", id)
	if err != nil && err != sql.ErrNoRows {
		return authz, Rollback(tx, err)
	}
	if err == sql.ErrNoRows {
		var fa authzModel
		err := txWithCtx.SelectOne(&fa, fmt.Sprintf("SELECT %s FROM authz WHERE id = ?", authzFields), id)
		if err != nil && err != sql.ErrNoRows {
			return authz, Rollback(tx, err)
		} else if err == sql.ErrNoRows {
			// If there was no result in either the pending authz table or the authz
			// table then return a `berrors.NotFound` instance (or a rollback error if
			// the transaction rollback fails)
			return authz, Rollback(
				tx,
				berrors.NotFoundError("no authorization found with id %q", id))
		}
		authz = fa.Authorization
	} else {
		authz = pa.Authorization
	}

	authz.Challenges, err = ssa.getChallenges(txWithCtx, authz.ID)
	if err != nil {
		return authz, Rollback(tx, err)
	}

	return authz, tx.Commit()
}
662923
func (c *Client) Authorize(password string) (response *Packet, err error) {
	if response, err = c.Send(Auth, password); nil == err {
		if response.Header.Type == AuthResponse {
			c.Authorized = true
		} else {
			err = ErrFailedAuthorization
			response = nil
			return
		}
	}

	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
}
425261
func (settings EnvironmentSettings) GetAuthorizer() (autorest.Authorizer, error) {
	//1.Client Credentials
	if c, e := settings.GetClientCredentials(); e == nil {
		return c.Authorizer()
	}

	//2. Client Certificate
	if c, e := settings.GetClientCertificate(); e == nil {
		return c.Authorizer()
	}

	//3. Username Password
	if c, e := settings.GetUsernamePassword(); e == nil {
		return c.Authorizer()
	}

	// 4. MSI
	return settings.GetMSI().Authorizer()
}
191590
func (sa *StorageAuthority) FinalizeAuthorization(_ context.Context, authz core.Authorization) (err error) {
	return
}
541152
func (a *Account) RemoveAuthorizedClient(name string) error {
	return a.del(a.auth, fmt.Sprintf("/api/v2/users/me/authorized-clients/%s", name))
}