-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
UserReconciler.java
214 lines (187 loc) · 8.22 KB
/
UserReconciler.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
package run.halo.app.core.extension.reconciler;
import static run.halo.app.core.extension.User.GROUP;
import static run.halo.app.core.extension.User.KIND;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;
import run.halo.app.core.extension.Role;
import run.halo.app.core.extension.RoleBinding;
import run.halo.app.core.extension.User;
import run.halo.app.core.extension.UserConnection;
import run.halo.app.core.extension.attachment.Attachment;
import run.halo.app.core.extension.service.AttachmentService;
import run.halo.app.core.extension.service.RoleService;
import run.halo.app.extension.ExtensionClient;
import run.halo.app.extension.GroupKind;
import run.halo.app.extension.MetadataUtil;
import run.halo.app.extension.controller.Controller;
import run.halo.app.extension.controller.ControllerBuilder;
import run.halo.app.extension.controller.Reconciler;
import run.halo.app.extension.controller.Reconciler.Request;
import run.halo.app.infra.AnonymousUserConst;
import run.halo.app.infra.ExternalUrlSupplier;
import run.halo.app.infra.utils.JsonUtils;
import run.halo.app.infra.utils.PathUtils;
@Slf4j
@Component
@RequiredArgsConstructor
public class UserReconciler implements Reconciler<Request> {
private static final String FINALIZER_NAME = "user-protection";
private final ExtensionClient client;
private final ExternalUrlSupplier externalUrlSupplier;
private final RoleService roleService;
private final AttachmentService attachmentService;
private final RetryTemplate retryTemplate = RetryTemplate.builder()
.maxAttempts(20)
.fixedBackoff(300)
.retryOn(IllegalStateException.class)
.build();
@Override
public Result reconcile(Request request) {
client.fetch(User.class, request.name()).ifPresent(user -> {
if (user.getMetadata().getDeletionTimestamp() != null) {
cleanUpResourcesAndRemoveFinalizer(request.name());
return;
}
addFinalizerIfNecessary(user);
ensureImportantAnnotation(request.name());
updatePermalink(request.name());
handleAvatar(request.name());
});
return new Result(false, null);
}
private void handleAvatar(String name) {
client.fetch(User.class, name).ifPresent(user -> {
Map<String, String> annotations = MetadataUtil.nullSafeAnnotations(user);
String avatarAttachmentName = annotations.get(User.AVATAR_ATTACHMENT_NAME_ANNO);
String oldAvatarAttachmentName = annotations.get(User.LAST_AVATAR_ATTACHMENT_NAME_ANNO);
if (StringUtils.isNotBlank(oldAvatarAttachmentName)
&& !StringUtils.equals(oldAvatarAttachmentName, avatarAttachmentName)) {
client.fetch(Attachment.class, oldAvatarAttachmentName)
.ifPresent(client::delete);
annotations.remove(User.LAST_AVATAR_ATTACHMENT_NAME_ANNO);
oldAvatarAttachmentName = null;
}
if (StringUtils.isNotBlank(avatarAttachmentName)) {
client.fetch(Attachment.class, avatarAttachmentName)
.ifPresent(attachment -> {
URI avatarUri = attachmentService.getPermalink(attachment).block();
if (avatarUri == null) {
throw new IllegalStateException("User avatar attachment not found.");
}
user.getSpec().setAvatar(avatarUri.toString());
});
} else if (StringUtils.isNotBlank(oldAvatarAttachmentName)) {
user.getSpec().setAvatar(null);
}
if (StringUtils.isBlank(oldAvatarAttachmentName)
&& StringUtils.isNotBlank(avatarAttachmentName)) {
annotations.put(User.LAST_AVATAR_ATTACHMENT_NAME_ANNO, avatarAttachmentName);
}
client.update(user);
});
}
private void ensureImportantAnnotation(String name) {
client.fetch(User.class, name).ifPresent(user -> {
Map<String, String> annotations = MetadataUtil.nullSafeAnnotations(user);
Map<String, String> oldAnnotations = Map.copyOf(annotations);
List<String> roleNames = listRoleNamesRef(name);
annotations.put(User.ROLE_NAMES_ANNO, JsonUtils.objectToJson(roleNames));
annotations.put(User.LAST_USED_EMAIL_ANNO, user.getSpec().getEmail());
if (!oldAnnotations.equals(annotations)) {
client.update(user);
}
});
}
List<String> listRoleNamesRef(String username) {
var subject = new RoleBinding.Subject(KIND, username, GROUP);
return roleService.listRoleRefs(subject)
.filter(this::isRoleRef)
.map(RoleBinding.RoleRef::getName)
.distinct()
.collectList()
.blockOptional()
.orElse(List.of());
}
private boolean isRoleRef(RoleBinding.RoleRef roleRef) {
var roleGvk = new Role().groupVersionKind();
var gk = new GroupKind(roleRef.getApiGroup(), roleRef.getKind());
return gk.equals(roleGvk.groupKind());
}
private void updatePermalink(String name) {
client.fetch(User.class, name).ifPresent(user -> {
if (AnonymousUserConst.isAnonymousUser(name)) {
// anonymous user is not allowed to have permalink
return;
}
if (user.getStatus() == null) {
user.setStatus(new User.UserStatus());
}
User.UserStatus status = user.getStatus();
String oldPermalink = status.getPermalink();
status.setPermalink(getUserPermalink(user));
if (!StringUtils.equals(oldPermalink, status.getPermalink())) {
client.update(user);
}
});
}
private String getUserPermalink(User user) {
return externalUrlSupplier.get()
.resolve(PathUtils.combinePath("authors", user.getMetadata().getName()))
.normalize().toString();
}
private void addFinalizerIfNecessary(User oldUser) {
Set<String> finalizers = oldUser.getMetadata().getFinalizers();
if (finalizers != null && finalizers.contains(FINALIZER_NAME)) {
return;
}
client.fetch(User.class, oldUser.getMetadata().getName())
.ifPresent(user -> {
Set<String> newFinalizers = user.getMetadata().getFinalizers();
if (newFinalizers == null) {
newFinalizers = new HashSet<>();
user.getMetadata().setFinalizers(newFinalizers);
}
newFinalizers.add(FINALIZER_NAME);
client.update(user);
});
}
private void cleanUpResourcesAndRemoveFinalizer(String userName) {
client.fetch(User.class, userName).ifPresent(user -> {
// wait for dependent resources to be deleted
deleteUserConnections(userName);
// remove finalizer
if (user.getMetadata().getFinalizers() != null) {
user.getMetadata().getFinalizers().remove(FINALIZER_NAME);
}
client.update(user);
});
}
void deleteUserConnections(String userName) {
listConnectionsByUsername(userName).forEach(client::delete);
// wait for user connection to be deleted
retryTemplate.execute(callback -> {
if (listConnectionsByUsername(userName).size() > 0) {
throw new IllegalStateException("User connection is not deleted yet");
}
return null;
});
}
List<UserConnection> listConnectionsByUsername(String username) {
return client.list(UserConnection.class,
connection -> connection.getSpec().getUsername().equals(username), null);
}
@Override
public Controller setupWith(ControllerBuilder builder) {
return builder
.extension(new User())
.build();
}
}