Guest User

Untitled

a guest
Oct 23rd, 2017
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.04 KB | None | 0 0
  1. <context:property-placeholder location="classpath:/ldap.properties"
  2. system-properties-mode="OVERRIDE" />
  3. <context:annotation-config />
  4.  
  5. <ldap:context-source id="contextSource" password="${sample.ldap.password}"
  6. url="${sample.ldap.url}" username="${sample.ldap.userDn}" base="${sample.ldap.base}" />
  7.  
  8. <ldap:ldap-template id="ldapTemplate"
  9. context-source-ref="contextSource" />
  10.  
  11. <!-- This will scan the org.springframework.ldap.samples.useradmin.domain
  12. package for interfaces extending CrudRepository (in our case, LdapRepository),
  13. automatically creating repository beans based on these interfaces. -->
  14. <ldap:repositories base-package="com.cazysystems.appstore.model" />
  15.  
  16. <!-- This one will never be referenced directly, but the ldap:repositories
  17. tag will make sure it will be 'wired in', because the GroupRepo interface
  18. extends from an interface that GroupRepoImpl imlements. -->
  19. <bean class="com.cazysystems.appstore.model.impli.GroupRepoImpl" />
  20.  
  21. <bean class="com.cazysystems.appstore.model.impli.DepartmentRepoImpl" />
  22.  
  23. <bean class="com.cazysystems.appstore.service.UserService">
  24. <property name="directoryType" value="${sample.ldap.directory.type}" />
  25. </bean>
  26.  
  27. @Configuration
  28. @EnableLdapRepositories("com.cazysystems.appstore.model")
  29. public class LdapConfiguration {
  30.  
  31. @Autowired
  32. Environment env;
  33.  
  34. @Bean
  35. public LdapContextSource contextSource() {
  36. LdapContextSource contextSource = new LdapContextSource();
  37. contextSource.setUrl(env.getRequiredProperty("sample.ldap.url"));
  38. contextSource.setBase(env.getRequiredProperty("sample.ldap.base"));
  39. contextSource.setUserDn(env.getRequiredProperty("sample.ldap.userDn"));
  40. contextSource.setPassword(env
  41. .getRequiredProperty("sample.ldap.password"));
  42. return contextSource;
  43. }
  44.  
  45. @Bean
  46. public LdapTemplate ldapTemplate() {
  47. return new LdapTemplate(contextSource());
  48. }
  49.  
  50. }
  51.  
  52. @Configuration
  53. public class AuthenticationConfiguration extends
  54. GlobalAuthenticationConfigurerAdapter {
  55.  
  56. @Autowired
  57. Environment env;
  58.  
  59. @Override
  60. public void init(AuthenticationManagerBuilder auth) throws Exception {
  61.  
  62. auth.ldapAuthentication()
  63. // .userDetailsContextMapper(userDetailsContextMapper())
  64. .userDnPatterns(
  65. env.getRequiredProperty("ldap.user_dn_patterns"))
  66. .groupSearchBase(
  67. env.getRequiredProperty("ldap.group_search_base"))
  68. .contextSource().ldif("classpath:setup_data.ldif")
  69. .url(env.getRequiredProperty("sample.ldap.url"))
  70. .managerDn("sample.ldap.userDn")
  71. .managerPassword("sample.ldap.password").port(10389);
  72. }
  73.  
  74. }
  75.  
  76. Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class com.cazysystems.appstore.model.Group
  77.  
  78. public interface GroupRepo extends LdapRepository<Group>, GroupRepoExtension {
  79. public final static String USER_GROUP = "ROLE_USER";
  80.  
  81. Group findByName(String groupName);
  82.  
  83. @Query("(member={0})")
  84. Collection<Group> findByMember(Name member);
  85. }
  86.  
  87. @Entry(objectClasses = { "groupOfNames", "top" }, base = "ou=Groups")
  88. public final class Group {
  89. @Id
  90. private Name id;
  91.  
  92. @Attribute(name = "cn")
  93. @DnAttribute(value = "cn", index = 1)
  94. private String name;
  95.  
  96. @Attribute(name = "description")
  97. private String description;
  98.  
  99. @Attribute(name = "member")
  100. private Set<Name> members = new HashSet<Name>();
  101.  
  102. public String getDescription() {
  103. return description;
  104. }
  105.  
  106. public void setDescription(String description) {
  107. this.description = description;
  108. }
  109.  
  110. public Set<Name> getMembers() {
  111. return members;
  112. }
  113.  
  114. public void addMember(Name newMember) {
  115. members.add(newMember);
  116. }
  117.  
  118. public void removeMember(Name member) {
  119. members.remove(member);
  120. }
  121.  
  122. public Name getId() {
  123. return id;
  124. }
  125.  
  126. public void setId(Name id) {
  127. this.id = id;
  128. }
  129.  
  130. public String getName() {
  131. return name;
  132. }
  133.  
  134. public void setName(String name) {
  135. this.name = name;
  136. }
  137. }
  138.  
  139. @EnableLdapRepositories("com.cazysystems.appstore.model")
  140.  
  141. <dependency>
  142. <groupId>org.springframework.security</groupId>
  143. <artifactId>spring-security-ldap</artifactId>
  144. </dependency>
  145.  
  146.  
  147. <dependency>
  148. <groupId>org.springframework.ldap</groupId>
  149. <artifactId>spring-ldap-core</artifactId>
  150. <version>2.0.3.RELEASE</version>
  151. </dependency>
  152.  
  153. <dependency>
  154. <groupId>org.springframework.ldap</groupId>
  155. <artifactId>spring-ldap-core-tiger</artifactId>
  156. <version>2.0.3.RELEASE</version>
  157. </dependency>
  158.  
  159. <dependency>
  160. <groupId>org.springframework.data</groupId>
  161. <artifactId>spring-data-commons</artifactId>
  162. </dependency>
  163.  
  164. @Controller
  165. public class GroupController {
  166.  
  167. @Autowired
  168. private GroupRepo groupRepo;
  169.  
  170. @Autowired
  171. private UserService userService;
  172.  
  173. @RequestMapping(value = "/groups", method = GET)
  174. public String listGroups(ModelMap map) {
  175. map.put("groups", groupRepo.getAllGroupNames());
  176. return "listGroups";
  177. }
  178.  
  179. @RequestMapping(value = "/newGroup", method = GET)
  180. public String initNewGroup() {
  181. return "newGroup";
  182. }
  183.  
  184. @RequestMapping(value = "/groups", method = POST)
  185. public String newGroup(Group group) {
  186. groupRepo.create(group);
  187.  
  188. return "redirect:groups/" + group.getName();
  189. }
  190.  
  191. @RequestMapping(value = "/groups/{name}", method = GET)
  192. public String editGroup(@PathVariable String name, ModelMap map) {
  193. Group foundGroup = groupRepo.findByName(name);
  194. map.put("group", foundGroup);
  195.  
  196. final Set<User> groupMembers = userService.findAllMembers(foundGroup.getMembers());
  197. map.put("members", groupMembers);
  198.  
  199. Iterable<User> otherUsers = Iterables.filter(userService.findAll(), new Predicate<User>() {
  200. @Override
  201. public boolean apply(User user) {
  202. return !groupMembers.contains(user);
  203. }
  204. });
  205. map.put("nonMembers", Lists.newLinkedList(otherUsers));
  206.  
  207. return "editGroup";
  208. }
  209.  
  210. @RequestMapping(value = "/groups/{name}/members", method = POST)
  211. public String addUserToGroup(@PathVariable String name, @RequestParam String userId) {
  212. Group group = groupRepo.findByName(name);
  213. group.addMember(userService.toAbsoluteDn(LdapUtils.newLdapName(userId)));
  214.  
  215. groupRepo.save(group);
  216.  
  217. return "redirect:/groups/" + name;
  218. }
  219.  
  220. @RequestMapping(value = "/groups/{name}/members", method = DELETE)
  221. public String removeUserFromGroup(@PathVariable String name, @RequestParam String userId) {
  222. Group group = groupRepo.findByName(name);
  223. group.removeMember(userService.toAbsoluteDn(LdapUtils.newLdapName(userId)));
  224.  
  225. groupRepo.save(group);
  226.  
  227. return "redirect:/groups/" + name;
  228. }
  229. }
  230.  
  231. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.cazysystems.appstore.domain.GroupRepo com.eazysystems.appstore.controller.GroupController.groupRepo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class com.cazysystems.appstore.domain.Group
  232. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
  233. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
  234. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
  235. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
  236. at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
  237. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  238. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
  239. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
  240. at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
  241. at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
  242. at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
  243. at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
  244. at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
  245. at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
  246. at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
  247. at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
  248. at com.eazysystems.appstore.Application.main(Application.java:20)
  249. Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.cazysystems.appstore.domain.GroupRepo com.eazysystems.appstore.controller.GroupController.groupRepo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class com.eazysystems.appstore.domain.Group
  250. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
  251. at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
  252. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
  253. ... 16 common frames omitted
  254. Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class com.eazysystems.appstore.domain.Group
  255. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
  256. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
  257. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
  258. at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
  259. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  260. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
  261. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
  262. at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
  263. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
  264. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
  265. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
  266. ... 18 common frames omitted
  267. Caused by: java.lang.IllegalArgumentException: Not an managed type: class com.cazysystems.appstore.domain.Group
  268. at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219)
  269. at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:68)
  270. at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:67)
  271. at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145)
  272. at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:89)
  273. at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:69)
  274. at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:173)
  275. at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239)
  276. at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225)
  277. at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
  278. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
  279. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
  280. ... 28 common frames omitted
  281.  
  282. @Component
  283. public class UserService implements BaseLdapNameAware {
  284.  
  285. @Autowired
  286. private UserRepo userRepo;
  287.  
  288. @Autowired
  289. private GroupRepo groupRepo;
  290.  
  291. private LdapName baseLdapPath;
  292.  
  293. @Autowired
  294. @Value("${sample.ldap.directory.type}")
  295. private DirectoryType directoryType;
  296.  
  297. /*
  298. * @Autowired public UserService(UserRepo userRepo, GroupRepo groupRepo) {
  299. * this.userRepo = userRepo; this.groupRepo = groupRepo; }
  300. */
  301. public Group getUserGroup() {
  302. return groupRepo.findByName(GroupRepo.USER_GROUP);
  303. }
  304.  
  305. public void setDirectoryType(DirectoryType directoryType) {
  306. this.directoryType = directoryType;
  307. }
  308.  
  309. @Override
  310. public void setBaseLdapPath(LdapName baseLdapPath) {
  311. this.baseLdapPath = baseLdapPath;
  312. }
  313.  
  314. public Iterable<User> findAll() {
  315. return userRepo.findAll();
  316. }
  317.  
  318. public User findUser(String userId) {
  319. return userRepo.findOne(LdapUtils.newLdapName(userId));
  320. }
  321.  
  322. public User createUser(User user) {
  323. User savedUser = userRepo.save(user);
  324.  
  325. Group userGroup = getUserGroup();
  326.  
  327. // The DN the member attribute must be absolute
  328. userGroup.addMember(toAbsoluteDn(savedUser.getId()));
  329. groupRepo.save(userGroup);
  330.  
  331. return savedUser;
  332. }
  333.  
  334. public LdapName toAbsoluteDn(Name relativeName) {
  335. return LdapNameBuilder.newInstance(baseLdapPath).add(relativeName)
  336. .build();
  337. }
  338.  
  339. /**
  340. * This method expects absolute DNs of group members. In order to find the
  341. * actual users the DNs need to have the base LDAP path removed.
  342. *
  343. * @param absoluteIds
  344. * @return
  345. */
  346. public Set<User> findAllMembers(Iterable<Name> absoluteIds) {
  347. return Sets.newLinkedHashSet(userRepo
  348. .findAll(toRelativeIds(absoluteIds)));
  349. }
  350.  
  351. public Iterable<Name> toRelativeIds(Iterable<Name> absoluteIds) {
  352. return Iterables.transform(absoluteIds, new Function<Name, Name>() {
  353. @Override
  354. public Name apply(Name input) {
  355. return LdapUtils.removeFirst(input, baseLdapPath);
  356. }
  357. });
  358. }
  359.  
  360. public User updateUser(String userId, User user) {
  361. LdapName originalId = LdapUtils.newLdapName(userId);
  362. User existingUser = userRepo.findOne(originalId);
  363.  
  364. existingUser.setFirstName(user.getFirstName());
  365. existingUser.setLastName(user.getLastName());
  366. existingUser.setFullName(user.getFullName());
  367. existingUser.setEmail(user.getEmail());
  368. existingUser.setPhone(user.getPhone());
  369. existingUser.setTitle(user.getTitle());
  370. existingUser.setDepartment(user.getDepartment());
  371. existingUser.setUnit(user.getUnit());
  372.  
  373. if (directoryType == DirectoryType.AD) {
  374. return updateUserAd(originalId, existingUser);
  375. } else {
  376. return updateUserStandard(originalId, existingUser);
  377. }
  378. }
  379.  
  380. /**
  381. * Update the user and - if its id changed - update all group references to
  382. * the user.
  383. *
  384. * @param originalId
  385. * the original id of the user.
  386. * @param existingUser
  387. * the user, populated with new data
  388. *
  389. * @return the updated entry
  390. */
  391. private User updateUserStandard(LdapName originalId, User existingUser) {
  392. User savedUser = userRepo.save(existingUser);
  393.  
  394. if (!originalId.equals(savedUser.getId())) {
  395. // The user has moved - we need to update group references.
  396. LdapName oldMemberDn = toAbsoluteDn(originalId);
  397. LdapName newMemberDn = toAbsoluteDn(savedUser.getId());
  398.  
  399. Collection<Group> groups = groupRepo.findByMember(oldMemberDn);
  400. updateGroupReferences(groups, oldMemberDn, newMemberDn);
  401. }
  402. return savedUser;
  403. }
  404.  
  405. /**
  406. * Special behaviour in AD forces us to get the group membership before the
  407. * user is updated, because AD clears group membership for removed entries,
  408. * which means that once the user is update we've lost track of which groups
  409. * the user was originally member of, preventing us to update the membership
  410. * references so that they point to the new DN of the user.
  411. *
  412. * This is slightly less efficient, since we need to get the group
  413. * membership for all updates even though the user may not have been moved.
  414. * Using our knowledge of which attributes are part of the distinguished
  415. * name we can do this more efficiently if we are implementing specifically
  416. * for Active Directory - this approach is just to highlight this quite
  417. * significant difference.
  418. *
  419. * @param originalId
  420. * the original id of the user.
  421. * @param existingUser
  422. * the user, populated with new data
  423. *
  424. * @return the updated entry
  425. */
  426. private User updateUserAd(LdapName originalId, User existingUser) {
  427. LdapName oldMemberDn = toAbsoluteDn(originalId);
  428. Collection<Group> groups = groupRepo.findByMember(oldMemberDn);
  429.  
  430. User savedUser = userRepo.save(existingUser);
  431. LdapName newMemberDn = toAbsoluteDn(savedUser.getId());
  432.  
  433. if (!originalId.equals(savedUser.getId())) {
  434. // The user has moved - we need to update group references.
  435. updateGroupReferences(groups, oldMemberDn, newMemberDn);
  436. }
  437. return savedUser;
  438. }
  439.  
  440. private void updateGroupReferences(Collection<Group> groups,
  441. Name originalId, Name newId) {
  442. for (Group group : groups) {
  443. group.removeMember(originalId);
  444. group.addMember(newId);
  445.  
  446. groupRepo.save(group);
  447. }
  448. }
  449.  
  450. public List<User> searchByNameName(String lastName) {
  451. return userRepo.findByFullNameContains(lastName);
  452. }
  453. }
  454.  
  455. @Configuration
  456. public class LdapManagerConfiguration {
  457.  
  458. @Autowired
  459. Environment ldapProperties;
  460.  
  461. @Bean
  462. public LdapContextSource contextSourceTarget() {
  463. LdapContextSource ldapContextSource = new LdapContextSource();
  464. ldapContextSource.setUrl(ldapProperties.getProperty("auth.ldap.url"));
  465. ldapContextSource.setBase(ldapProperties.getProperty("auth.ldap.base"));
  466. ldapContextSource.setUserDn(ldapProperties
  467. .getProperty("auth.ldap.userdn"));
  468. ldapContextSource.setPassword(ldapProperties
  469. .getProperty("auth.ldap.password"));
  470.  
  471. return ldapContextSource;
  472.  
  473. }
  474.  
  475. @Bean
  476. public LdapTemplate ldapTemplate() {
  477.  
  478. return new LdapTemplate(contextSourceTarget());
  479.  
  480. }
  481.  
  482. @Bean
  483. public InetOrgPersonContextMapper inetOrgPersonContextMapper() {
  484. return new InetOrgPersonContextMapper();
  485. }
  486.  
  487. @Bean
  488. public DefaultLdapUsernameToDnMapper defaultLdapUsernameToDnMapper() {
  489. return new DefaultLdapUsernameToDnMapper(
  490. ldapProperties.getProperty("auth.ldap.groupbase"),
  491. ldapProperties.getProperty("auth.ldap.attributename.username"));// "uid"
  492. }
  493.  
  494. @Bean
  495. public LdapUserDetailsManager ldapUserDetailManager() {
  496. LdapUserDetailsManager userManager = new LdapUserDetailsManager(
  497. contextSourceTarget());
  498.  
  499. userManager.setGroupSearchBase(ldapProperties
  500. .getProperty("auth.ldap.groupbase"));
  501. userManager.setUserDetailsMapper(inetOrgPersonContextMapper());
  502. userManager.setUsernameMapper(defaultLdapUsernameToDnMapper());
  503. userManager.setGroupRoleAttributeName(ldapProperties
  504. .getProperty("auth.ldap.attributename.grouprole"));
  505. userManager.setGroupMemberAttributeName(ldapProperties
  506. .getProperty("auth.ldap.attributename.groupmemeber"));
  507.  
  508. return userManager;
  509.  
  510. }
  511.  
  512. }
  513.  
  514. Logger logger = LoggerFactory.getLogger(LdapUserManagerImpl.class);
  515.  
  516. @Autowired
  517. LdapTemplate ldapTemplate;
  518.  
  519. @Autowired
  520. Environment ldapProperties;
  521.  
  522. final String passwordAttribute = "userPassword";
  523.  
  524. @Override
  525. public boolean createUser(final String user,
  526. final String defaultPasswordPolicy)
  527. throws UserAlreadyExistsAsInactive {
  528.  
  529. boolean created = false;
  530.  
  531. String inactivePeople = ldapProperties.getProperty(
  532. "auth.ldap.inactive.groupbase").replace("ou=", "");
  533.  
  534. String activePeople = ldapProperties.getProperty("auth.ldap.groupbase")
  535. .replace("ou=", "");
  536.  
  537. if (existsUser(user, inactivePeople)) {
  538. logger.error("User " + user
  539. + " already exists in ldap but it's incative");
  540. throw new UserAlreadyExistsAsInactive(user);
  541.  
  542. }
  543. if (existsUser(user, activePeople)) {
  544. logger.error("User " + user
  545. + " already exists in ldap and is Active");
  546. return false;
  547. }
  548.  
  549. try {
  550.  
  551. ldapTemplate.bind(buildDn(user, inactivePeople), null,
  552. createUserDetails(user, defaultPasswordPolicy));
  553. created = true;
  554.  
  555. } catch (Exception e) {
  556. logger.error(
  557. "Unexpected exception when trying to create user in LdapException",
  558. e);
  559. return created;
  560. }
  561. return created;
  562. }
  563.  
  564. public UserI findUser(String userName, String group) {
  565.  
  566. try {
  567. String dn = buildDN(userName, group);
  568. User user = ldapTemplate.lookup(dn, new UserAttributesMapper());
  569. return user;
  570. } catch (NameNotFoundException e) {
  571. return new UserNullObject();
  572. }
  573.  
  574. }
  575.  
  576. @Override
  577. public void changeUserGroup(String userName, String oldGroup,
  578. String newGroup) throws ReLocoException {
  579.  
  580. UserI user = findUser(userName, oldGroup);
  581. if (!user.isEmpty()) {
  582.  
  583. try {
  584.  
  585. Object password = getLdapPassword(userName, oldGroup);
  586.  
  587. ldapTemplate.unbind(buildDN(userName, oldGroup));
  588.  
  589. String defaultPasswordPolicy = ldapProperties
  590. .getProperty("auth.ldap.default.userpollicy");
  591.  
  592. ldapTemplate.bind(buildDN(userName, newGroup), null,
  593. createUserDetails(userName, defaultPasswordPolicy));
  594.  
  595. applyPasswordToUser(userName, password, newGroup);
  596.  
  597. } catch (Exception e) {
  598. logger.error("Error on change user from incative to active people group "
  599. + e);
  600. throw new ConfirmAccountValidationCodeException(userName);
  601. }
  602. } else {
  603.  
  604. throw new UserNotFoundException(
  605. "The username provided for the given group '" + oldGroup
  606. + "' does not exist");
  607. }
  608.  
  609. }
Add Comment
Please, Sign In to add comment