Skip to content

Commit

Permalink
ldap login
Browse files Browse the repository at this point in the history
  • Loading branch information
RichardShan committed Nov 27, 2018
1 parent a48d893 commit f3c3b5c
Show file tree
Hide file tree
Showing 12 changed files with 242 additions and 24 deletions.
13 changes: 11 additions & 2 deletions server/src/main/java/edp/davinci/controller/LoginController.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import edp.davinci.core.common.Constants;
import edp.davinci.core.common.ResultMap;
import edp.davinci.dto.userDto.UserLogin;
import edp.davinci.service.LdapService;
import edp.davinci.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
Expand Down Expand Up @@ -54,6 +55,9 @@ public class LoginController {
@Autowired
private UserService userService;

@Autowired(required = false)
private LdapService ldapService;

/**
* 登录
*
Expand All @@ -69,8 +73,13 @@ public ResponseEntity login(@Valid @RequestBody UserLogin userLogin, @ApiIgnore
return ResponseEntity.status(resultMap.getCode()).body(resultMap);
}
try {
ResultMap resultMap = userService.userLogin(userLogin);
return ResponseEntity.status(resultMap.getCode()).body(resultMap);
if (null == ldapService) {
ResultMap resultMap = userService.userLogin(userLogin);
return ResponseEntity.status(resultMap.getCode()).body(resultMap);
} else {
ResultMap resultMap = ldapService.userLogin(userLogin);
return ResponseEntity.status(resultMap.getCode()).body(resultMap);
}
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
Expand Down
3 changes: 3 additions & 0 deletions server/src/main/java/edp/davinci/dao/OrganizationMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public interface OrganizationMapper {
Expand Down Expand Up @@ -84,6 +85,8 @@ public interface OrganizationMapper {

int updateMemberNum(Organization organization);

int addOneMemberNum(@Param("list") Set<Long> orgIds);

int updateTeamNum(Organization organization);


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public interface RelUserOrganizationMapper {
Expand Down Expand Up @@ -71,4 +72,7 @@ public interface RelUserOrganizationMapper {
@Select({"SELECT r.* FROM rel_user_organization r inner join project p on p.org_id = r.org_id where r.user_id = #{userId} and p.id = #{projectId}"})
RelUserOrganization getRelByProject(@Param("userId") Long userId, @Param("projectId") Long projectId);


int insertBatch(@Param("list") Set<RelUserOrganization> list);

}
3 changes: 3 additions & 0 deletions server/src/main/java/edp/davinci/dao/RelUserTeamMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,7 @@ public interface RelUserTeamMapper {


int deleteBatch(@Param("list") List<Long> list);


int insertBatch(@Param("list") Set<RelUserTeam> list);
}
3 changes: 3 additions & 0 deletions server/src/main/java/edp/davinci/dao/TeamMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ public interface TeamMapper {
@Select({"select * from team where org_id= #{orgId}"})
List<Team> getByOrgId(@Param("orgId") Long orgId);

@Select({"select * from team where description= #{desc}"})
List<Team> getByDesc(@Param("desc") String desc);

// @Select({
// "select t.id, t.`name`, t.description, t.visibility, t.parent_team_id from team t, rel_user_team rut",
// "where rut.team_id = t.id and t.org_id = #{orgId} and rut.user_id = #{userId} and (rut.role = 1 OR t.visibility = 1)"
Expand Down
2 changes: 2 additions & 0 deletions server/src/main/java/edp/davinci/model/LdapPerson.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
public class LdapPerson {
private String name;
private String sAMAccountName;
private String dept;
private String email;

@Override
public String toString() {
Expand Down
11 changes: 8 additions & 3 deletions server/src/main/java/edp/davinci/service/LdapService.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,15 @@

package edp.davinci.service;

import edp.davinci.core.common.ResultMap;
import edp.davinci.dto.userDto.UserLogin;
import edp.davinci.model.LdapPerson;

import javax.naming.NamingException;
import edp.davinci.model.User;

public interface LdapService {
public LdapPerson findByUsername(String username, String password) throws NamingException;
LdapPerson findByUsername(String username, String password) throws Exception;

ResultMap userLogin(UserLogin userLogin);

User registUser(LdapPerson ldapPerson);
}
182 changes: 163 additions & 19 deletions server/src/main/java/edp/davinci/service/impl/LdapServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,41 @@

package edp.davinci.service.impl;

import edp.davinci.model.LdapPerson;
import edp.core.exception.ServerException;
import edp.core.utils.TokenUtils;
import edp.davinci.core.common.ResultMap;
import edp.davinci.core.enums.UserOrgRoleEnum;
import edp.davinci.core.enums.UserTeamRoleEnum;
import edp.davinci.dao.*;
import edp.davinci.dto.userDto.UserLogin;
import edp.davinci.dto.userDto.UserLoginResult;
import edp.davinci.model.*;
import edp.davinci.service.LdapService;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.springframework.ldap.query.LdapQueryBuilder.query;

@Slf4j
@Service("ldapService")
public class LdapServiceImpl implements LdapService {

Expand All @@ -44,33 +62,159 @@ public class LdapServiceImpl implements LdapService {
@Value("${spring.ldap.domainName}")
private String ldapDomainName;

public LdapPerson findByUsername(String username, String password) throws NamingException {
@Autowired
private UserMapper userMapper;

@Autowired
private TeamMapper teamMapper;

@Autowired
private RelUserTeamMapper relUserTeamMapper;

@Autowired
private RelUserOrganizationMapper relUserOrganizationMapper;

@Autowired
private OrganizationMapper organizationMapper;


@Autowired
private TokenUtils tokenUtils;

public LdapPerson findByUsername(String username, String password) throws Exception {
LdapPerson ldapPerson = null;

if (StringUtils.endsWithIgnoreCase(username,ldapDomainName)) {
if (StringUtils.endsWithIgnoreCase(username, ldapDomainName)) {
username = username.replaceAll("(?i)" + ldapDomainName, "");
}
String userDn = username + ldapDomainName;

DirContext ctx = ldapTemplate.getContextSource().getContext(userDn, password);

List<LdapPerson> search = ldapTemplate.search(
query().where("objectclass").is("person").and("sAMAccountName").is(username),
new AttributesMapper<LdapPerson>() {
@Override
public LdapPerson mapFromAttributes(Attributes attributes) throws NamingException {
LdapPerson ldapPerson = new LdapPerson();
ldapPerson.setName(attributes.get("cn").get().toString());
ldapPerson.setSAMAccountName(attributes.get("sAMAccountName").get().toString());
return ldapPerson;
}
});
DirContext ctx = null;
try {
ctx = ldapTemplate.getContextSource().getContext(userDn, password);

List<LdapPerson> search = ldapTemplate.search(
query().where("objectclass").is("person").and("sAMAccountName").is(username),
new AttributesMapper<LdapPerson>() {
@Override
public LdapPerson mapFromAttributes(Attributes attributes) throws NamingException {

if (null != search && search.size() > 0) {
ldapPerson = search.get(0);
LdapPerson ldapPerson = new LdapPerson();
ldapPerson.setName(attributes.get("cn").get().toString());
String distinguishedname = attributes.get("distinguishedname").get().toString();
if (!StringUtils.isEmpty(distinguishedname)) {
String[] split = distinguishedname.split(",");
List<String> list = new ArrayList<>();
for (String s : split) {
if (StringUtils.startsWithIgnoreCase(s.trim(), "OU=")) {
if (StringUtils.endsWithIgnoreCase(s.trim(), "HABROOT")) {
continue;
}
list.add(0, s.trim().replace("OU=", ""));
}
}
ldapPerson.setDept(list.stream().collect(Collectors.joining("_")));
}
ldapPerson.setSAMAccountName(attributes.get("sAMAccountName").get().toString());
ldapPerson.setEmail(userDn);
return ldapPerson;
}
});

if (null != search && search.size() > 0) {
ldapPerson = search.get(0);
}
} catch (Exception e) {
throw new ServerException(e.getMessage());
} finally {
if (null != ctx) {
LdapUtils.closeContext(ctx);
}
}

LdapUtils.closeContext(ctx);
return ldapPerson;
}


@Override
public ResultMap userLogin(UserLogin userLogin) {
ResultMap resultMap = new ResultMap(tokenUtils);

User user = userMapper.selectByUsername(userLogin.getUsername());
if (null == user) {
LdapPerson ldapPerson = null;
try {
ldapPerson = findByUsername(userLogin.getUsername(), userLogin.getPassword());
if (null != ldapPerson) {
user = registUser(ldapPerson);
}
} catch (Exception e) {
log.info("user not found: {}", userLogin.getUsername());
return resultMap.fail().message("user not found").payload("username or password is wrong");
}

if (null == ldapPerson) {
log.info("user not found: {}", userLogin.getUsername());
return resultMap.fail().message("user not found").payload("username or password is wrong");
}
}
//校验密码
if (!BCrypt.checkpw(userLogin.getPassword(), user.getPassword())) {
log.info("password is wrong: {}", userLogin.getUsername());
return resultMap.fail().message("password is wrong").payload("username or password is wrong");
}
//是否激活
if (!user.getActive()) {
log.info("this user is not active: {}", userLogin.getUsername());
return resultMap.failWithToken(tokenUtils.generateToken(user)).message("this user is not active");
}

UserLoginResult userLoginResult = new UserLoginResult();
BeanUtils.copyProperties(user, userLoginResult);
return resultMap.success(tokenUtils.generateToken(user)).payload(userLoginResult);
}



@Override
@Transactional
public User registUser(LdapPerson ldapPerson) {
User user = null;
if (null != ldapPerson) {
try {
user.setName(ldapPerson.getName());
user.setEmail(ldapPerson.getEmail());
user.setUsername(ldapPerson.getSAMAccountName());
user.setDescription(ldapPerson.getDept());
user.setActive(true);
user.setPassword("-1");

int insert = userMapper.insert(user);
if (insert > 0) {
List<Team> teams = teamMapper.getByDesc(ldapPerson.getDept());
if (null != teams && teams.size() > 0) {
Set<Long> orgIds = new HashSet<>();
Set<RelUserTeam> relUserTeamSet = new HashSet<>();
Set<RelUserOrganization> relUserOrganizationSet = new HashSet<>();
for (Team team : teams) {
relUserTeamSet.add(new RelUserTeam(team.getId(), user.getId(), UserTeamRoleEnum.MEMBER.getRole()));
orgIds.add(team.getOrgId());
}
for (Long orgId : orgIds) {
relUserOrganizationSet.add(new RelUserOrganization(orgId, user.getId(), UserOrgRoleEnum.MEMBER.getRole()));
}

relUserTeamMapper.insertBatch(relUserTeamSet);
relUserOrganizationMapper.insertBatch(relUserOrganizationSet);
organizationMapper.addOneMemberNum(orgIds);
}
}
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
return null;
}
}
return user;
}

}
9 changes: 9 additions & 0 deletions server/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ spring:
caffeine:
type: caffeine

ldap:
urls: ldap://10.151.6.97:389
username: davinci-ldap02
password: m6#6EY69
base: OU=宜信公司,OU=HABROOT,DC=creditease,DC=corp
domainName: '@creditease.cn'



logging:
config: file:${DAVINCI3_HOME}/config/logback.xml

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@
</where>
</update>

<update id="addOneMemberNum" parameterType="java.util.Set">
update organization set team_num=(team_num + 1) where id in
<foreach collection="list" index="index" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</update>

<select id="getJointlyOrganization" resultType="edp.davinci.dto.organizationDto.OrganizationInfo" parameterType="java.util.Set">
SELECT o.* FROM
(organization o,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,19 @@
#{role, jdbcType=SMALLINT}
</trim>
</insert>



<insert id="insertBatch" useGeneratedKeys="true" keyProperty="id">
insert ignore into rel_user_organization
(org_id,user_id, role)
VALUES
<foreach collection="list" item="record" index="index" separator=",">
(
#{record.orgId,jdbcType=BIGINT},
#{record.userId,jdbcType=BIGINT},
#{record.role,jdbcType=SMALLINT}
)
</foreach>
</insert>
</mapper>
Loading

0 comments on commit f3c3b5c

Please sign in to comment.