feat(org): add organization and membership contract and storage

This commit is contained in:
shira committed 2026-10-06 15:55:29 +03:00
1 parent a0551a34b8
commit bdc5855001
90 files changed
+17545 -480

No files matched your search

@@ -17,20 +17,22 @@ import (
)
var regexMap = map[string]ogenregex.Regexp{
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
}
var (
// Allocate option closure once.
@@ -1342,6 +1342,263 @@ func (s *Server) handleCreateMySupportCaseRequest(args [0]string, argsEscaped bo
}
}
// handleCreateOrganizationRequest handles CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
func (s *Server) handleCreateOrganizationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("CreateOrganization"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/organizations"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), CreateOrganizationOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: CreateOrganizationOperation,
ID: "CreateOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, CreateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, CreateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeCreateOrganizationParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
request, rawBody, close, err := s.decodeCreateOrganizationRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response CreateOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: CreateOrganizationOperation,
OperationSummary: "Create an organization; the caller becomes its owner.",
OperationID: "CreateOrganization",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
},
Raw: r,
}
type (
Request = *OrganizationCreate
Params = CreateOrganizationParams
Response = CreateOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackCreateOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.CreateOrganization(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.CreateOrganization(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeCreateOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleCreateOrganizationInvitationRequest handles CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -4390,6 +4647,224 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool,
}
}
// handleGetOrganizationRequest handles GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetOrganization"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: GetOrganizationOperation,
ID: "GetOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeGetOrganizationParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response GetOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetOrganizationOperation,
OperationSummary: "Read an organization of which the caller is a member.",
OperationID: "GetOrganization",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
},
Raw: r,
}
type (
Request = struct{}
Params = GetOrganizationParams
Response = GetOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackGetOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetOrganization(ctx, params)
return response, err
},
)
} else {
response, err = s.h.GetOrganization(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeGetOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -5670,6 +6145,233 @@ func (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool
}
}
// handleListMyOrganizationsRequest handles ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
func (s *Server) handleListMyOrganizationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListMyOrganizations"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/organizations"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyOrganizationsOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ListMyOrganizationsOperation,
ID: "ListMyOrganizations",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListMyOrganizationsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeListMyOrganizationsParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response ListMyOrganizationsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListMyOrganizationsOperation,
OperationSummary: "List the organizations available to the current account.",
OperationID: "ListMyOrganizations",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListMyOrganizationsParams
Response = ListMyOrganizationsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListMyOrganizationsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListMyOrganizations(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListMyOrganizations(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeListMyOrganizationsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMySupportCasesRequest handles ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -8162,6 +8864,269 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap
}
}
// handleUpdateOrganizationRequest handles UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
func (s *Server) handleUpdateOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("UpdateOrganization"),
semconv.HTTPRequestMethodKey.String("PATCH"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateOrganizationOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: UpdateOrganizationOperation,
ID: "UpdateOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, UpdateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, UpdateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeUpdateOrganizationParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
request, rawBody, close, err := s.decodeUpdateOrganizationRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response UpdateOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: UpdateOrganizationOperation,
OperationSummary: "Change the profile of an organization.",
OperationID: "UpdateOrganization",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
},
Raw: r,
}
type (
Request = *OrganizationUpdate
Params = UpdateOrganizationParams
Response = UpdateOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackUpdateOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.UpdateOrganization(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.UpdateOrganization(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeUpdateOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleUpdateOrganizationInvitationRequest handles UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -29,6 +29,10 @@ type CreateOrganizationNeedRes interface {
createOrganizationNeedRes()
}
type CreateOrganizationRes interface {
createOrganizationRes()
}
type DeclineMyInvitationRes interface {
declineMyInvitationRes()
}
@@ -85,6 +89,10 @@ type GetOrganizationNeedRes interface {
getOrganizationNeedRes()
}
type GetOrganizationRes interface {
getOrganizationRes()
}
type ListMyConsentsRes interface {
listMyConsentsRes()
}
@@ -93,6 +101,10 @@ type ListMyInvitationsRes interface {
listMyInvitationsRes()
}
type ListMyOrganizationsRes interface {
listMyOrganizationsRes()
}
type ListMySupportCasesRes interface {
listMySupportCasesRes()
}
@@ -145,6 +157,10 @@ type UpdateOrganizationNeedRes interface {
updateOrganizationNeedRes()
}
type UpdateOrganizationRes interface {
updateOrganizationRes()
}
type ViewMyInvitationRes interface {
viewMyInvitationRes()
}
File diff suppressed because it is too large. Load diff
@@ -11,6 +11,7 @@ const (
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
@@ -25,12 +26,14 @@ const (
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
ListMyConsentsOperation OperationName = "ListMyConsents"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
@@ -42,6 +45,7 @@ const (
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UpdateOrganizationOperation OperationName = "UpdateOrganization"
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
@@ -503,6 +503,100 @@ func decodeCreateMySupportCaseParams(args [0]string, argsEscaped bool, r *http.R
return params, nil
}
// CreateOrganizationParams is parameters of CreateOrganization operation.
type CreateOrganizationParams struct {
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
// request by method, path, and body.
//
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
// not_found or 409 state_conflict. A replay does not repeat the side effect.
//
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
// precondition_required (nothing changed; read the resource again and retry), 422
// idempotency_key_reused, 429, and every 5xx.
//
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
// before any other key check; a running request with the same fingerprint returns 409
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
}
func unpackCreateOrganizationParams(packed middleware.Parameters) (params CreateOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "Idempotency-Key",
In: "header",
}
params.IdempotencyKey = packed[key].(string)
}
return params
}
func decodeCreateOrganizationParams(args [0]string, argsEscaped bool, r *http.Request) (params CreateOrganizationParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode header: Idempotency-Key.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "Idempotency-Key",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.IdempotencyKey = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 255,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.IdempotencyKey)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "Idempotency-Key",
In: "header",
Err: err,
}
}
return params, nil
}
// CreateOrganizationInvitationParams is parameters of CreateOrganizationInvitation operation.
type CreateOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -1447,6 +1541,75 @@ func decodeGetMySupportCaseParams(args [1]string, argsEscaped bool, r *http.Requ
return params, nil
}
// GetOrganizationParams is parameters of GetOrganization operation.
type GetOrganizationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
}
func unpackGetOrganizationParams(packed middleware.Parameters) (params GetOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
return params
}
func decodeGetOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params GetOrganizationParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
return params, nil
}
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
type GetOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -2238,6 +2401,182 @@ func decodeListMyInvitationsParams(args [0]string, argsEscaped bool, r *http.Req
return params, nil
}
// ListMyOrganizationsParams is parameters of ListMyOrganizations operation.
type ListMyOrganizationsParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
// `page.has_more` to detect the end.
Limit OptInt32 `json:",omitempty,omitzero"`
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
Cursor OptString `json:",omitempty,omitzero"`
}
func unpackListMyOrganizationsParams(packed middleware.Parameters) (params ListMyOrganizationsParams) {
{
key := middleware.ParameterKey{
Name: "limit",
In: "query",
}
if v, ok := packed[key]; ok {
params.Limit = v.(OptInt32)
}
}
{
key := middleware.ParameterKey{
Name: "cursor",
In: "query",
}
if v, ok := packed[key]; ok {
params.Cursor = v.(OptString)
}
}
return params
}
func decodeListMyOrganizationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyOrganizationsParams, _ error) {
q := uri.NewQueryDecoder(r.URL.Query())
// Set default value for query: limit.
{
val := int32(20)
params.Limit.SetTo(val)
}
// Decode query: limit.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "limit",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotLimitVal int32
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt32(val)
if err != nil {
return err
}
paramsDotLimitVal = c
return nil
}(); err != nil {
return err
}
params.Limit.SetTo(paramsDotLimitVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Limit.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 100,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "limit",
In: "query",
Err: err,
}
}
// Decode query: cursor.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "cursor",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotCursorVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotCursorVal = c
return nil
}(); err != nil {
return err
}
params.Cursor.SetTo(paramsDotCursorVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Cursor.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 512,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "cursor",
In: "query",
Err: err,
}
}
return params, nil
}
// ListMySupportCasesParams is parameters of ListMySupportCases operation.
type ListMySupportCasesParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
@@ -3535,6 +3874,75 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h
return params, nil
}
// UpdateOrganizationParams is parameters of UpdateOrganization operation.
type UpdateOrganizationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
}
func unpackUpdateOrganizationParams(packed middleware.Parameters) (params UpdateOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
return params
}
func decodeUpdateOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params UpdateOrganizationParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
return params, nil
}
// UpdateOrganizationInvitationParams is parameters of UpdateOrganizationInvitation operation.
type UpdateOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -409,6 +409,85 @@ func (s *Server) decodeCreateMySupportCaseRequest(r *http.Request) (
}
}
func (s *Server) decodeCreateOrganizationRequest(r *http.Request) (
req *OrganizationCreate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationCreate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCreateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationCreate,
rawBody []byte,
@@ -1278,6 +1357,85 @@ func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) (
}
}
func (s *Server) decodeUpdateOrganizationRequest(r *http.Request) (
req *OrganizationUpdate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationUpdate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeUpdateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationUpdate,
rawBody []byte,
@@ -657,6 +657,133 @@ func encodeCreateMySupportCaseResponse(response CreateMySupportCaseRes, w http.R
}
}
func encodeCreateOrganizationResponse(response CreateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(201)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationConflict:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(409)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationUnprocessableEntity:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(422)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeCreateOrganizationInvitationResponse(response CreateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -1769,6 +1896,89 @@ func encodeGetMySupportCaseResponse(response GetMySupportCaseRes, w http.Respons
}
}
func encodeGetOrganizationResponse(response GetOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -2161,6 +2371,77 @@ func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.Respo
}
}
func encodeListMyOrganizationsResponse(response ListMyOrganizationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *MyOrganizationListHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeListMySupportCasesResponse(response ListMySupportCasesRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SupportCaseListHeaders:
@@ -3282,6 +3563,133 @@ func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes
}
}
func encodeUpdateOrganizationResponse(response UpdateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationPreconditionFailed:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(412)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeUpdateOrganizationInvitationResponse(response UpdateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -60,6 +60,7 @@ var operationRolesSessionCookie = map[string][]string{
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
@@ -72,11 +73,13 @@ var operationRolesSessionCookie = map[string][]string{
GetMyInvitationOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
ListMyConsentsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
@@ -85,6 +88,7 @@ var operationRolesSessionCookie = map[string][]string{
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
@@ -118,6 +122,7 @@ var operationRolesSessionCsrf = map[string][]string{
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
@@ -127,6 +132,7 @@ var operationRolesSessionCsrf = map[string][]string{
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
@@ -253,6 +253,36 @@ type Handler interface {
//
// POST /api/v1/me/support-cases
CreateMySupportCase(ctx context.Context, req SupportCaseCreate, params CreateMySupportCaseParams) (CreateMySupportCaseRes, error)
// CreateOrganization implements CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (CreateOrganizationRes, error)
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -608,6 +638,30 @@ type Handler interface {
//
// GET /api/v1/me/support-cases/{case_id}
GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error)
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -765,6 +819,35 @@ type Handler interface {
//
// GET /api/v1/me/invitations
ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (ListMyInvitationsRes, error)
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (ListMyOrganizationsRes, error)
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -1086,6 +1169,42 @@ type Handler interface {
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/answers
SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error)
// UpdateOrganization implements UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (UpdateOrganizationRes, error)
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -273,6 +273,39 @@ func (UnimplementedHandler) CreateMySupportCase(ctx context.Context, req Support
return r, ht.ErrNotImplemented
}
// CreateOrganization implements CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
func (UnimplementedHandler) CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (r CreateOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -670,6 +703,33 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
return r, ht.ErrNotImplemented
}
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrganizationParams) (r GetOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -845,6 +905,38 @@ func (UnimplementedHandler) ListMyInvitations(ctx context.Context, params ListMy
return r, ht.ErrNotImplemented
}
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
func (UnimplementedHandler) ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (r ListMyOrganizationsRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -1199,6 +1291,45 @@ func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *A
return r, ht.ErrNotImplemented
}
// UpdateOrganization implements UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
func (UnimplementedHandler) UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (r UpdateOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
File diff suppressed because it is too large. Load diff