auth.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package middleware
  2. import (
  3. "crypto/subtle"
  4. "net/http"
  5. "strings"
  6. "github.com/owncast/owncast/core/data"
  7. "github.com/owncast/owncast/core/user"
  8. "github.com/owncast/owncast/utils"
  9. log "github.com/sirupsen/logrus"
  10. )
  11. // ExternalAccessTokenHandlerFunc is a function that is called after validing access.
  12. type ExternalAccessTokenHandlerFunc func(user.ExternalAPIUser, http.ResponseWriter, *http.Request)
  13. // UserAccessTokenHandlerFunc is a function that is called after validing user access.
  14. type UserAccessTokenHandlerFunc func(user.User, http.ResponseWriter, *http.Request)
  15. // RequireAdminAuth wraps a handler requiring HTTP basic auth for it using the given
  16. // the stream key as the password and and a hardcoded "admin" for username.
  17. func RequireAdminAuth(handler http.HandlerFunc) http.HandlerFunc {
  18. return func(w http.ResponseWriter, r *http.Request) {
  19. username := "admin"
  20. password := data.GetAdminPassword()
  21. realm := "Owncast Authenticated Request"
  22. // The following line is kind of a work around.
  23. // If you want HTTP Basic Auth + Cors it requires _explicit_ origins to be provided in the
  24. // Access-Control-Allow-Origin header. So we just pull out the origin header and specify it.
  25. // If we want to lock down admin APIs to not be CORS accessible for anywhere, this is where we would do that.
  26. w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
  27. w.Header().Set("Access-Control-Allow-Credentials", "true")
  28. w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  29. // For request needing CORS, send a 204.
  30. if r.Method == "OPTIONS" {
  31. w.WriteHeader(http.StatusNoContent)
  32. return
  33. }
  34. user, pass, ok := r.BasicAuth()
  35. // Failed
  36. if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {
  37. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  38. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  39. log.Debugln("Failed admin authentication")
  40. return
  41. }
  42. handler(w, r)
  43. }
  44. }
  45. func accessDenied(w http.ResponseWriter) {
  46. w.WriteHeader(http.StatusUnauthorized) //nolint
  47. w.Write([]byte("unauthorized")) //nolint
  48. }
  49. // RequireExternalAPIAccessToken will validate a 3rd party access token.
  50. func RequireExternalAPIAccessToken(scope string, handler ExternalAccessTokenHandlerFunc) http.HandlerFunc {
  51. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  52. // We should accept 3rd party preflight OPTIONS requests.
  53. if r.Method == "OPTIONS" {
  54. // All OPTIONS requests should have a wildcard CORS header.
  55. w.Header().Set("Access-Control-Allow-Origin", "*")
  56. w.WriteHeader(http.StatusNoContent)
  57. return
  58. }
  59. authHeader := strings.Split(r.Header.Get("Authorization"), "Bearer ")
  60. token := strings.Join(authHeader, "")
  61. if len(authHeader) == 0 || token == "" {
  62. log.Warnln("invalid access token")
  63. accessDenied(w)
  64. return
  65. }
  66. integration, err := user.GetExternalAPIUserForAccessTokenAndScope(token, scope)
  67. if integration == nil || err != nil {
  68. accessDenied(w)
  69. return
  70. }
  71. // All auth'ed 3rd party requests should have a wildcard CORS header.
  72. w.Header().Set("Access-Control-Allow-Origin", "*")
  73. handler(*integration, w, r)
  74. if err := user.SetExternalAPIUserAccessTokenAsUsed(token); err != nil {
  75. log.Debugln("token not found when updating last_used timestamp")
  76. }
  77. })
  78. }
  79. // RequireUserAccessToken will validate a provided user's access token and make sure the associated user is enabled.
  80. // Not to be used for validating 3rd party access.
  81. func RequireUserAccessToken(handler UserAccessTokenHandlerFunc) http.HandlerFunc {
  82. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  83. accessToken := r.URL.Query().Get("accessToken")
  84. if accessToken == "" {
  85. accessDenied(w)
  86. return
  87. }
  88. ipAddress := utils.GetIPAddressFromRequest(r)
  89. // Check if this client's IP address is banned.
  90. if blocked, err := data.IsIPAddressBanned(ipAddress); blocked {
  91. log.Debugln("Client ip address has been blocked. Rejecting.")
  92. accessDenied(w)
  93. return
  94. } else if err != nil {
  95. log.Errorln("error determining if IP address is blocked: ", err)
  96. }
  97. // A user is required to use the websocket
  98. user := user.GetUserByToken(accessToken)
  99. if user == nil || !user.IsEnabled() {
  100. accessDenied(w)
  101. return
  102. }
  103. handler(*user, w, r)
  104. })
  105. }
  106. // RequireUserModerationScopeAccesstoken will validate a provided user's access token and make sure the associated user is enabled
  107. // and has "MODERATOR" scope assigned to the user.
  108. func RequireUserModerationScopeAccesstoken(handler http.HandlerFunc) http.HandlerFunc {
  109. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  110. accessToken := r.URL.Query().Get("accessToken")
  111. if accessToken == "" {
  112. accessDenied(w)
  113. return
  114. }
  115. // A user is required to use the websocket
  116. user := user.GetUserByToken(accessToken)
  117. if user == nil || !user.IsEnabled() || !user.IsModerator() {
  118. accessDenied(w)
  119. return
  120. }
  121. handler(w, r)
  122. })
  123. }