mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 01:53:42 +01:00
218 lines
8.7 KiB
Go
218 lines
8.7 KiB
Go
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/url"
|
|
"text/template"
|
|
"time"
|
|
|
|
"github.com/oapi-codegen/nullable"
|
|
"github.com/phishingclub/phishingclub/data"
|
|
"github.com/phishingclub/phishingclub/errs"
|
|
"github.com/phishingclub/phishingclub/model"
|
|
"github.com/phishingclub/phishingclub/vo"
|
|
)
|
|
|
|
// reportPreviewTimeout bounds a preview, the browser download on first use
|
|
// included. It is below the 3 minute timeout of the preview route.
|
|
const reportPreviewTimeout = 150 * time.Second
|
|
|
|
// PreviewPDF renders content, a report template, with sample data into a PDF
|
|
// the same way a campaign report is rendered, so the result shows the real
|
|
// page size, fonts and page breaks. kind picks the sample data: simulation,
|
|
// training or program. A template that does not parse or run returns a
|
|
// validation error with the reason.
|
|
func (s *ReportTemplate) PreviewPDF(
|
|
ctx context.Context,
|
|
session *model.Session,
|
|
content string,
|
|
kind string,
|
|
) ([]byte, error) {
|
|
ae := NewAuditEvent("ReportTemplate.PreviewPDF", session)
|
|
isAuthorized, err := IsAuthorized(session, data.PERMISSION_ALLOW_GLOBAL)
|
|
if err != nil && !errors.Is(err, errs.ErrAuthorizationFailed) {
|
|
s.LogAuthError(err)
|
|
return nil, errs.Wrap(err)
|
|
}
|
|
if !isAuthorized {
|
|
s.AuditLogNotAuthorized(ae)
|
|
return nil, errs.ErrAuthorizationFailed
|
|
}
|
|
// the same size limit as a stored template
|
|
if _, err := vo.NewOptionalString1MB(content); err != nil {
|
|
return nil, errs.NewValidationError(err)
|
|
}
|
|
html, err := renderReportPreviewKind(content, kind)
|
|
if err != nil {
|
|
return nil, errs.NewValidationError(err)
|
|
}
|
|
// a page that never finishes, such as an endless script, is stopped
|
|
// before the route's write deadline
|
|
ctx, cancel := context.WithTimeout(ctx, reportPreviewTimeout)
|
|
defer cancel()
|
|
rb := newReportBrowser(ctx, s.RemoteBrowserExecPath, s.Logger)
|
|
defer rb.close()
|
|
rb.useAssets(loadReportAssets(ctx, s.DomainService, nil, s.Logger))
|
|
pdf, err := rb.renderPDF(html)
|
|
if err != nil {
|
|
s.Logger.Errorw("failed to render report preview PDF", "error", err)
|
|
return nil, errs.Wrap(err)
|
|
}
|
|
// no audit log on read
|
|
return pdf, nil
|
|
}
|
|
|
|
// renderReportPreviewKind renders content with the sample data of a report
|
|
// kind, escaped the way a real report of that kind is.
|
|
func renderReportPreviewKind(content string, kind string) (string, error) {
|
|
switch kind {
|
|
case model.ReportKindProgram:
|
|
return renderProgramReportContent(content, programReportSampleData())
|
|
case model.ReportKindTraining:
|
|
return renderReportPreview(content, true)
|
|
case model.ReportKindSimulation, "":
|
|
return renderReportPreview(content, false)
|
|
}
|
|
return "", fmt.Errorf("unknown report kind")
|
|
}
|
|
|
|
// renderReportPreview renders content with the sample report data, escaped
|
|
// the way a campaign report is.
|
|
func renderReportPreview(content string, isTraining bool) (string, error) {
|
|
tmpl, err := template.New("report").Funcs(TemplateFuncs()).Parse(content)
|
|
if err != nil {
|
|
return "", fmt.Errorf("template does not parse: %w", err)
|
|
}
|
|
var buf bytes.Buffer
|
|
if err := tmpl.Execute(&buf, htmlEscapeReportData(reportSampleData(isTraining))); err != nil {
|
|
return "", fmt.Errorf("template does not run: %w", err)
|
|
}
|
|
return buf.String(), nil
|
|
}
|
|
|
|
// reportScreenshotPlaceholder is a grey SVG data URI standing in for a
|
|
// screenshot in the sample report data.
|
|
func reportScreenshotPlaceholder(label string) string {
|
|
svg := `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="500" viewBox="0 0 800 500">` +
|
|
`<rect width="800" height="500" fill="#f3f4f6"/>` +
|
|
`<rect x="12" y="12" width="776" height="476" fill="none" stroke="#d1d5db" stroke-width="2" stroke-dasharray="10 8"/>` +
|
|
`<text x="400" y="240" text-anchor="middle" font-family="sans-serif" font-size="30" fill="#6b7280">` + label + `</text>` +
|
|
`<text x="400" y="282" text-anchor="middle" font-family="sans-serif" font-size="18" fill="#9ca3af">Sample placeholder</text>` +
|
|
`</svg>`
|
|
return "data:image/svg+xml," + url.PathEscape(svg)
|
|
}
|
|
|
|
// reportSampleData is the report data a template preview is rendered with. It
|
|
// matches the sample data of the report editor preview.
|
|
func reportSampleData(isTraining bool) *model.ReportData {
|
|
var templates []model.ReportCampaignTemplate
|
|
var shots []model.ReportTemplateScreenshots
|
|
for n := 1; n <= 2; n++ {
|
|
t := model.ReportCampaignTemplate{
|
|
Number: n,
|
|
Name: fmt.Sprintf("Sample template %d", n),
|
|
Domain: fmt.Sprintf("sample%d.test", n),
|
|
EmailFrom: fmt.Sprintf("it-support@sample%d.test", n),
|
|
EmailSubject: fmt.Sprintf("Sample subject for template %d", n),
|
|
}
|
|
templates = append(templates, t)
|
|
shots = append(shots, model.ReportTemplateScreenshots{
|
|
Number: n,
|
|
Name: t.Name,
|
|
Email: reportScreenshotPlaceholder(fmt.Sprintf("Template %d: email screenshot", n)),
|
|
Domain: t.Domain,
|
|
EmailFrom: t.EmailFrom,
|
|
EmailSubject: t.EmailSubject,
|
|
BeforeLandingPage: reportScreenshotPlaceholder(fmt.Sprintf("Template %d: before landing page screenshot", n)),
|
|
LandingPage: reportScreenshotPlaceholder(fmt.Sprintf("Template %d: landing page screenshot", n)),
|
|
AfterLandingPage: reportScreenshotPlaceholder(fmt.Sprintf("Template %d: after landing page screenshot", n)),
|
|
})
|
|
}
|
|
// the sample is built from counts by the same code as a real report, so
|
|
// every percent and rate in the preview is what a real report would show
|
|
group := func(name string, total, clicked, submitted, reported, started, completed int, suppressed bool) model.CampaignGroupStat {
|
|
return model.CampaignGroupStat{
|
|
Group: name,
|
|
Total: total,
|
|
Clicked: clicked,
|
|
Submitted: submitted,
|
|
Reported: reported,
|
|
TrainingStarted: started,
|
|
TrainingCompleted: completed,
|
|
Suppressed: suppressed,
|
|
}
|
|
}
|
|
stats := &model.CampaignResultView{
|
|
Recipients: 120,
|
|
EmailsSent: 118,
|
|
TrackingPixelLoaded: 74,
|
|
WebsiteLoaded: 32,
|
|
SubmittedData: 14,
|
|
Reported: 8,
|
|
}
|
|
departments := []model.CampaignGroupStat{
|
|
group("Engineering", 70, 21, 9, 11, 0, 0, false),
|
|
group("Sales", 49, 20, 10, 4, 0, 0, false),
|
|
group("Other (small groups)", 1, 0, 0, 0, 0, 0, true),
|
|
}
|
|
positions := []model.CampaignGroupStat{
|
|
group("Head of operations", 40, 12, 5, 6, 0, 0, false),
|
|
group("Account Executive", 35, 14, 7, 3, 0, 0, false),
|
|
group("Other (small groups)", 1, 0, 0, 0, 0, 0, true),
|
|
}
|
|
languages := []model.CampaignGroupStat{
|
|
group("English", 64, 18, 8, 5, 0, 0, false),
|
|
group("German", 41, 10, 4, 2, 0, 0, false),
|
|
group("Danish", 15, 4, 2, 1, 0, 0, false),
|
|
}
|
|
recipients := []model.ReportRecipient{
|
|
{FirstName: "Alice", LastName: "Andersen", Email: "alice@worldcorp.test", Department: "Research and Development", Position: "Head of operations", ClickedLink: true, SubmittedData: true},
|
|
{FirstName: "Bob", LastName: "Berg", Email: "bob@worldcorp.test", Department: "Sales", Position: "Account Executive", ClickedLink: true},
|
|
{FirstName: "Carol", LastName: "Chan", Email: "carol@worldcorp.test", Department: "Finance", Position: "Analyst", Reported: true},
|
|
}
|
|
campaignName := "Q1 Phishing Simulation"
|
|
if isTraining {
|
|
campaignName = "Q1 Awareness Training"
|
|
stats.TrainingStarted = 52
|
|
stats.TrainingCompleted = 41
|
|
departments = []model.CampaignGroupStat{
|
|
group("Engineering", 70, 0, 0, 0, 31, 25, false),
|
|
group("Sales", 49, 0, 0, 0, 21, 16, false),
|
|
group("Other (small groups)", 1, 0, 0, 0, 0, 0, true),
|
|
}
|
|
languages = []model.CampaignGroupStat{
|
|
group("English", 64, 0, 0, 0, 29, 23, false),
|
|
group("German", 41, 0, 0, 0, 17, 13, false),
|
|
group("Danish", 15, 0, 0, 0, 6, 5, false),
|
|
}
|
|
for i := range recipients {
|
|
recipients[i].TrainingStarted = i < 2
|
|
recipients[i].TrainingCompleted = i == 0
|
|
}
|
|
}
|
|
campaign := &model.Campaign{IsTraining: nullable.NewNullableWithValue(isTraining)}
|
|
rd := buildReportData(campaignName, "World Corp", campaign, stats, recipients, departments, "Department", departments, positions)
|
|
rd.CampaignStartDate = "2025-01-01"
|
|
rd.CampaignEndDate = "2025-01-31"
|
|
rd.CampaignClosedAt = "2025-02-01"
|
|
loc := InstallLocation()
|
|
rd.DeliveryStartUnix = time.Date(2025, time.January, 1, 9, 0, 0, 0, loc).Unix()
|
|
rd.DeliveryEndUnix = time.Date(2025, time.January, 31, 16, 0, 0, 0, loc).Unix()
|
|
rd.ClosedUnix = time.Date(2025, time.February, 1, 9, 0, 0, 0, loc).Unix()
|
|
rd.LanguageGroups = toReportGroupStats(languages)
|
|
rd.Templates = templates
|
|
rd.TemplateScreenshots = shots
|
|
rd.TemplateCount = len(templates)
|
|
rd.Domain = templates[0].Domain
|
|
rd.EmailFrom = templates[0].EmailFrom
|
|
rd.EmailSubject = templates[0].EmailSubject
|
|
rd.EmailScreenshot = shots[0].Email
|
|
rd.BeforeLandingPageScreenshot = shots[0].BeforeLandingPage
|
|
rd.LandingPageScreenshot = shots[0].LandingPage
|
|
rd.AfterLandingPageScreenshot = shots[0].AfterLandingPage
|
|
return rd
|
|
}
|