UmsAdminServiceImpl.java 12.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;
M
macro 已提交
17
import com.macro.mall.service.UmsAdminCacheService;
Z
zhh 已提交
18
import com.macro.mall.service.UmsAdminService;
Z
zhh 已提交
19 20
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Z
zhh 已提交
21
import org.springframework.beans.BeanUtils;
Z
zhh 已提交
22
import org.springframework.beans.factory.annotation.Autowired;
23
import org.springframework.security.authentication.BadCredentialsException;
Z
zhh 已提交
24
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Z
zhh 已提交
25
import org.springframework.security.core.AuthenticationException;
Z
zhh 已提交
26 27
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
M
macro 已提交
28
import org.springframework.security.core.userdetails.UsernameNotFoundException;
29
import org.springframework.security.crypto.password.PasswordEncoder;
Z
zhh 已提交
30
import org.springframework.stereotype.Service;
Z
zhh 已提交
31
import org.springframework.util.CollectionUtils;
Z
zhh 已提交
32
import org.springframework.util.StringUtils;
Z
zhh 已提交
33 34
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
Z
zhh 已提交
35

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

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

Z
zhh 已提交
68 69
    @Override
    public UmsAdmin getAdminByUsername(String username) {
M
macro 已提交
70 71
        UmsAdmin admin = adminCacheService.getAdmin(username);
        if(admin!=null) return  admin;
Z
zhh 已提交
72 73 74
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin> adminList = adminMapper.selectByExample(example);
Z
zhh 已提交
75
        if (adminList != null && adminList.size() > 0) {
M
macro 已提交
76 77 78
            admin = adminList.get(0);
            adminCacheService.setAdmin(admin);
            return admin;
Z
zhh 已提交
79 80 81
        }
        return null;
    }
Z
zhh 已提交
82 83 84 85

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

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

Z
zhh 已提交
123 124 125 126 127 128
    /**
     * 添加登录记录
     * @param username 用户名
     */
    private void insertLoginLog(String username) {
        UmsAdmin admin = getAdminByUsername(username);
M
macro 已提交
129
        if(admin==null) return;
Z
zhh 已提交
130 131 132 133 134 135 136 137 138
        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 已提交
139 140 141 142 143 144 145 146 147 148 149
    /**
     * 根据用户名修改登录时间
     */
    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 已提交
150 151
    @Override
    public String refreshToken(String oldToken) {
M
macro 已提交
152
        return jwtTokenUtil.refreshHeadToken(oldToken);
Z
zhh 已提交
153
    }
Z
zhh 已提交
154 155 156 157 158 159 160

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

    @Override
M
macro 已提交
161
    public List<UmsAdmin> list(String keyword, Integer pageSize, Integer pageNum) {
Z
zhh 已提交
162
        PageHelper.startPage(pageNum, pageSize);
Z
zhh 已提交
163 164
        UmsAdminExample example = new UmsAdminExample();
        UmsAdminExample.Criteria criteria = example.createCriteria();
M
macro 已提交
165 166 167
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andUsernameLike("%" + keyword + "%");
            example.or(example.createCriteria().andNickNameLike("%" + keyword + "%"));
Z
zhh 已提交
168 169 170 171 172 173
        }
        return adminMapper.selectByExample(example);
    }

    @Override
    public int update(Long id, UmsAdmin admin) {
Z
zhh 已提交
174
        admin.setId(id);
M
macro 已提交
175 176 177 178 179 180 181 182 183 184 185 186
        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 已提交
187 188 189
        int count = adminMapper.updateByPrimaryKeySelective(admin);
        adminCacheService.delAdmin(id);
        return count;
Z
zhh 已提交
190 191 192 193
    }

    @Override
    public int delete(Long id) {
M
macro 已提交
194 195 196 197
        adminCacheService.delAdmin(id);
        int count = adminMapper.deleteByPrimaryKey(id);
        adminCacheService.delResourceList(id);
        return count;
Z
zhh 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    }

    @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);
        }
M
macro 已提交
218
        adminCacheService.delResourceList(adminId);
Z
zhh 已提交
219 220 221 222 223 224 225 226
        return count;
    }

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

M
macro 已提交
227 228
    @Override
    public List<UmsResource> getResourceList(Long adminId) {
M
macro 已提交
229 230 231 232 233 234 235 236 237
        List<UmsResource> resourceList = adminCacheService.getResourceList(adminId);
        if(CollUtil.isNotEmpty(resourceList)){
            return  resourceList;
        }
        resourceList = adminRoleRelationDao.getResourceList(adminId);
        if(CollUtil.isNotEmpty(resourceList)){
            adminCacheService.setResourceList(adminId,resourceList);
        }
        return resourceList;
M
macro 已提交
238 239
    }

Z
zhh 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    @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 已提交
260 261
        return 0;
    }
Z
zhh 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

    /**
     * 将+-权限关系转化为对象
     */
    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 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300

    @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);
M
macro 已提交
301
        adminCacheService.delAdmin(umsAdmin.getId());
M
macro 已提交
302 303
        return 1;
    }
M
macro 已提交
304 305 306 307 308 309

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