2024-07-29 00:29:16 -04:00
|
|
|
package auth
|
2024-07-15 10:12:53 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/go-chi/jwtauth/v5"
|
|
|
|
)
|
|
|
|
|
2024-07-29 00:47:58 -04:00
|
|
|
// Authenticator performs API key and user JWT authentication.
|
2024-07-29 00:29:16 -04:00
|
|
|
type Authenticator struct {
|
|
|
|
domain string
|
|
|
|
jwt *jwtauth.JWTAuth
|
|
|
|
}
|
2024-07-15 10:12:53 -04:00
|
|
|
|
2024-07-29 00:47:58 -04:00
|
|
|
// NewAuthenticator creates a new Authenticator with the provided JWT secret and cookie domain.
|
2024-07-29 00:29:16 -04:00
|
|
|
func NewAuthenticator(jwtSecret string, domain string) *Authenticator {
|
|
|
|
return &Authenticator{
|
|
|
|
domain: domain,
|
|
|
|
jwt: jwtauth.New("HS256", []byte(jwtSecret), nil),
|
|
|
|
}
|
2024-07-15 10:12:53 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
2024-07-29 00:29:16 -04:00
|
|
|
ErrLoginFailed = errors.New("Login failed")
|
|
|
|
ErrInternal = errors.New("Internal server error")
|
|
|
|
ErrUnauthorized = errors.New("Unauthorized")
|
|
|
|
ErrBadRequest = errors.New("Bad request")
|
2024-07-15 10:12:53 -04:00
|
|
|
)
|
|
|
|
|
2024-07-29 00:47:58 -04:00
|
|
|
// ErrorResponse writes the error and appropriate HTTP response code.
|
2024-07-29 00:29:16 -04:00
|
|
|
func ErrorResponse(w http.ResponseWriter, err error) {
|
|
|
|
switch err {
|
|
|
|
case ErrLoginFailed, ErrUnauthorized:
|
|
|
|
http.Error(w, err.Error(), http.StatusUnauthorized)
|
|
|
|
case ErrBadRequest:
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
case ErrInternal:
|
|
|
|
fallthrough
|
|
|
|
default:
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
2024-07-15 10:12:53 -04:00
|
|
|
}
|
|
|
|
}
|