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 var req ComAtprotoServerCreateInviteCodesRequest
26 if err := e.Bind(&req); err != nil {
27 s.logger.Error("error binding", "error", err)
28 return helpers.ServerError(e, nil)
29 }
30
31 if err := e.Validate(req); err != nil {
32 s.logger.Error("error validating", "error", err)
33 return helpers.InputError(e, nil)
34 }
35
36 if req.CodeCount == nil {
37 req.CodeCount = to.IntPtr(1)
38 }
39
40 if req.ForAccounts == nil {
41 req.ForAccounts = to.StringSlicePtr([]string{"admin"})
42 }
43
44 var codes []ComAtprotoServerCreateInviteCodesItem
45
46 for _, did := range *req.ForAccounts {
47 var ics []string
48
49 for range *req.CodeCount {
50 ic := uuid.NewString()
51 ics = append(ics, ic)
52
53 if err := s.db.Create(&models.InviteCode{
54 Code: ic,
55 Did: did,
56 RemainingUseCount: req.UseCount,
57 }, nil).Error; err != nil {
58 s.logger.Error("error creating invite code", "error", err)
59 return helpers.ServerError(e, nil)
60 }
61 }
62
63 codes = append(codes, ComAtprotoServerCreateInviteCodesItem{
64 Account: did,
65 Codes: ics,
66 })
67 }
68
69 return e.JSON(200, codes)
70}