/*
 * Copyright 2021 PingCAP, Inc.
 *
 * 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,
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package auth

import (
	"context"
	"crypto/tls"
	"fmt"
	"net/http"

	"github.com/pingcap/fn"
	"github.com/pingcap/log"

	"github.com/pingcap/mimir/pkg/protos"
)

type contextKey string

const (
	tlsCNKey = contextKey("TLSCommonName")
)

func CommonName(ctx context.Context) string {
	name, ok := ctx.Value(tlsCNKey).(string)
	if !ok {
		name = protos.DefaultUserID
	}
	return name
}

func Auth(tlsCfg *tls.Config) fn.PluginFunc {
	return func(ctx context.Context, req *http.Request) (context.Context, error) {
		if tlsCfg == nil {
			return context.WithValue(ctx, tlsCNKey, protos.DefaultUserID), nil
		}
		if req.TLS == nil {
			log.Error("tls configured but received a http request")
			return ctx, fmt.Errorf("unexpected http request")
		}
		if len(req.TLS.VerifiedChains) == 0 {
			log.Error("tls configured but a request without verify arrived")
			return ctx, fmt.Errorf("unable to verify the user")
		}
		cn := req.TLS.VerifiedChains[0][0].Subject.CommonName
		return context.WithValue(ctx, tlsCNKey, cn), nil
	}
}
