Files

680 lines
30 KiB
Go

package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateprivacy"
"lincodex/backend/internal/usecase/candidateview"
)
const (
privacyCursorVersion = 1
privacyCursorBytes = 46
defaultPrivacyLimit = 20
privacyCursorEvents = 1
privacyCursorHidden = 2
privacyCursorAccess = 3
// privacyCursorEvidence belongs to the skill evidence list, which shares the
// owner-bound cursor of the privacy lists.
privacyCursorEvidence = 4
)
// CandidateViewOperations serves private previews, owner access history, and
// organization-scoped anonymous card reads.
type CandidateViewOperations interface {
GetOrganizationCard(ctx context.Context, actorID, organizationID uuid.UUID, handle string) (domain.AnonymousCandidateViewDTO, error)
GetMyCardPreview(ctx context.Context, actorID uuid.UUID) (candidateview.PreviewResult, error)
ListMyCardAccessHistory(ctx context.Context, query outbound.CandidateCardAccessListQuery) (outbound.CandidateCardAccessListPage, error)
}
// CandidatePrivacyOperations serves candidate-owned publication and privacy
// settings.
type CandidatePrivacyOperations interface {
GetMyPrivacySettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error)
SetMyPublication(ctx context.Context, userID uuid.UUID, expectedVersion int64, state domain.PublicationState, fields []domain.CardField) (domain.Publication, error)
SetMySearchStatus(ctx context.Context, userID uuid.UUID, expectedVersion int64, value domain.SearchStatusValue) (domain.SearchStatus, time.Time, error)
ListMyPrivacyHistory(ctx context.Context, query outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error)
ListMyHiddenOrganizations(ctx context.Context, query outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error)
HideOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error)
UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) error
}
// PrivacyHandler binds the privacy read and settings use cases to the v1 API.
type PrivacyHandler struct {
views CandidateViewOperations
settings CandidatePrivacyOperations
publicOrigin string
}
func NewPrivacyHandler(views CandidateViewOperations, settings CandidatePrivacyOperations, publicOrigin string) *PrivacyHandler {
if views == nil || settings == nil {
panic("v1.NewPrivacyHandler - view and settings operations must not be nil")
}
return &PrivacyHandler{views: views, settings: settings, publicOrigin: publicOrigin}
}
func (handler *Handler) GetMyCardPreview(ctx context.Context) (api.GetMyCardPreviewRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.GetMyCardPreview(ctx)
}
return handler.privacy.GetMyCardPreview(ctx)
}
func (handler *Handler) GetMyPrivacySettings(ctx context.Context) (api.GetMyPrivacySettingsRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.GetMyPrivacySettings(ctx)
}
return handler.privacy.GetMyPrivacySettings(ctx)
}
func (handler *Handler) GetOrganizationCandidateCard(ctx context.Context, params api.GetOrganizationCandidateCardParams) (api.GetOrganizationCandidateCardRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.GetOrganizationCandidateCard(ctx, params)
}
return handler.privacy.GetOrganizationCandidateCard(ctx, params)
}
func (handler *Handler) HideOrganization(ctx context.Context, params api.HideOrganizationParams) (api.HideOrganizationRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.HideOrganization(ctx, params)
}
return handler.privacy.HideOrganization(ctx, params)
}
func (handler *Handler) ListMyCardAccessHistory(ctx context.Context, params api.ListMyCardAccessHistoryParams) (api.ListMyCardAccessHistoryRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.ListMyCardAccessHistory(ctx, params)
}
return handler.privacy.ListMyCardAccessHistory(ctx, params)
}
func (handler *Handler) ListMyHiddenOrganizations(ctx context.Context, params api.ListMyHiddenOrganizationsParams) (api.ListMyHiddenOrganizationsRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.ListMyHiddenOrganizations(ctx, params)
}
return handler.privacy.ListMyHiddenOrganizations(ctx, params)
}
func (handler *Handler) ListMyPrivacyHistory(ctx context.Context, params api.ListMyPrivacyHistoryParams) (api.ListMyPrivacyHistoryRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.ListMyPrivacyHistory(ctx, params)
}
return handler.privacy.ListMyPrivacyHistory(ctx, params)
}
func (handler *Handler) SetMyPublication(ctx context.Context, request *api.PublicationUpdate) (api.SetMyPublicationRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.SetMyPublication(ctx, request)
}
return handler.privacy.SetMyPublication(ctx, request)
}
func (handler *Handler) SetMySearchStatus(ctx context.Context, request *api.SearchStatusUpdate) (api.SetMySearchStatusRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.SetMySearchStatus(ctx, request)
}
return handler.privacy.SetMySearchStatus(ctx, request)
}
func (handler *Handler) UnhideOrganization(ctx context.Context, params api.UnhideOrganizationParams) (api.UnhideOrganizationRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.UnhideOrganization(ctx, params)
}
return handler.privacy.UnhideOrganization(ctx, params)
}
func (handler *PrivacyHandler) GetMyCardPreview(ctx context.Context) (api.GetMyCardPreviewRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyCardPreviewUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
preview, err := handler.views.GetMyCardPreview(ctx, principal.UserID)
if err != nil {
if errors.Is(err, candidateview.ErrForbidden) {
return (*api.GetMyCardPreviewForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
return &api.CardPreviewHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: cardPreviewResponse(preview)}, nil
}
func (handler *PrivacyHandler) GetMyPrivacySettings(ctx context.Context) (api.GetMyPrivacySettingsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyPrivacySettingsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
settings, err := handler.settings.GetMyPrivacySettings(ctx, principal.UserID)
if err != nil {
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
return (*api.GetMyPrivacySettingsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
return &api.PrivacySettingsHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: privacySettingsResponse(settings)}, nil
}
func (handler *PrivacyHandler) GetOrganizationCandidateCard(ctx context.Context, params api.GetOrganizationCandidateCardParams) (api.GetOrganizationCandidateCardRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetOrganizationCandidateCardUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
view, err := handler.views.GetOrganizationCard(ctx, principal.UserID, params.OrgID, string(params.CandidateHandle))
if err != nil {
switch {
case errors.Is(err, candidateview.ErrForbidden):
return (*api.GetOrganizationCandidateCardForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, candidateview.ErrCandidateCardNotFound), errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.GetOrganizationCandidateCardNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, candidateview.ErrInvalidCandidateHandle):
return (*api.GetOrganizationCandidateCardBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationPath, "/candidate_handle").Response), nil
}
if limited, ok := candidateViewRateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
return &api.AnonymousCardContentHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: anonymousCardResponse(view)}, nil
}
func (handler *PrivacyHandler) ListMyCardAccessHistory(ctx context.Context, params api.ListMyCardAccessHistoryParams) (api.ListMyCardAccessHistoryRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyCardAccessHistoryUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorAccess)
if pointer != "" {
return (*api.ListMyCardAccessHistoryBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
var after *outbound.CandidateCardAccessPosition
if cursor != nil {
position := outbound.CandidateCardAccessPosition{OccurredAt: cursor.at, ID: cursor.id}
after = &position
}
page, err := handler.views.ListMyCardAccessHistory(ctx, outbound.CandidateCardAccessListQuery{CandidateID: principal.UserID, After: after, Limit: limit})
if err != nil {
if errors.Is(err, candidateview.ErrForbidden) || errors.Is(err, candidateprivacy.ErrForbidden) {
return (*api.ListMyCardAccessHistoryForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
items := make([]api.CardAccess, 0, len(page.Items))
for _, access := range page.Items {
organization := api.NilPrivacyOrganization{}
if name := page.OrganizationNames[access.OrganizationID()]; name != "" {
organization.SetTo(api.PrivacyOrganization{ID: access.OrganizationID(), Name: name})
} else {
organization.SetToNull()
}
items = append(items, api.CardAccess{
ID: access.ID(), Kind: api.CardAccessKind(access.Kind()), OccurredAt: api.Timestamp(access.OccurredAt()), Organization: organization,
})
}
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
last := page.Items[len(page.Items)-1]
return encodePrivacyCursor(principal.UserID, privacyCursorAccess, last.OccurredAt(), last.ID())
})
if err != nil {
return nil, fmt.Errorf("PrivacyHandler.ListMyCardAccessHistory - encode cursor: %w", err)
}
return &api.CardAccessListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.CardAccessList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}
func (handler *PrivacyHandler) ListMyHiddenOrganizations(ctx context.Context, params api.ListMyHiddenOrganizationsParams) (api.ListMyHiddenOrganizationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyHiddenOrganizationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorHidden)
if pointer != "" {
return (*api.ListMyHiddenOrganizationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
var after *outbound.HiddenOrganizationPosition
if cursor != nil {
position := outbound.HiddenOrganizationPosition{HiddenAt: cursor.at, OrganizationID: cursor.id}
after = &position
}
page, err := handler.settings.ListMyHiddenOrganizations(ctx, outbound.HiddenOrganizationListQuery{UserID: principal.UserID, After: after, Limit: limit})
if err != nil {
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
return (*api.ListMyHiddenOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
items := make([]api.HiddenOrganization, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, hiddenOrganizationResponse(item))
}
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
last := page.Items[len(page.Items)-1]
return encodePrivacyCursor(principal.UserID, privacyCursorHidden, last.HiddenAt, last.OrganizationID)
})
if err != nil {
return nil, fmt.Errorf("PrivacyHandler.ListMyHiddenOrganizations - encode cursor: %w", err)
}
return &api.HiddenOrganizationListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.HiddenOrganizationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}
func (handler *PrivacyHandler) ListMyPrivacyHistory(ctx context.Context, params api.ListMyPrivacyHistoryParams) (api.ListMyPrivacyHistoryRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyPrivacyHistoryUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorEvents)
if pointer != "" {
return (*api.ListMyPrivacyHistoryBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
var after *outbound.CandidatePrivacyEventPosition
if cursor != nil {
position := outbound.CandidatePrivacyEventPosition{OccurredAt: cursor.at, ID: cursor.id}
after = &position
}
page, err := handler.settings.ListMyPrivacyHistory(ctx, outbound.CandidatePrivacyEventListQuery{UserID: principal.UserID, After: after, Limit: limit})
if err != nil {
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
return (*api.ListMyPrivacyHistoryForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
items := make([]api.PrivacyEvent, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, privacyEventResponse(item))
}
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
last := page.Items[len(page.Items)-1]
return encodePrivacyCursor(principal.UserID, privacyCursorEvents, last.OccurredAt, last.ID)
})
if err != nil {
return nil, fmt.Errorf("PrivacyHandler.ListMyPrivacyHistory - encode cursor: %w", err)
}
return &api.PrivacyEventListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.PrivacyEventList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}
func (handler *PrivacyHandler) SetMyPublication(ctx context.Context, request *api.PublicationUpdate) (api.SetMyPublicationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SetMyPublicationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.SetMyPublicationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if request == nil {
return (*api.SetMyPublicationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
fields := make([]domain.CardField, 0, len(request.Fields))
for _, field := range request.Fields {
fields = append(fields, domain.CardField(field))
}
publication, err := handler.settings.SetMyPublication(ctx, principal.UserID, int64(request.ExpectedVersion), domain.PublicationState(request.State), fields)
if err != nil {
switch {
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
return (*api.SetMyPublicationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, domain.ErrVisibilityVersionConflict):
return (*api.SetMyPublicationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, domain.ErrPublicationConsentRequired):
return (*api.SetMyPublicationConflict)(privacyStateConflict(ctx, api.ProblemFieldLocationBody, "/state", "consent_required")), nil
case errors.Is(err, domain.ErrInvalidVisibility):
return (*api.SetMyPublicationBadRequest)(&privacyVisibilityInvalid(ctx, err).Response), nil
default:
return nil, err
}
}
return &api.PublicationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: publicationResponse(publication)}, nil
}
func (handler *PrivacyHandler) SetMySearchStatus(ctx context.Context, request *api.SearchStatusUpdate) (api.SetMySearchStatusRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SetMySearchStatusUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.SetMySearchStatusForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if request == nil {
return (*api.SetMySearchStatusBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
status, asOf, err := handler.settings.SetMySearchStatus(ctx, principal.UserID, int64(request.ExpectedVersion), domain.SearchStatusValue(request.Value))
if err != nil {
switch {
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
return (*api.SetMySearchStatusForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, domain.ErrVisibilityVersionConflict):
return (*api.SetMySearchStatusPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, domain.ErrInvalidVisibility):
return (*api.SetMySearchStatusBadRequest)(&privacyVisibilityInvalid(ctx, err).Response), nil
default:
return nil, err
}
}
return &api.SearchStatusHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: searchStatusResponse(status, asOf)}, nil
}
func (handler *PrivacyHandler) HideOrganization(ctx context.Context, params api.HideOrganizationParams) (api.HideOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.HideOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.HideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
hidden, err := handler.settings.HideOrganization(ctx, principal.UserID, params.OrgID)
if err != nil {
switch {
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
return (*api.HideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrCandidatePrivacyOrganizationNotVisible), errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.HideOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, outbound.ErrCandidateHiddenOrganizationLimit):
return (*api.HideOrganizationConflict)(privacyStateConflict(ctx, api.ProblemFieldLocationPath, "/org_id", "limit_reached")), nil
default:
return nil, err
}
}
return &api.HiddenOrganizationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: hiddenOrganizationResponse(hidden)}, nil
}
func (handler *PrivacyHandler) UnhideOrganization(ctx context.Context, params api.UnhideOrganizationParams) (api.UnhideOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.UnhideOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.UnhideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if err := handler.settings.UnhideOrganization(ctx, principal.UserID, params.OrgID); err != nil {
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
return (*api.UnhideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
return &api.UnhideOrganizationNoContent{CacheControl: api.CacheControlNoStoreNoStore}, nil
}
type privacyCursor struct {
at time.Time
id uuid.UUID
}
func privacyPageParams(limit api.OptInt32, cursor api.OptString, owner uuid.UUID, kind byte) (int32, *privacyCursor, string) {
pageLimit, set := limit.Get()
if !set {
pageLimit = defaultPrivacyLimit
}
if pageLimit < 1 || pageLimit > outbound.MaxPrivacyPageSize {
return 0, nil, "limit"
}
value, set := cursor.Get()
if !set {
return pageLimit, nil, ""
}
position, err := decodePrivacyCursor(value, owner, kind)
if err != nil {
return 0, nil, "cursor"
}
return pageLimit, &position, ""
}
func encodePrivacyCursor(owner uuid.UUID, kind byte, at time.Time, id uuid.UUID) (string, error) {
at = at.UTC()
seconds, nanos := at.Unix(), at.Nanosecond()
if owner == uuid.Nil || id == uuid.Nil || kind < privacyCursorEvents || kind > privacyCursorEvidence || at.IsZero() ||
at.Year() < 1 || at.Year() > 9999 || nanos < 0 || nanos >= 1_000_000_000 || nanos%1_000 != 0 {
return "", errors.New("privacy cursor requires an owner and valid page position")
}
var value [privacyCursorBytes]byte
value[0], value[1] = privacyCursorVersion, kind
copy(value[2:18], owner[:])
writePrivacyCursorSeconds(value[18:26], seconds)
binary.BigEndian.PutUint32(value[26:30], uint32(nanos))
copy(value[30:46], id[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodePrivacyCursor(cursor string, owner uuid.UUID, kind byte) (privacyCursor, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != privacyCursorBytes || owner == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != privacyCursorVersion || value[1] != kind ||
uuid.UUID(value[2:18]) != owner {
return privacyCursor{}, errors.New("privacy cursor is invalid")
}
seconds := decodePrivacyCursorSeconds(value[18:26])
nanos := binary.BigEndian.Uint32(value[26:30])
id := uuid.UUID(value[30:46])
if nanos >= 1_000_000_000 || nanos%1_000 != 0 || id == uuid.Nil {
return privacyCursor{}, errors.New("privacy cursor position is invalid")
}
at := time.Unix(seconds, int64(nanos)).UTC()
if at.IsZero() || at.Year() < 1 || at.Year() > 9999 {
return privacyCursor{}, errors.New("privacy cursor timestamp is invalid")
}
return privacyCursor{at: at, id: id}, nil
}
func writePrivacyCursorSeconds(encoded []byte, seconds int64) {
encoded[0] = byte((seconds >> 56) & 0xff)
encoded[1] = byte((seconds >> 48) & 0xff)
encoded[2] = byte((seconds >> 40) & 0xff)
encoded[3] = byte((seconds >> 32) & 0xff)
encoded[4] = byte((seconds >> 24) & 0xff)
encoded[5] = byte((seconds >> 16) & 0xff)
encoded[6] = byte((seconds >> 8) & 0xff)
encoded[7] = byte(seconds & 0xff)
}
func decodePrivacyCursorSeconds(encoded []byte) int64 {
high := int64(binary.BigEndian.Uint32(encoded[:4]))
low := int64(binary.BigEndian.Uint32(encoded[4:]))
return high<<32 | low
}
func privacyNextCursor(hasMore bool, itemCount int, encode func() (string, error)) (api.NilString, error) {
var next api.NilString
next.SetToNull()
if !hasMore {
return next, nil
}
if itemCount == 0 {
return api.NilString{}, errors.New("privacy page has_more without items")
}
if hasMore {
cursor, err := encode()
if err != nil {
return api.NilString{}, err
}
next.SetTo(cursor)
}
return next, nil
}
func cardPreviewResponse(preview candidateview.PreviewResult) api.CardPreview {
state := api.PublicationStateClosed
if preview.Published {
state = api.PublicationStatePublished
}
fields := make(api.CardFieldSet, 0, len(preview.Fields.Fields()))
for _, field := range preview.Fields.Fields() {
fields = append(fields, api.CardField(field))
}
card := api.NilAnonymousCardContent{}
if preview.Card == nil {
card.SetToNull()
} else {
card.SetTo(anonymousCardResponse(*preview.Card))
}
evidence := api.NilOrganizationEvidence{}
if preview.Card == nil {
evidence.SetToNull()
} else {
evidence.SetTo(organizationEvidenceResponse(preview.Evidence))
}
return api.CardPreview{State: state, Fields: fields, Card: card, Evidence: evidence, GeneratedAt: api.Timestamp(preview.GeneratedAt)}
}
func anonymousCardResponse(view domain.AnonymousCandidateViewDTO) api.AnonymousCardContent {
content := api.AnonymousCardContent{Pseudonym: view.Pseudonym}
for _, category := range view.Categories {
content.Categories = append(content.Categories, api.CardCategory{
Specialization: api.SpecializationCode(category.Specialization), Grade: api.GradeCode(category.Grade),
Strength: api.CardCategoryStrength(category.Strength), Basis: api.EvidenceBasis(category.Basis),
})
}
for _, skill := range view.Skills {
content.Stack = append(content.Stack, api.AnonymousCardContentStackItem(skill))
}
for _, assessment := range view.SelfAssessment {
grade := api.OptNilGradeCode{}
if assessment.DeclaredGrade == nil {
grade.SetToNull()
} else {
grade.SetTo(api.GradeCode(*assessment.DeclaredGrade))
}
content.SelfAssessment = append(content.SelfAssessment, api.CardSelfAssessment{
Specialization: api.SpecializationCode(assessment.Specialization),
ConfirmationStatus: api.CardSelfAssessmentConfirmationStatus(assessment.ConfirmationStatus),
DeclaredGrade: grade,
})
}
content.ExperienceBand.SetToNull()
if view.ExperienceBand != nil {
content.ExperienceBand.SetTo(api.CandidateExperienceBand(*view.ExperienceBand))
}
for _, format := range view.WorkFormats {
content.WorkFormats = append(content.WorkFormats, api.CandidateWorkFormat(format))
}
content.SalaryCompatibility.SetToNull()
if view.SalaryCompatibility != nil {
content.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*view.SalaryCompatibility))
}
for _, project := range view.Projects {
description := api.NilString{Null: true}
if project.Description != nil {
description.SetTo(*project.Description)
}
stack := make([]api.StackTag, 0, len(project.Stack))
for _, tag := range project.Stack {
stack = append(stack, api.StackTag(tag))
}
content.Projects = append(content.Projects, api.CardProject{
Title: project.Title, Description: description, Stack: stack, RepositoryVerified: project.RepositoryVerified,
})
}
return content
}
func privacySettingsResponse(settings outbound.CandidatePrivacySettings) api.PrivacySettings {
return api.PrivacySettings{
Publication: publicationResponse(settings.Publication),
SearchStatus: searchStatusResponse(settings.SearchStatus, settings.AsOf),
HiddenOrganizationsTotal: int(settings.HiddenCount),
}
}
func publicationResponse(publication domain.Publication) api.Publication {
response := api.Publication{State: api.PublicationState(publication.State()), Version: api.PublicationVersion(publication.Version())}
response.ClosedReason.SetToNull()
if reason := publication.ClosedReason(); reason != "" {
response.ClosedReason.SetTo(api.PublicationClosedReason(reason))
}
response.ConsentID.SetToNull()
if consentID := publication.ConsentRecordID(); consentID != uuid.Nil {
response.ConsentID.SetTo(consentID)
}
response.PublishedAt.SetToNull()
if publishedAt := publication.PublishedAt(); !publishedAt.IsZero() {
response.PublishedAt.SetTo(api.Timestamp(publishedAt))
}
for _, field := range publication.Fields().Fields() {
response.Fields = append(response.Fields, api.CardField(field))
}
if response.Fields == nil {
response.Fields = api.CardFieldSet{}
}
return response
}
func searchStatusResponse(status domain.SearchStatus, asOf time.Time) api.SearchStatus {
response := api.SearchStatus{Value: api.SearchStatusValue(status.Effective(asOf)), Lapsed: status.Lapsed(asOf), Version: api.SearchStatusVersion(status.Version())}
response.ConfirmedAt.SetToNull()
if confirmedAt := status.ConfirmedAt(); !confirmedAt.IsZero() {
response.ConfirmedAt.SetTo(api.Timestamp(confirmedAt))
}
response.LapsesAt.SetToNull()
if lapsesAt := status.LapsesAt(); !lapsesAt.IsZero() {
response.LapsesAt.SetTo(api.Timestamp(lapsesAt))
}
return response
}
func privacyEventResponse(event outbound.CandidatePrivacyEventRecord) api.PrivacyEvent {
response := api.PrivacyEvent{ID: event.ID, Kind: api.PrivacyEventKind(event.Kind), OccurredAt: api.Timestamp(event.OccurredAt)}
if event.Fields == nil {
response.Fields = nil
} else {
response.Fields = make(api.CardFieldSet, 0, len(event.Fields.Fields()))
for _, field := range event.Fields.Fields() {
response.Fields = append(response.Fields, api.CardField(field))
}
}
response.ConsentID.SetToNull()
if event.ConsentRecordID != uuid.Nil {
response.ConsentID.SetTo(event.ConsentRecordID)
}
response.Organization.SetToNull()
if event.OrganizationID != uuid.Nil && event.OrganizationName != "" {
response.Organization.SetTo(api.PrivacyOrganization{ID: event.OrganizationID, Name: event.OrganizationName})
}
return response
}
func hiddenOrganizationResponse(hidden outbound.HiddenOrganizationRecord) api.HiddenOrganization {
return api.HiddenOrganization{
Organization: api.PrivacyOrganization{ID: hidden.OrganizationID, Name: hidden.OrganizationName},
HiddenAt: api.Timestamp(hidden.HiddenAt),
}
}
func privacyVisibilityInvalid(ctx context.Context, err error) *api.ProblemStatusCode {
field, ok := errors.AsType[*domain.VisibilityFieldError](err)
if !ok {
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
}
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer)
}
func privacyStateConflict(ctx context.Context, location api.ProblemFieldLocation, pointer, code string) *api.Problem {
response := problem.New(ctx, api.ProblemCodeStateConflict).Response
response.Errors = []api.ProblemFieldError{{
In: location, Pointer: pointer, Code: code,
Message: "The requested setting cannot be applied in the current state.",
}}
return &response
}
func candidateViewRateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) {
limited, ok := errors.AsType[*candidateview.RateLimitedError](err)
if !ok {
return nil, false
}
return problem.RateLimited(ctx, wholeSeconds(time.Until(limited.RetryAt))), true
}