-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
FreeMarkerEmailTemplateProvider.java
executable file
·304 lines (256 loc) · 11.7 KB
/
FreeMarkerEmailTemplateProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.email.freemarker;
import java.io.IOException;
import java.net.URI;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import org.keycloak.broker.provider.BrokeredIdentityContext;
import org.keycloak.common.util.ObjectUtil;
import org.keycloak.email.EmailException;
import org.keycloak.email.EmailSenderProvider;
import org.keycloak.email.EmailTemplateProvider;
import org.keycloak.email.freemarker.beans.EventBean;
import org.keycloak.email.freemarker.beans.ProfileBean;
import org.keycloak.events.Event;
import org.keycloak.events.EventType;
import org.keycloak.forms.login.freemarker.model.UrlBean;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakUriInfo;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.theme.FreeMarkerException;
import org.keycloak.theme.FreeMarkerUtil;
import org.keycloak.theme.Theme;
import org.keycloak.theme.beans.LinkExpirationFormatterMethod;
import org.keycloak.theme.beans.MessageFormatterMethod;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class FreeMarkerEmailTemplateProvider implements EmailTemplateProvider {
protected KeycloakSession session;
/**
* authenticationSession can be null for some email sendings, it is filled only for email sendings performed as part of the authentication session (email verification, password reset, broker link
* etc.)!
*/
protected AuthenticationSessionModel authenticationSession;
protected FreeMarkerUtil freeMarker;
protected RealmModel realm;
protected UserModel user;
protected final Map<String, Object> attributes = new HashMap<>();
public FreeMarkerEmailTemplateProvider(KeycloakSession session, FreeMarkerUtil freeMarker) {
this.session = session;
this.freeMarker = freeMarker;
}
@Override
public EmailTemplateProvider setRealm(RealmModel realm) {
this.realm = realm;
return this;
}
@Override
public EmailTemplateProvider setUser(UserModel user) {
this.user = user;
return this;
}
@Override
public EmailTemplateProvider setAttribute(String name, Object value) {
attributes.put(name, value);
return this;
}
@Override
public EmailTemplateProvider setAuthenticationSession(AuthenticationSessionModel authenticationSession) {
this.authenticationSession = authenticationSession;
return this;
}
protected String getRealmName() {
if (realm.getDisplayName() != null) {
return realm.getDisplayName();
} else {
return ObjectUtil.capitalize(realm.getName());
}
}
@Override
public void sendEvent(Event event) throws EmailException {
Map<String, Object> attributes = new HashMap<>();
attributes.put("user", new ProfileBean(user));
attributes.put("event", new EventBean(event));
send(toCamelCase(event.getType()) + "Subject", "event-" + event.getType().toString().toLowerCase() + ".ftl", attributes);
}
@Override
public void sendPasswordReset(String link, long expirationInMinutes) throws EmailException {
Map<String, Object> attributes = new HashMap<>(this.attributes);
attributes.put("user", new ProfileBean(user));
addLinkInfoIntoAttributes(link, expirationInMinutes, attributes);
attributes.put("realmName", getRealmName());
send("passwordResetSubject", "password-reset.ftl", attributes);
}
@Override
public void sendSmtpTestEmail(Map<String, String> config, UserModel user) throws EmailException {
setRealm(session.getContext().getRealm());
setUser(user);
Map<String, Object> attributes = new HashMap<>(this.attributes);
attributes.put("user", new ProfileBean(user));
attributes.put("realmName", realm.getName());
EmailTemplate email = processTemplate("emailTestSubject", Collections.emptyList(), "email-test.ftl", attributes);
send(config, email.getSubject(), email.getTextBody(), email.getHtmlBody());
}
@Override
public void sendConfirmIdentityBrokerLink(String link, long expirationInMinutes) throws EmailException {
Map<String, Object> attributes = new HashMap<>(this.attributes);
attributes.put("user", new ProfileBean(user));
addLinkInfoIntoAttributes(link, expirationInMinutes, attributes);
attributes.put("realmName", getRealmName());
BrokeredIdentityContext brokerContext = (BrokeredIdentityContext) this.attributes.get(IDENTITY_PROVIDER_BROKER_CONTEXT);
String idpAlias = brokerContext.getIdpConfig().getAlias();
String idpDisplayName = brokerContext.getIdpConfig().getDisplayName();
idpAlias = ObjectUtil.capitalize(idpAlias);
if (idpDisplayName != null) {
idpAlias = ObjectUtil.capitalize(idpDisplayName);
}
attributes.put("identityProviderContext", brokerContext);
attributes.put("identityProviderAlias", idpAlias);
List<Object> subjectAttrs = Arrays.asList(idpAlias);
send("identityProviderLinkSubject", subjectAttrs, "identity-provider-link.ftl", attributes);
}
@Override
public void sendExecuteActions(String link, long expirationInMinutes) throws EmailException {
Map<String, Object> attributes = new HashMap<>(this.attributes);
attributes.put("user", new ProfileBean(user));
addLinkInfoIntoAttributes(link, expirationInMinutes, attributes);
attributes.put("realmName", getRealmName());
send("executeActionsSubject", "executeActions.ftl", attributes);
}
@Override
public void sendVerifyEmail(String link, long expirationInMinutes) throws EmailException {
Map<String, Object> attributes = new HashMap<>(this.attributes);
attributes.put("user", new ProfileBean(user));
addLinkInfoIntoAttributes(link, expirationInMinutes, attributes);
attributes.put("realmName", getRealmName());
send("emailVerificationSubject", "email-verification.ftl", attributes);
}
/**
* Add link info into template attributes.
*
* @param link to add
* @param expirationInMinutes to add
* @param attributes to add link info into
*/
protected void addLinkInfoIntoAttributes(String link, long expirationInMinutes, Map<String, Object> attributes) throws EmailException {
attributes.put("link", link);
attributes.put("linkExpiration", expirationInMinutes);
KeycloakUriInfo uriInfo = session.getContext().getUri();
URI baseUri = uriInfo.getBaseUri();
try {
Locale locale = session.getContext().resolveLocale(user);
attributes.put("linkExpirationFormatter", new LinkExpirationFormatterMethod(getTheme().getMessages(locale), locale));
attributes.put("url", new UrlBean(realm, getTheme(), baseUri, null));
} catch (IOException e) {
throw new EmailException("Failed to template email", e);
}
}
@Override
public void send(String subjectFormatKey, String bodyTemplate, Map<String, Object> bodyAttributes) throws EmailException {
send(subjectFormatKey, Collections.emptyList(), bodyTemplate, bodyAttributes);
}
protected EmailTemplate processTemplate(String subjectKey, List<Object> subjectAttributes, String template, Map<String, Object> attributes) throws EmailException {
try {
Theme theme = getTheme();
Locale locale = session.getContext().resolveLocale(user);
attributes.put("locale", locale);
Properties rb = new Properties();
rb.putAll(theme.getMessages(locale));
rb.putAll(realm.getRealmLocalizationTextsByLocale(locale.toLanguageTag()));
attributes.put("msg", new MessageFormatterMethod(locale, rb));
attributes.put("properties", theme.getProperties());
String subject = new MessageFormat(rb.getProperty(subjectKey, subjectKey), locale).format(subjectAttributes.toArray());
String textTemplate = String.format("text/%s", template);
String textBody;
try {
textBody = freeMarker.processTemplate(attributes, textTemplate, theme);
} catch (final FreeMarkerException e) {
throw new EmailException("Failed to template plain text email.", e);
}
String htmlTemplate = String.format("html/%s", template);
String htmlBody;
try {
htmlBody = freeMarker.processTemplate(attributes, htmlTemplate, theme);
} catch (final FreeMarkerException e) {
throw new EmailException("Failed to template html email.", e);
}
return new EmailTemplate(subject, textBody, htmlBody);
} catch (Exception e) {
throw new EmailException("Failed to template email", e);
}
}
protected Theme getTheme() throws IOException {
return session.theme().getTheme(Theme.Type.EMAIL);
}
@Override
public void send(String subjectFormatKey, List<Object> subjectAttributes, String bodyTemplate, Map<String, Object> bodyAttributes) throws EmailException {
try {
EmailTemplate email = processTemplate(subjectFormatKey, subjectAttributes, bodyTemplate, bodyAttributes);
send(email.getSubject(), email.getTextBody(), email.getHtmlBody());
} catch (EmailException e) {
throw e;
} catch (Exception e) {
throw new EmailException("Failed to template email", e);
}
}
protected void send(String subject, String textBody, String htmlBody) throws EmailException {
send(realm.getSmtpConfig(), subject, textBody, htmlBody);
}
protected void send(Map<String, String> config, String subject, String textBody, String htmlBody) throws EmailException {
EmailSenderProvider emailSender = session.getProvider(EmailSenderProvider.class);
emailSender.send(config, user, subject, textBody, htmlBody);
}
@Override
public void close() {
}
protected String toCamelCase(EventType event) {
StringBuilder sb = new StringBuilder("event");
for (String s : event.name().toLowerCase().split("_")) {
sb.append(ObjectUtil.capitalize(s));
}
return sb.toString();
}
protected static class EmailTemplate {
private String subject;
private String textBody;
private String htmlBody;
public EmailTemplate(String subject, String textBody, String htmlBody) {
this.subject = subject;
this.textBody = textBody;
this.htmlBody = htmlBody;
}
public String getSubject() {
return subject;
}
public String getTextBody() {
return textBody;
}
public String getHtmlBody() {
return htmlBody;
}
}
}