All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cory.service.UserService Maven / Gradle / Ivy

There is a newer version: 0.0.35
Show newest version
package com.cory.service;

import com.cory.constant.BaseConstants;
import com.cory.constant.CacheConstants;
import com.cory.constant.ErrorCode;
import com.cory.context.CurrentUser;
import com.cory.dao.UserDao;
import com.cory.enums.UserLevel;
import com.cory.enums.UserStatus;
import com.cory.enums.UserType;
import com.cory.exception.CoryException;
import com.cory.model.User;
import com.cory.model.UserRoleRel;
import com.cory.util.systemconfigcache.SystemConfigCacheKey;
import com.cory.util.systemconfigcache.SystemConfigCacheUtil;
import com.cory.web.util.PasswordEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * generated by CodeGenerator on 2017/5/10.
 */
@Slf4j
@Service
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
@Transactional
public class UserService extends BaseService {

    private static final String DEFAULT_PASSWORD = "123456";

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserRoleRelService userRoleRelService;

    @Override
    public UserDao getDao() {
        return userDao;
    }

    @CachePut(value = CacheConstants.User)
    @Override
    public void add(User model) {
        model.setPassword(passwordEncoder.encode(model.getUserName(), DEFAULT_PASSWORD));
        model.setLastLogonSuccess(false);
        super.add(model);
    }

    @CacheEvict(value = CacheConstants.User, key = "#model.id", allEntries = true)
    @Override
    public void delete(User model) {
        super.delete(model);
    }

    @CacheEvict(value = CacheConstants.User, key = "#id", allEntries = true)
    @Override
    public void delete(int id) {
        super.delete(id);
    }

    @CacheEvict(value = CacheConstants.User, key = "#model.id", allEntries = true)
    @Override
    public void update(User model) {
        User db = userDao.get(model.getId());
        model.setPassword(db.getPassword());
        model.setLastLogonTime(db.getLastLogonTime());
        model.setLastLogonIp(db.getLastLogonIp());
        model.setLastLogonSuccess(db.getLastLogonSuccess());
        super.update(model);
    }

    @Cacheable(value = CacheConstants.User, key = "#id")
    @Override
    public User get(int id) {
        User user = super.get(id);
        assembleRoles(user);
        return user;
    }

    @Cacheable(value = CacheConstants.User, key = "'userName-'.concat(#userName)")
    public User findByUserName(String userName) {
        if (StringUtils.isBlank(userName)) {
            return null;
        }
        User user = userDao.findByUserName(userName);
        assembleRoles(user);
        return user;
    }

    private void assembleRoles(User user) {
        if (null == user || null == user.getId() || user.getId() <= 0) {
            return;
        }
        user.setRoles(roleService.getByUser(user.getId()));
    }

    /**
     * 注册一个用户,并分配普通用户角色
     * @param phone
     * @param password
     * @return 注册成功返回空,注册失败返回失败信息
     */
    public String register(String phone, String password) {
        if (null != userDao.findByUserName(phone)) {
            return phone + "已经注册,请直接登录或者重新输入.";
        }
        int admin = 1;
        User user = newUser(phone, password, admin);
        assignRole(user, admin);

        log.info("用户注册成功,手机号:{}", phone);

        return null;
    }

    private void assignRole(User user, int admin) {
        UserRoleRel userRoleRel = new UserRoleRel();
        userRoleRel.setCreator(BaseConstants.ADMIN_ID);
        userRoleRel.setModifier(BaseConstants.ADMIN_ID);
        userRoleRel.setUserId(user.getId());
        userRoleRel.setRoleId(roleService.getByName(SystemConfigCacheUtil.getCache(SystemConfigCacheKey.NORMAL_ROLE_NAME)).getId());
        userRoleRelService.assign(userRoleRel);
    }

    private User newUser(String phone, String password, int admin) {
        User user = new User();
        user.setUserName(phone);
        user.setPhone(phone);
        user.setPassword(passwordEncoder.encode(phone, password));
        user.setLevel(UserLevel.NORMAL);
        user.setStatus(UserStatus.NORMAL);
        user.setType(UserType.SITE);
        user.setCreator(BaseConstants.ADMIN_ID);
        user.setModifier(BaseConstants.ADMIN_ID);
        user.setLastLogonSuccess(false);

        userDao.add(user);
        return user;
    }

    @CacheEvict(value = CacheConstants.User, key = "#userId", allEntries = true)
    public void changePasswordDirectly(Integer userId, String newPassword) {
        if (StringUtils.isBlank(newPassword)) {
            throw new CoryException(ErrorCode.SAVE_ERROR, "密码不能为空.");
        }
        checkPassword(newPassword);
        User user = this.getDao().get(userId);
        if (null == user) {
            throw new CoryException(ErrorCode.SAVE_ERROR, "根据用户ID(" + userId + ")找不到用户.");
        }
        user.setPassword(passwordEncoder.encode(user.getUserName(), newPassword));
        user.setModifyTime(new Date());
        user.setModifier(CurrentUser.get().getId());
        this.getDao().updateModel(user);
    }

    @CacheEvict(value = CacheConstants.User, key = "#currentUser.id", allEntries = true)
    public void checkAndChangePassword(String password, String newPassword, String passwordConfirm) {
        Integer userId = CurrentUser.get().getId();
        User user = this.get(userId);
        if (null == user) {
            throw new CoryException(ErrorCode.SAVE_ERROR, "非法操作.");
        }
        if (!StringUtils.equals(user.getPassword(), passwordEncoder.encode(user.getUserName(), password))) {
            throw new CoryException(ErrorCode.SAVE_ERROR, "原密码不正确,请检查.");
        }
        newPassword = newPassword.trim();
        passwordConfirm = passwordConfirm.trim();
        checkPassword(newPassword);
        if (!StringUtils.equals(newPassword, passwordConfirm)) {
            throw new CoryException(ErrorCode.SAVE_ERROR, "两次输入的密码不一致,请检查.");
        }
        changePasswordDirectly(userId, newPassword);
    }

    private void checkPassword(String newPassword) {
        if (newPassword.length() < 6 || newPassword.length() > 32) {
            throw new CoryException(ErrorCode.SAVE_ERROR, "密码长度在6-32位之间.");
        }
    }

    public void updateLastLogonInfo(Integer id, String ip, boolean success, Date time) {
        userDao.updateLastLogonInfo(id, ip, success, time);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy