github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/auth/simple/simple.go (about) 1 package simple 2 3 import ( 4 "context" 5 6 "github.com/projecteru2/core/types" 7 8 "google.golang.org/grpc" 9 "google.golang.org/grpc/metadata" 10 ) 11 12 // BasicAuth use token to auth grcp request 13 type BasicAuth struct { 14 username string 15 password string 16 } 17 18 // NewBasicAuth return a basicauth obj 19 func NewBasicAuth(username, password string) *BasicAuth { 20 return &BasicAuth{username, password} 21 } 22 23 // StreamInterceptor define stream interceptor 24 func (b *BasicAuth) StreamInterceptor(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { 25 ctx := stream.Context() 26 if err := b.doAuth(ctx); err != nil { 27 return err 28 } 29 return handler(srv, stream) 30 } 31 32 // UnaryInterceptor define unary interceptor 33 func (b *BasicAuth) UnaryInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { 34 if err := b.doAuth(ctx); err != nil { 35 return nil, err 36 } 37 return handler(ctx, req) 38 } 39 40 func (b *BasicAuth) doAuth(ctx context.Context) error { 41 meta, ok := metadata.FromIncomingContext(ctx) 42 if !ok { 43 return types.ErrInvaildGRPCRequestMeta 44 } 45 passwords, ok := meta[b.username] 46 if !ok { 47 return types.ErrInvaildGRPCUsername 48 } 49 if len(passwords) < 1 || passwords[0] != b.password { 50 return types.ErrInvaildGRPCPassword 51 } 52 return nil 53 }