route/server/common.go

56 lines
1.1 KiB
Go
Raw Normal View History

2017-04-29 02:47:24 +00:00
package server
import (
"context"
"errors"
"git.xeserv.us/xena/route/database"
"github.com/Xe/ln"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
)
// errors
var (
ErrNotAuthorized = errors.New("server: not authorized")
)
func (s *Server) getAuth(ctx context.Context, scope string) (database.Token, error) {
var err error
md, ok := metadata.FromContext(ctx)
if !ok {
2017-04-29 03:08:11 +00:00
return database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
2017-04-29 02:47:24 +00:00
}
jwtToken, ok := md["authorization"]
if !ok {
return database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
}
val := jwtToken[0]
t, err := s.db.GetToken(ctx, val)
if err != nil {
return database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
}
ok = false
for _, sc := range t.Scopes {
if sc == scope {
ok = true
}
}
if !ok {
return database.Token{}, grpc.Errorf(codes.Unauthenticated, "invalid scope.")
}
return t, nil
}
func handleError(ctx context.Context, clitok database.Token, err error, f ln.F) error {
ln.Error(err, f, clitok.F())
return err
}