credential.go 1005 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package auth
  2. import (
  3. "context"
  4. "google.golang.org/grpc/metadata"
  5. )
  6. // A Credential is used to authenticate.
  7. type Credential struct {
  8. App string
  9. Token string
  10. }
  11. // GetRequestMetadata gets the request metadata.
  12. func (c *Credential) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
  13. return map[string]string{
  14. appKey: c.App,
  15. tokenKey: c.Token,
  16. }, nil
  17. }
  18. // RequireTransportSecurity always returns false.
  19. func (c *Credential) RequireTransportSecurity() bool {
  20. return false
  21. }
  22. // ParseCredential parses credential from given ctx.
  23. func ParseCredential(ctx context.Context) Credential {
  24. var credential Credential
  25. md, ok := metadata.FromIncomingContext(ctx)
  26. if !ok {
  27. return credential
  28. }
  29. apps, tokens := md[appKey], md[tokenKey]
  30. if len(apps) == 0 || len(tokens) == 0 {
  31. return credential
  32. }
  33. app, token := apps[0], tokens[0]
  34. if len(app) == 0 || len(token) == 0 {
  35. return credential
  36. }
  37. credential.App = app
  38. credential.Token = token
  39. return credential
  40. }