Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ Authorization: Bearer <jwt-token>
| Method | Path | Description |
|---|---|---|
| GET | `/{uploadId}/status` | Poll file import progress and stats |
| POST | `/{uploadId}/map` | Apply column mapping after initial upload |
| POST | `/{uploadId}/map` | Import an upload whose headers didn't match, using a column mapping (see File Import) |

### Templates — `/api/templates`

Expand All @@ -530,7 +530,7 @@ Authorization: Bearer <jwt-token>
| PUT | `/{id}` | Update template |
| DELETE | `/{id}` | Delete template |
| POST | `/{id}/duplicate` | Clone template (appends " (Copy)") |
| POST | `/upload-html` | Parse a raw `.html` file, returns the HTML string |
| POST | `/upload-html` | Read an `.html`/`.htm` file (UTF-8), returns the HTML string; other files get 400 |

### Image Upload — `/api/upload`

Expand Down Expand Up @@ -699,6 +699,15 @@ Once an email is in the suppression list it can never be imported or sent to aga
- **XLS:** legacy format, at most 65,536 rows. Formulas are evaluated.
- **Columns:** `email`, `first_name` and `last_name` are required. Case and order don't matter, and extra columns are ignored.

**Column mapping.** If the headers don't include those three, nothing is imported yet: the upload ends `failed` with `needsMapping: true`, and the status lists the file's `columns` with a `preview` of the first row's values. The file is kept (for up to a day) until it is mapped:

```
POST /api/uploads/{uploadId}/map
{"mapping": {"E-mail": "email", "Given Name": "first_name", "Surname": "last_name", "Notes": "ignore"}}
```

Keys are the file's headers (any case) and values the fields; the other direction (`{"email": "E-mail", ...}`) works too. The import then runs with the mapping and the response has the real counts (`imported`, `skipped`, `duplicates`). A mapping naming a column that isn't in the file, or leaving a field unmapped, gets 400 and the upload can be mapped again; an upload that is already imported gets 409.

**Per row**, each row is handled on its own, so one bad row never fails the file:

```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.mailengine.mailengine.service.CampaignService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
Expand Down Expand Up @@ -115,7 +116,7 @@ public ResponseEntity<Map<String, String>> sendCampaign(@PathVariable Long id) {
@PostMapping("/{id}/test")
public ResponseEntity<Map<String, String>> sendTestEmail(
@PathVariable Long id,
@RequestBody TestEmailRequest request
@Valid @RequestBody TestEmailRequest request
) {
campaignSendingService.sendTestEmail(id, request.testEmails());
return ResponseEntity.ok(Map.of("message", "Test email sent"));
Expand Down Expand Up @@ -160,6 +161,6 @@ public ResponseEntity<Map<String, String>> resumeCampaign(@PathVariable Long id)
// Request body for the test send endpoint.
// A Java record keeps it concise — no need for a separate file.
record TestEmailRequest(
@NotEmpty List<@Email String> testEmails
@NotEmpty List<@NotBlank @Email String> testEmails
) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@
import com.mailengine.mailengine.entity.FileUpload;
import com.mailengine.mailengine.exception.BadRequestException;
import com.mailengine.mailengine.exception.ResourceNotFoundException;
import com.mailengine.mailengine.entity.enums.UploadStatus;
import com.mailengine.mailengine.repository.FileUploadRepository;
import com.mailengine.mailengine.repository.PendingUploadFileRepository;
import com.mailengine.mailengine.service.FileUploadService;
import com.mailengine.mailengine.service.TemplateService;
import lombok.RequiredArgsConstructor;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
Expand All @@ -29,6 +33,7 @@ public class UploadController {
private final TemplateService templateService;
private final FileUploadService fileUploadService;
private final FileUploadRepository fileUploadRepository;
private final PendingUploadFileRepository pendingUploadFileRepository;

@PostMapping("/upload/image")
public ResponseEntity<Map<String, String>> uploadImage(
Expand Down Expand Up @@ -73,7 +78,8 @@ public ResponseEntity<UploadStatusResponse> getUploadStatus(@PathVariable Long u
upload.getTotalRows(),
upload.getImportedRows(),
upload.getSkippedRows(),
upload.getDuplicateRows()
upload.getDuplicateRows(),
upload.getStatus() == UploadStatus.failed && pendingUploadFileRepository.existsById(uploadId)
));
}

Expand All @@ -92,7 +98,7 @@ public ResponseEntity<UploadStatusResponse> getUploadStatus(@PathVariable Long u
* @throws BadRequestException if the "mapping" key in the request body is null or empty
*/
@PostMapping("/uploads/{uploadId}/map")
public ResponseEntity<Map<String, Object>> applyColumnMapping(
public ResponseEntity<?> applyColumnMapping(
@PathVariable Long uploadId,
@RequestBody Map<String, Map<String, String>> body) {

Expand All @@ -101,7 +107,14 @@ public ResponseEntity<Map<String, Object>> applyColumnMapping(
throw new BadRequestException("mapping is required");
}

FileUploadService.ImportResult result = fileUploadService.applyMapping(uploadId, mapping);
FileUploadService.ImportResult result;
try {
result = fileUploadService.applyMapping(uploadId, mapping);
} catch (TaskRejectedException busy) {
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(Map.of(
"uploadId", uploadId,
"message", "Too many imports are in progress. Please try again in a few minutes."));
}

return ResponseEntity.ok(Map.of(
"imported", result.imported() != null ? result.imported() : 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class UploadStatusResponse {

private UploadStatus status;

/** First 5 rows of the uploaded file for the column-mapping UI. */
/** Each column with its value in the file's first data row, for the column-mapping UI. */
private List<Map<String, String>> preview;

/** Detected column headers — frontend maps these to system fields. */
Expand All @@ -23,4 +23,10 @@ public class UploadStatusResponse {
private Integer importedRows;
private Integer skippedRows;
private Integer duplicateRows;

/**
* The file's headers aren't email/first_name/last_name: nothing was imported yet. Map its {@code columns}
* with POST /api/uploads/{id}/map to import it.
*/
private boolean needsMapping;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.mailengine.mailengine.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/** The file of an upload waiting for its columns to be mapped (see FileUploadService#applyMapping). */
@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "pending_upload_files")
public class PendingUploadFile {

@Id
@Column(name = "upload_id")
private Long uploadId;

@Column(name = "file_name")
private String fileName;

@Column(name = "content", nullable = false)
private byte[] content;

public PendingUploadFile(Long uploadId, String fileName, byte[] content) {
this.uploadId = uploadId;
this.fileName = fileName;
this.content = content;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,13 @@ public interface FileUploadRepository extends JpaRepository<FileUpload, Long> {
@Modifying
@Query("update FileUpload u set u.status = :to where u.status = :from")
int updateStatus(@Param("from") UploadStatus from, @Param("to") UploadStatus to);

/**
* Moves one upload from {@code from} to {@code to} only if it is still in {@code from}; returns 1 if this
* caller won. Two requests to map the same upload at once: only one of them gets to import it.
*/
@Transactional
@Modifying
@Query("update FileUpload u set u.status = :to where u.id = :id and u.status = :from")
int claim(@Param("id") Long id, @Param("from") UploadStatus from, @Param("to") UploadStatus to);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.mailengine.mailengine.repository;

import com.mailengine.mailengine.entity.PendingUploadFile;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

public interface PendingUploadFileRepository extends JpaRepository<PendingUploadFile, Long> {

/** Files nobody mapped within a day (the comparison runs in the database, in its own clock). */
@Transactional
@Modifying
@Query(value = "DELETE FROM pending_upload_files WHERE created_at < NOW() - INTERVAL '1 day'", nativeQuery = true)
int deleteOlderThanOneDay();
}
26 changes: 26 additions & 0 deletions src/main/java/com/mailengine/mailengine/security/TokenHashing.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.mailengine.mailengine.security;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;

/**
* One-time tokens (password reset, email verification) are stored as their SHA-256, never as sent:
* someone who can read the database cannot use what they find there. The tokens are long random
* values, so a plain (unsalted) hash is enough to look them up by.
*/
public final class TokenHashing {

private TokenHashing() {
}

public static String sha256Hex(String token) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 is always available", e);
}
}
}
10 changes: 6 additions & 4 deletions src/main/java/com/mailengine/mailengine/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import com.mailengine.mailengine.repository.UserRepository;
import com.mailengine.mailengine.security.JwtService;
import com.mailengine.mailengine.security.SecurityUtils;
import com.mailengine.mailengine.security.TokenHashing;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -42,7 +43,7 @@ public void register(RegisterRequest request) {
}

public void verifyEmail(String token) {
EmailVerificationToken evt = verificationTokenRepository.findByToken(token)
EmailVerificationToken evt = verificationTokenRepository.findByToken(TokenHashing.sha256Hex(token))
.orElseThrow(() -> new BadRequestException("Invalid or expired verification link"));

if (evt.isUsed() || evt.isExpired()) {
Expand Down Expand Up @@ -129,14 +130,15 @@ public void forgotPassword(ForgotPasswordRequest request) {
userRepository.findByEmailIgnoreCase(normalizeEmail(request.getEmail())).ifPresent(user -> {
passwordResetTokenRepository.deleteByUserId(user.getId());
String token = UUID.randomUUID().toString();
passwordResetTokenRepository.save(
new PasswordResetToken(token, user, Instant.now().plus(1, ChronoUnit.HOURS)));
// Only the hash is stored; the token itself exists only in the email
passwordResetTokenRepository.save(new PasswordResetToken(
TokenHashing.sha256Hex(token), user, Instant.now().plus(1, ChronoUnit.HOURS)));
emailService.sendPasswordResetEmail(user.getEmail(), token);
});
}

public void resetPassword(ResetPasswordRequest request) {
PasswordResetToken prt = passwordResetTokenRepository.findByToken(request.getToken())
PasswordResetToken prt = passwordResetTokenRepository.findByToken(TokenHashing.sha256Hex(request.getToken()))
.orElseThrow(() -> new BadRequestException("Invalid or expired reset link"));
if (prt.isUsed() || prt.isExpired()) {
throw new BadRequestException("Reset link has expired or already been used");
Expand Down
Loading
Loading