stillbox/pkg/gordio/auth/auth.go

62 lines
1.2 KiB
Go
Raw Normal View History

2024-07-29 00:29:16 -04:00
package auth
2024-07-15 10:12:53 -04:00
import (
"errors"
"net/http"
2024-08-04 08:55:12 -04:00
"dynatron.me/x/stillbox/pkg/gordio/config"
2024-07-15 10:12:53 -04:00
"github.com/go-chi/jwtauth/v5"
)
2024-08-01 01:01:08 -04:00
type UserID int
func (u *UserID) Int32Ptr() *int32 {
if u == nil {
return nil
}
i := int32(*u)
return &i
}
2024-07-29 00:47:58 -04:00
// Authenticator performs API key and user JWT authentication.
2024-07-29 00:58:32 -04:00
type Authenticator interface {
jwtAuth
apiKeyAuth
}
2024-10-22 08:39:15 -04:00
type Auth struct {
2024-08-04 09:07:31 -04:00
jwt *jwtauth.JWTAuth
cfg config.Auth
2024-07-29 00:29:16 -04:00
}
2024-07-15 10:12:53 -04:00
2024-08-04 08:55:12 -04:00
// NewAuthenticator creates a new Authenticator with the provided config.
2024-10-22 08:39:15 -04:00
func NewAuthenticator(cfg config.Auth) *Auth {
return &Auth{
2024-08-04 09:07:31 -04:00
jwt: jwtauth.New("HS256", []byte(cfg.JWTSecret), nil),
cfg: cfg,
2024-07-29 00:29:16 -04:00
}
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
}
}