UmsAdminServiceImpl.java 11.7 KB
Newer Older
Z
zhh 已提交
1 2
package com.macro.mall.service.impl;

M
macro 已提交
3 4
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
Z
zhh 已提交
5
import com.github.pagehelper.PageHelper;
M
macro 已提交
6
import com.macro.mall.bo.AdminUserDetails;
Z
zhh 已提交
7 8
import com.macro.mall.dao.UmsAdminPermissionRelationDao;
import com.macro.mall.dao.UmsAdminRoleRelationDao;
Z
zhh 已提交
9
import com.macro.mall.dto.UmsAdminParam;
M
macro 已提交
10
import com.macro.mall.dto.UpdateAdminPasswordParam;
Z
zhh 已提交
11
import com.macro.mall.mapper.UmsAdminLoginLogMapper;
Z
zhh 已提交
12
import com.macro.mall.mapper.UmsAdminMapper;
Z
zhh 已提交
13 14 15
import com.macro.mall.mapper.UmsAdminPermissionRelationMapper;
import com.macro.mall.mapper.UmsAdminRoleRelationMapper;
import com.macro.mall.model.*;
M
macro 已提交
16
import com.macro.mall.security.util.JwtTokenUtil;
Z
zhh 已提交
17
import com.macro.mall.service.UmsAdminService;
Z
zhh 已提交
18 19
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Z
zhh 已提交
20
import org.springframework.beans.BeanUtils;
Z
zhh 已提交
21
import org.springframework.beans.factory.annotation.Autowired;
22
import org.springframework.security.authentication.BadCredentialsException;
Z
zhh 已提交
23
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Z
zhh 已提交
24
import org.springframework.security.core.AuthenticationException;
Z
zhh 已提交
25 26
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
M
macro 已提交
27
import org.springframework.security.core.userdetails.UsernameNotFoundException;
28
import org.springframework.security.crypto.password.PasswordEncoder;
Z
zhh 已提交
29
import org.springframework.stereotype.Service;
Z
zhh 已提交
30
import org.springframework.util.CollectionUtils;
Z
zhh 已提交
31
import org.springframework.util.StringUtils;
Z
zhh 已提交
32 33
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
Z
zhh 已提交
34

Z
zhh 已提交
35
import javax.servlet.http.HttpServletRequest;
Z
zhh 已提交
36 37
import java.util.ArrayList;
import java.util.Date;
Z
zhh 已提交
38
import java.util.List;
Z
zhh 已提交
39
import java.util.stream.Collectors;
Z
zhh 已提交
40 41 42

/**
 * UmsAdminService实现类
Z
zhh 已提交
43
 * Created by macro on 2018/4/26.
Z
zhh 已提交
44 45
 */
@Service
Z
zhh 已提交
46
public class UmsAdminServiceImpl implements UmsAdminService {
Z
zhh 已提交
47
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);
Z
zhh 已提交
48
    @Autowired
Z
zhh 已提交
49 50 51
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
Z
zhh 已提交
52 53 54 55 56 57 58 59 60 61
    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private UmsAdminRoleRelationMapper adminRoleRelationMapper;
    @Autowired
    private UmsAdminRoleRelationDao adminRoleRelationDao;
    @Autowired
    private UmsAdminPermissionRelationMapper adminPermissionRelationMapper;
    @Autowired
    private UmsAdminPermissionRelationDao adminPermissionRelationDao;
Z
zhh 已提交
62 63
    @Autowired
    private UmsAdminLoginLogMapper loginLogMapper;
Z
zhh 已提交
64

Z
zhh 已提交
65 66 67 68 69
    @Override
    public UmsAdmin getAdminByUsername(String username) {
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin> adminList = adminMapper.selectByExample(example);
Z
zhh 已提交
70
        if (adminList != null && adminList.size() > 0) {
Z
zhh 已提交
71 72 73 74
            return adminList.get(0);
        }
        return null;
    }
Z
zhh 已提交
75 76 77 78

    @Override
    public UmsAdmin register(UmsAdminParam umsAdminParam) {
        UmsAdmin umsAdmin = new UmsAdmin();
Z
zhh 已提交
79 80 81
        BeanUtils.copyProperties(umsAdminParam, umsAdmin);
        umsAdmin.setCreateTime(new Date());
        umsAdmin.setStatus(1);
Z
zhh 已提交
82 83 84 85
        //查询是否有相同用户名的用户
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(umsAdmin.getUsername());
        List<UmsAdmin> umsAdminList = adminMapper.selectByExample(example);
Z
zhh 已提交
86
        if (umsAdminList.size() > 0) {
Z
zhh 已提交
87 88 89
            return null;
        }
        //将密码进行加密操作
M
macro 已提交
90 91
        String encodePassword = passwordEncoder.encode(umsAdmin.getPassword());
        umsAdmin.setPassword(encodePassword);
Z
zhh 已提交
92 93 94 95 96 97
        adminMapper.insert(umsAdmin);
        return umsAdmin;
    }

    @Override
    public String login(String username, String password) {
Z
zhh 已提交
98 99 100
        String token = null;
        //密码需要客户端加密后传递
        try {
M
macro 已提交
101
            UserDetails userDetails = loadUserByUsername(username);
102 103 104 105 106
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
Z
zhh 已提交
107
            token = jwtTokenUtil.generateToken(userDetails);
M
macro 已提交
108
//            updateLoginTimeByUsername(username);
Z
zhh 已提交
109
            insertLoginLog(username);
Z
zhh 已提交
110
        } catch (AuthenticationException e) {
Z
zhh 已提交
111
            LOGGER.warn("登录异常:{}", e.getMessage());
Z
zhh 已提交
112 113
        }
        return token;
Z
zhh 已提交
114 115
    }

Z
zhh 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    /**
     * 添加登录记录
     * @param username 用户名
     */
    private void insertLoginLog(String username) {
        UmsAdmin admin = getAdminByUsername(username);
        UmsAdminLoginLog loginLog = new UmsAdminLoginLog();
        loginLog.setAdminId(admin.getId());
        loginLog.setCreateTime(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        loginLog.setIp(request.getRemoteAddr());
        loginLogMapper.insert(loginLog);
    }

Z
zhh 已提交
131 132 133 134 135 136 137 138 139 140 141
    /**
     * 根据用户名修改登录时间
     */
    private void updateLoginTimeByUsername(String username) {
        UmsAdmin record = new UmsAdmin();
        record.setLoginTime(new Date());
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        adminMapper.updateByExampleSelective(record, example);
    }

Z
zhh 已提交
142 143
    @Override
    public String refreshToken(String oldToken) {
M
macro 已提交
144
        return jwtTokenUtil.refreshHeadToken(oldToken);
Z
zhh 已提交
145
    }
Z
zhh 已提交
146 147 148 149 150 151 152

    @Override
    public UmsAdmin getItem(Long id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    @Override
M
macro 已提交
153
    public List<UmsAdmin> list(String keyword, Integer pageSize, Integer pageNum) {
Z
zhh 已提交
154
        PageHelper.startPage(pageNum, pageSize);
Z
zhh 已提交
155 156
        UmsAdminExample example = new UmsAdminExample();
        UmsAdminExample.Criteria criteria = example.createCriteria();
M
macro 已提交
157 158 159
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andUsernameLike("%" + keyword + "%");
            example.or(example.createCriteria().andNickNameLike("%" + keyword + "%"));
Z
zhh 已提交
160 161 162 163 164 165
        }
        return adminMapper.selectByExample(example);
    }

    @Override
    public int update(Long id, UmsAdmin admin) {
Z
zhh 已提交
166
        admin.setId(id);
M
macro 已提交
167 168 169 170 171 172 173 174 175 176 177 178
        UmsAdmin rawAdmin = adminMapper.selectByPrimaryKey(id);
        if(rawAdmin.getPassword().equals(admin.getPassword())){
            //与原加密密码相同的不需要修改
            admin.setPassword(null);
        }else{
            //与原加密密码不同的需要加密修改
            if(StrUtil.isEmpty(admin.getPassword())){
                admin.setPassword(null);
            }else{
                admin.setPassword(passwordEncoder.encode(admin.getPassword()));
            }
        }
M
macro 已提交
179
        return adminMapper.updateByPrimaryKeySelective(admin);
Z
zhh 已提交
180 181 182 183
    }

    @Override
    public int delete(Long id) {
Z
zhh 已提交
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
        return adminMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateRole(Long adminId, List<Long> roleIds) {
        int count = roleIds == null ? 0 : roleIds.size();
        //先删除原来的关系
        UmsAdminRoleRelationExample adminRoleRelationExample = new UmsAdminRoleRelationExample();
        adminRoleRelationExample.createCriteria().andAdminIdEqualTo(adminId);
        adminRoleRelationMapper.deleteByExample(adminRoleRelationExample);
        //建立新关系
        if (!CollectionUtils.isEmpty(roleIds)) {
            List<UmsAdminRoleRelation> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                UmsAdminRoleRelation roleRelation = new UmsAdminRoleRelation();
                roleRelation.setAdminId(adminId);
                roleRelation.setRoleId(roleId);
                list.add(roleRelation);
            }
            adminRoleRelationDao.insertList(list);
        }
        return count;
    }

    @Override
    public List<UmsRole> getRoleList(Long adminId) {
        return adminRoleRelationDao.getRoleList(adminId);
    }

M
macro 已提交
213 214 215 216 217
    @Override
    public List<UmsResource> getResourceList(Long adminId) {
        return adminRoleRelationDao.getResourceList(adminId);
    }

Z
zhh 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    @Override
    public int updatePermission(Long adminId, List<Long> permissionIds) {
        //删除原所有权限关系
        UmsAdminPermissionRelationExample relationExample = new UmsAdminPermissionRelationExample();
        relationExample.createCriteria().andAdminIdEqualTo(adminId);
        adminPermissionRelationMapper.deleteByExample(relationExample);
        //获取用户所有角色权限
        List<UmsPermission> permissionList = adminRoleRelationDao.getRolePermissionList(adminId);
        List<Long> rolePermissionList = permissionList.stream().map(UmsPermission::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(permissionIds)) {
            List<UmsAdminPermissionRelation> relationList = new ArrayList<>();
            //筛选出+权限
            List<Long> addPermissionIdList = permissionIds.stream().filter(permissionId -> !rolePermissionList.contains(permissionId)).collect(Collectors.toList());
            //筛选出-权限
            List<Long> subPermissionIdList = rolePermissionList.stream().filter(permissionId -> !permissionIds.contains(permissionId)).collect(Collectors.toList());
            //插入+-权限关系
            relationList.addAll(convert(adminId,1,addPermissionIdList));
            relationList.addAll(convert(adminId,-1,subPermissionIdList));
            return adminPermissionRelationDao.insertList(relationList);
        }
Z
zhh 已提交
238 239
        return 0;
    }
Z
zhh 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

    /**
     * 将+-权限关系转化为对象
     */
    private List<UmsAdminPermissionRelation> convert(Long adminId,Integer type,List<Long> permissionIdList) {
        List<UmsAdminPermissionRelation> relationList = permissionIdList.stream().map(permissionId -> {
            UmsAdminPermissionRelation relation = new UmsAdminPermissionRelation();
            relation.setAdminId(adminId);
            relation.setType(type);
            relation.setPermissionId(permissionId);
            return relation;
        }).collect(Collectors.toList());
        return relationList;
    }

    @Override
    public List<UmsPermission> getPermissionList(Long adminId) {
        return adminRoleRelationDao.getPermissionList(adminId);
    }
M
macro 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

    @Override
    public int updatePassword(UpdateAdminPasswordParam param) {
        if(StrUtil.isEmpty(param.getUsername())
                ||StrUtil.isEmpty(param.getOldPassword())
                ||StrUtil.isEmpty(param.getNewPassword())){
            return -1;
        }
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(param.getUsername());
        List<UmsAdmin> adminList = adminMapper.selectByExample(example);
        if(CollUtil.isEmpty(adminList)){
            return -2;
        }
        UmsAdmin umsAdmin = adminList.get(0);
        if(!passwordEncoder.matches(param.getOldPassword(),umsAdmin.getPassword())){
            return -3;
        }
        umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword()));
        adminMapper.updateByPrimaryKey(umsAdmin);
        return 1;
    }
M
macro 已提交
281 282 283 284 285 286

    @Override
    public UserDetails loadUserByUsername(String username){
        //获取用户信息
        UmsAdmin admin = getAdminByUsername(username);
        if (admin != null) {
M
macro 已提交
287 288
            List<UmsResource> resourceList = getResourceList(admin.getId());
            return new AdminUserDetails(admin,resourceList);
M
macro 已提交
289 290 291
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
Z
zhh 已提交
292
}