41 lines
1.1 KiB
Go
41 lines
1.1 KiB
Go
package user
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"example.com/userService/internal/types"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func (s *Service) ExportUser(ctx context.Context, req *types.UserIDReq) (*types.ExportResp, error) {
|
|
u, err := s.GetUser(ctx, req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
payload, err := json.Marshal(u)
|
|
if err != nil {
|
|
return nil, s.failure(ctx, err)
|
|
}
|
|
var nonce [16]byte
|
|
if _, err = rand.Read(nonce[:]); err != nil {
|
|
return nil, s.failure(ctx, err)
|
|
}
|
|
key := fmt.Sprintf("exports/users/%d/%s.txt", u.ID, hex.EncodeToString(nonce[:]))
|
|
if _, err = s.deps.Uploads.Put(ctx, key, strings.NewReader(string(payload)), int64(len(payload)), "text/plain"); err != nil {
|
|
return nil, s.failure(ctx, err)
|
|
}
|
|
url, err := s.deps.Downloads.PresignGet(ctx, key, 5*time.Minute)
|
|
if err != nil {
|
|
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
|
|
defer cancel()
|
|
_ = s.deps.Files.Delete(cleanup, key)
|
|
return nil, s.failure(ctx, err)
|
|
}
|
|
s.deps.Logger.InfoContext(ctx, "user.exported", "userId", u.ID)
|
|
return &types.ExportResp{DownloadURL: url.String()}, nil
|
|
}
|