ezshare/server/interceptors/auth.go

56 lines
1.3 KiB
Go
Raw Normal View History

2021-12-05 13:55:18 +00:00
package interceptors
import (
"context"
"fmt"
"gitea.benny.dog/torjus/ezshare/pb"
"gitea.benny.dog/torjus/ezshare/store"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/peer"
)
type ContextKey string
var ContextKeyRole ContextKey = "role"
func NewAuthInterceptor(s store.UserStore) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
p, ok := peer.FromContext(ctx)
if ok {
tlsInfo, ok := p.AuthInfo.(credentials.TLSInfo)
if ok {
fmt.Printf("%+v\n", tlsInfo.State.PeerCertificates[0].Subject.CommonName)
if len(tlsInfo.State.PeerCertificates) == 1 {
cert := tlsInfo.State.PeerCertificates[0]
id := cert.Subject.CommonName
user, err := s.GetUser(id)
if err == nil {
newCtx := context.WithValue(ctx, ContextKeyRole, user.UserRole)
return handler(newCtx, req)
}
}
}
}
newCtx := context.WithValue(ctx, ContextKeyRole, pb.User_UNKNOWN)
return handler(newCtx, req)
}
}
func RoleFromContext(ctx context.Context) pb.User_Role {
value := ctx.Value(ContextKeyRole)
if value == nil {
return pb.User_UNKNOWN
}
role, ok := value.(pb.User_Role)
if ok {
return role
}
return pb.User_UNKNOWN
}