auth.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package auth
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "github.com/gin-gonic/gin"
  8. log "github.com/sirupsen/logrus"
  9. )
  10. func Header(c *gin.Context, key string) string {
  11. if values, _ := c.Request.Header[key]; len(values) > 0 {
  12. return values[0]
  13. }
  14. return ""
  15. }
  16. func BasicAuth() gin.HandlerFunc {
  17. realm := "Authorization Required"
  18. realm = "Basic realm=" + strconv.Quote(realm)
  19. user := os.Getenv("USER")
  20. password := os.Getenv("PASSWORD")
  21. enabled := isEnabled(user, password)
  22. if enabled {
  23. log.Warn("Auth mode enabled")
  24. log.Warn(fmt.Sprintf("Visit http://%s:%s@0.0.0.0:8080", user, password))
  25. }
  26. return func(c *gin.Context) {
  27. header := Header(c, "Authorization")
  28. if enabled && header != authorizationHeader(user, password) {
  29. // Credentials doesn't match, we return 401 and abort handlers chain.
  30. c.Header("WWW-Authenticate", realm)
  31. c.AbortWithStatus(401)
  32. return
  33. }
  34. c.Next()
  35. }
  36. }
  37. func isEnabled(user, password string) bool {
  38. switch {
  39. case user == "":
  40. return false
  41. case password == "":
  42. return false
  43. default:
  44. return true
  45. }
  46. }
  47. func authorizationHeader(user, password string) string {
  48. base := user + ":" + password
  49. return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
  50. }