2021-12-13 11:08:10 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/base64"
|
|
|
|
"strings"
|
|
|
|
|
2024-10-17 15:15:05 +00:00
|
|
|
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth"
|
2021-12-13 11:08:10 +00:00
|
|
|
|
2023-07-07 23:33:10 +00:00
|
|
|
"go.linka.cloud/grpc-toolkit/errors"
|
|
|
|
"go.linka.cloud/grpc-toolkit/interceptors"
|
|
|
|
"go.linka.cloud/grpc-toolkit/interceptors/metadata"
|
2021-12-13 11:08:10 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func BasicAuth(user, password string) string {
|
|
|
|
return "basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+password))
|
|
|
|
}
|
|
|
|
|
2022-03-11 11:33:18 +00:00
|
|
|
type BasicValidator func(ctx context.Context, user, password string) (context.Context, error)
|
2021-12-13 11:08:10 +00:00
|
|
|
|
|
|
|
func makeBasicAuthFunc(v BasicValidator) grpc_auth.AuthFunc {
|
|
|
|
return func(ctx context.Context) (context.Context, error) {
|
|
|
|
a, err := grpc_auth.AuthFromMD(ctx, "basic")
|
|
|
|
if err != nil {
|
|
|
|
return ctx, err
|
|
|
|
}
|
|
|
|
c, err := base64.StdEncoding.DecodeString(a)
|
|
|
|
if err != nil {
|
|
|
|
return ctx, err
|
|
|
|
}
|
|
|
|
cs := string(c)
|
|
|
|
s := strings.IndexByte(cs, ':')
|
|
|
|
if s < 0 {
|
|
|
|
return ctx, errors.Unauthenticatedf("malformed basic auth")
|
|
|
|
}
|
|
|
|
return v(ctx, cs[:s], cs[s+1:])
|
|
|
|
}
|
|
|
|
}
|
2022-03-11 11:33:18 +00:00
|
|
|
|
|
|
|
func NewBasicAuthClientIntereptors(user, password string) interceptors.ClientInterceptors {
|
|
|
|
return metadata.NewInterceptors("authorization", BasicAuth(user, password))
|
|
|
|
}
|