UmsAdminServiceImpl.java 10.3 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;
M
macro 已提交
7
import com.macro.mall.common.exception.Asserts;
M
macro 已提交
8
import com.macro.mall.common.util.RequestUtil;
Z
zhh 已提交
9
import com.macro.mall.dao.UmsAdminRoleRelationDao;
Z
zhh 已提交
10
import com.macro.mall.dto.UmsAdminParam;
M
macro 已提交
11
import com.macro.mall.dto.UpdateAdminPasswordParam;
Z
zhh 已提交
12
import com.macro.mall.mapper.UmsAdminLoginLogMapper;
Z
zhh 已提交
13
import com.macro.mall.mapper.UmsAdminMapper;
Z
zhh 已提交
14 15
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;
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 39 40
import java.util.List;

/**
M
macro 已提交
41
 * 后台用户管理Service实现类
Z
zhh 已提交
42
 * Created by macro on 2018/4/26.
Z
zhh 已提交
43 44
 */
@Service
Z
zhh 已提交
45
public class UmsAdminServiceImpl implements UmsAdminService {
Z
zhh 已提交
46
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);
Z
zhh 已提交
47
    @Autowired
Z
zhh 已提交
48 49 50
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
Z
zhh 已提交
51 52 53 54 55 56 57
    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private UmsAdminRoleRelationMapper adminRoleRelationMapper;
    @Autowired
    private UmsAdminRoleRelationDao adminRoleRelationDao;
    @Autowired
Z
zhh 已提交
58
    private UmsAdminLoginLogMapper loginLogMapper;
M
macro 已提交
59 60
    @Autowired
    private UmsAdminCacheService adminCacheService;
Z
zhh 已提交
61

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

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

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

Z
zhh 已提交
120 121 122 123 124 125
    /**
     * 添加登录记录
     * @param username 用户名
     */
    private void insertLoginLog(String username) {
        UmsAdmin admin = getAdminByUsername(username);
M
macro 已提交
126
        if(admin==null) return;
Z
zhh 已提交
127 128 129 130 131
        UmsAdminLoginLog loginLog = new UmsAdminLoginLog();
        loginLog.setAdminId(admin.getId());
        loginLog.setCreateTime(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
M
macro 已提交
132
        loginLog.setIp(RequestUtil.getRequestIp(request));
Z
zhh 已提交
133 134 135
        loginLogMapper.insert(loginLog);
    }

Z
zhh 已提交
136 137 138 139 140 141 142 143 144 145 146
    /**
     * 根据用户名修改登录时间
     */
    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 已提交
147 148
    @Override
    public String refreshToken(String oldToken) {
M
macro 已提交
149
        return jwtTokenUtil.refreshHeadToken(oldToken);
Z
zhh 已提交
150
    }
Z
zhh 已提交
151 152 153 154 155 156 157

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

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

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

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

    @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 已提交
215
        adminCacheService.delResourceList(adminId);
Z
zhh 已提交
216 217 218 219 220 221 222 223
        return count;
    }

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

M
macro 已提交
224 225
    @Override
    public List<UmsResource> getResourceList(Long adminId) {
M
macro 已提交
226 227 228 229 230 231 232 233 234
        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 已提交
235 236
    }

M
macro 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    @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 已提交
256
        adminCacheService.delAdmin(umsAdmin.getId());
M
macro 已提交
257 258
        return 1;
    }
M
macro 已提交
259 260 261 262 263 264

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