1package server
2
3import (
4 "github.com/Azure/go-autorest/autorest/to"
5 "github.com/google/uuid"
6 "github.com/haileyok/cocoon/internal/helpers"
7 "github.com/haileyok/cocoon/models"
8 "github.com/labstack/echo/v4"
9)
10
11type ComAtprotoServerCreateInviteCodesRequest struct {
12 CodeCount *int `json:"codeCount,omitempty"`
13 UseCount int `json:"useCount" validate:"required"`
14 ForAccounts *[]string `json:"forAccounts,omitempty"`
15}
16
17type ComAtprotoServerCreateInviteCodesResponse []ComAtprotoServerCreateInviteCodesItem
18
19type ComAtprotoServerCreateInviteCodesItem struct {
20 Account string `json:"account"`
21 Codes []string `json:"codes"`
22}
23
24func (s *Server) handleCreateInviteCodes(e echo.Context) error {
25 ctx := e.Request().Context()
26 logger := s.logger.With("name", "handleServerCreateInviteCodes")
27
28 var req ComAtprotoServerCreateInviteCodesRequest
29 if err := e.Bind(&req); err != nil {
30 logger.Error("error binding", "error", err)
31 return helpers.ServerError(e, nil)
32 }
33
34 if err := e.Validate(req); err != nil {
35 logger.Error("error validating", "error", err)
36 return helpers.InputError(e, nil)
37 }
38
39 if req.CodeCount == nil {
40 req.CodeCount = to.IntPtr(1)
41 }
42
43 if req.ForAccounts == nil {
44 req.ForAccounts = to.StringSlicePtr([]string{"admin"})
45 }
46
47 var codes []ComAtprotoServerCreateInviteCodesItem
48
49 for _, did := range *req.ForAccounts {
50 var ics []string
51
52 for range *req.CodeCount {
53 ic := uuid.NewString()
54 ics = append(ics, ic)
55
56 if err := s.db.Create(ctx, &models.InviteCode{
57 Code: ic,
58 Did: did,
59 RemainingUseCount: req.UseCount,
60 }, nil).Error; err != nil {
61 logger.Error("error creating invite code", "error", err)
62 return helpers.ServerError(e, nil)
63 }
64 }
65
66 codes = append(codes, ComAtprotoServerCreateInviteCodesItem{
67 Account: did,
68 Codes: ics,
69 })
70 }
71
72 return e.JSON(200, codes)
73}