stillbox/pkg/gordio/auth/auth.go

63 lines
1.3 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
}
type authenticator struct {
2024-07-29 00:29:16 -04:00
domain string
jwt *jwtauth.JWTAuth
2024-08-04 08:55:12 -04:00
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.
func NewAuthenticator(cfg *config.Auth) Authenticator {
2024-07-29 00:58:32 -04:00
return &authenticator{
2024-08-04 08:55:12 -04:00
domain: cfg.Domain,
jwt: jwtauth.New("HS256", []byte(cfg.JWTSecret), nil),
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
}
}