1 package com.nilhcem.fakesmtp.server;
2
3 import org.subethamail.smtp.AuthenticationHandler;
4 import org.subethamail.smtp.MessageContext;
5
6 import java.util.Optional;
7
8
9 /**
10 * Simulates an authentication handler to allow capturing emails that are set up with login authentication.
11 *
12 * @author jasonpenny
13 * @since 1.2
14 */
15 /*package*/ final class SMTPAuthHandler implements AuthenticationHandler {
16 private static final String USER_IDENTITY = "User";
17 private static final String PROMPT_USERNAME = "334 VXNlcm5hbWU6"; // VXNlcm5hbWU6 is base64 for "Username:"
18 private static final String PROMPT_PASSWORD = "334 UGFzc3dvcmQ6"; // UGFzc3dvcmQ6 is base64 for "Password:"
19
20 private int pass = 0;
21
22 /**
23 * Simulates an authentication process.
24 * <p>
25 * <ul>
26 * <li>first prompts for username;</li>
27 * <li>then, prompts for password;</li>
28 * <li>finally, returns {@code null} to finish the authentication process;</li>
29 * </ul>
30 * </p>
31 *
32 * @return <code>null</code> if the authentication process is finished, otherwise a string to hand back to the client.
33 * @param clientInput The client's input, eg "AUTH PLAIN dGVzdAB0ZXN0ADEyMzQ="
34 */
35 @Override
36 public Optional<String> auth(String clientInput, MessageContext messageContext) {
37 String prompt;
38
39 if (++pass == 1) {
40 prompt = SMTPAuthHandler.PROMPT_USERNAME;
41 } else if (pass == 2) {
42 prompt = SMTPAuthHandler.PROMPT_PASSWORD;
43 } else {
44 pass = 0;
45 return Optional.empty();
46 }
47 return Optional.of(prompt);
48 }
49
50 /**
51 * If the authentication process was successful, this returns the identity
52 * of the user. The type defining the identity can vary depending on the
53 * authentication mechanism used, but typically this returns a String username.
54 * If authentication was not successful, the return value is undefined.
55 */
56 @Override
57 public Object getIdentity() {
58 return SMTPAuthHandler.USER_IDENTITY;
59 }
60 }