route/internal/server/common.go

69 lines
1.4 KiB
Go
Raw Normal View History

2017-04-29 02:47:24 +00:00
package server
import (
"context"
"errors"
2017-09-30 13:41:35 +00:00
"git.xeserv.us/xena/route/internal/database"
2017-04-29 02:47:24 +00:00
"github.com/Xe/ln"
2017-10-01 15:06:27 +00:00
"golang.org/x/net/trace"
2017-04-29 02:47:24 +00:00
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
)
// errors
var (
ErrNotAuthorized = errors.New("server: not authorized")
)
2017-10-01 15:06:27 +00:00
func (s *Server) getAuth(ctx context.Context, operation, scope string) (context.Context, database.Token, error) {
2017-04-29 02:47:24 +00:00
var err error
2017-09-30 16:47:47 +00:00
md, ok := metadata.FromIncomingContext(ctx)
2017-04-29 02:47:24 +00:00
if !ok {
2017-10-01 15:06:27 +00:00
return nil, database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
2017-04-29 02:47:24 +00:00
}
jwtToken, ok := md["authorization"]
if !ok {
2017-10-01 15:06:27 +00:00
return nil, database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
2017-04-29 02:47:24 +00:00
}
val := jwtToken[0]
t, err := s.db.GetToken(ctx, val)
if err != nil {
2017-10-01 15:06:27 +00:00
return nil, database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
2017-04-29 02:47:24 +00:00
}
ok = false
for _, sc := range t.Scopes {
if sc == scope {
ok = true
}
}
if !ok {
2017-10-01 15:06:27 +00:00
return nil, database.Token{}, grpc.Errorf(codes.Unauthenticated, "invalid scope.")
2017-04-29 02:47:24 +00:00
}
2017-10-01 15:06:27 +00:00
tr := trace.New("routed-grpc", operation)
ctx = trace.NewContext(ctx, tr)
ln.Log(ctx, t)
2017-10-01 15:06:27 +00:00
return ctx, t, nil
2017-04-29 02:47:24 +00:00
}
func handleError(ctx context.Context, clitok database.Token, err error, f ln.F) error {
2017-10-01 15:06:27 +00:00
tr, ok := trace.FromContext(ctx)
if !ok {
goto skip
}
tr.SetError()
skip:
2017-10-01 13:28:13 +00:00
ln.Error(ctx, err, f, clitok)
2017-04-29 02:47:24 +00:00
return err
}