auth/internal/domain/action.go

87 lines
2.0 KiB
Go
Raw Normal View History

2021-12-30 00:42:54 +00:00
package domain
import (
"fmt"
"strconv"
"source.toby3d.me/toby3d/auth/internal/common"
2021-12-30 00:42:54 +00:00
)
2022-01-29 17:50:45 +00:00
// Action represent action for token endpoint supported by IndieAuth.
//
2021-12-30 00:42:54 +00:00
// NOTE(toby3d): Encapsulate enums in structs for extra compile-time safety:
// https://threedots.tech/post/safer-enums-in-go/#struct-based-enums
type Action struct {
action string
2021-12-30 00:42:54 +00:00
}
2022-12-26 14:09:34 +00:00
//nolint:gochecknoglobals // structs cannot be constants
2021-12-30 00:42:54 +00:00
var (
ActionUnd = Action{action: ""} // "und"
2022-01-29 17:50:45 +00:00
// ActionRevoke represent action for revoke token.
ActionRevoke = Action{action: "revoke"} // "revoke"
2022-01-29 17:50:45 +00:00
// ActionTicket represent action for TicketAuth extension.
ActionTicket = Action{action: "ticket"} // "ticket"
2021-12-30 00:42:54 +00:00
)
var ErrActionSyntax error = NewError(ErrorCodeInvalidRequest, "unknown action method", "")
2022-12-26 14:09:34 +00:00
//nolint:gochecknoglobals
var uidsActions = map[string]Action{
ActionRevoke.action: ActionRevoke,
ActionTicket.action: ActionTicket,
}
2021-12-30 00:42:54 +00:00
// ParseAction parse string identifier of action into struct enum.
2022-01-29 17:50:45 +00:00
func ParseAction(uid string) (Action, error) {
if action, ok := uidsActions[uid]; ok {
return action, nil
2021-12-30 00:42:54 +00:00
}
return ActionUnd, fmt.Errorf("%w: %s", ErrActionSyntax, uid)
2021-12-30 00:42:54 +00:00
}
// UnmarshalForm implements custom unmarshler for form values.
func (a *Action) UnmarshalForm(v []byte) error {
action, err := ParseAction(string(v))
if err != nil {
return fmt.Errorf("Action: UnmarshalForm: %w", err)
2021-12-30 00:42:54 +00:00
}
*a = action
return nil
}
2022-01-29 17:50:45 +00:00
// UnmarshalJSON implements custom unmarshler for JSON.
2021-12-30 00:42:54 +00:00
func (a *Action) UnmarshalJSON(v []byte) error {
src, err := strconv.Unquote(string(v))
if err != nil {
return fmt.Errorf("Action: UnmarshalJSON: %w", err)
2021-12-30 00:42:54 +00:00
}
action, err := ParseAction(src)
if err != nil {
return fmt.Errorf("Action: UnmarshalJSON: %w", err)
2021-12-30 00:42:54 +00:00
}
*a = action
return nil
}
// String returns string representation of action.
func (a Action) String() string {
if a.action != "" {
return a.action
}
return common.Und
}
func (a Action) GoString() string {
return "domain.Action(" + a.String() + ")"
2021-12-30 00:42:54 +00:00
}