1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.opencastproject.userdirectory.ldap;
23
24 import org.springframework.ldap.core.DirContextAdapter;
25 import org.springframework.ldap.core.DirContextOperations;
26 import org.springframework.security.core.GrantedAuthority;
27 import org.springframework.security.core.userdetails.UserDetails;
28 import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
29
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.List;
34 import java.util.Objects;
35 import java.util.StringJoiner;
36
37 public class OpencastUserDetailsContextMapper implements UserDetailsContextMapper {
38
39 private final String[] name;
40
41 private final String mail;
42
43 public OpencastUserDetailsContextMapper(String[] name, String mail) {
44 Objects.requireNonNull(name);
45 Objects.requireNonNull(mail);
46 this.name = name;
47 this.mail = mail;
48 }
49
50 @Override
51 public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
52 Collection<? extends GrantedAuthority> authorities) {
53 String dn = ctx.getNameInNamespace();
54
55 OpencastUserDetails.Essence essence = new OpencastUserDetails.Essence();
56 essence.setDn(dn);
57 essence.setUsername(username);
58 essence.setName(buildName(ctx));
59 essence.setMail(ctx.getStringAttribute(mail));
60
61
62 for (GrantedAuthority authority : authorities) {
63 essence.addAuthority(authority);
64 }
65
66 return essence.createUserDetails();
67 }
68 private String buildName(DirContextOperations ctx) {
69 StringJoiner joiner = new StringJoiner(" ");
70 for (String attribute: name) {
71 joiner.add(ctx.getStringAttribute(attribute));
72 }
73 return joiner.toString();
74 }
75
76 @Override
77 public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
78 throw new UnsupportedOperationException("OpencastUserContextMapper only supports reading from a context. Please"
79 + "use a subclass if mapUserToContext() is required.");
80 }
81
82 public String[] getAttributes() {
83 List<String> attributes = new ArrayList<>(Arrays.asList(name));
84 attributes.add(mail);
85 return attributes.toArray(new String[] {});
86 }
87 }