// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package secret

import (
	"github.com/vmware/harbor/src/common/secret"
)

// SecurityContext implements security.Context interface based on secret store
type SecurityContext struct {
	secret string
	store  *secret.Store
}

// NewSecurityContext ...
func NewSecurityContext(secret string, store *secret.Store) *SecurityContext {
	return &SecurityContext{
		secret: secret,
		store:  store,
	}
}

// IsAuthenticated returns true if the secret is valid
func (s *SecurityContext) IsAuthenticated() bool {
	if s.store == nil {
		return false
	}
	return s.store.IsValid(s.secret)
}

// GetUsername returns the corresponding username of the secret
// or null if the secret is invalid
func (s *SecurityContext) GetUsername() string {
	if s.store == nil {
		return ""
	}
	return s.store.GetUsername(s.secret)
}

// IsSysAdmin always returns false
func (s *SecurityContext) IsSysAdmin() bool {
	return false
}

// HasReadPerm returns true if the corresponding user of the secret
// is jobservice, otherwise returns false
func (s *SecurityContext) HasReadPerm(projectIDOrName interface{}) bool {
	if s.store == nil {
		return false
	}
	return s.store.GetUsername(s.secret) == secret.JobserviceUser
}

// HasWritePerm always returns false
func (s *SecurityContext) HasWritePerm(projectIDOrName interface{}) bool {
	return false
}

// HasAllPerm always returns false
func (s *SecurityContext) HasAllPerm(projectIDOrName interface{}) bool {
	return false
}
