shiro (四) spring结合 LoginService

package com.miv.shiro.login.service;

import java.util.Date;

import java.util.List;

import javax.mail.MessagingException;

import javax.mail.internet.MimeMessage;

import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authc.LockedAccountException;

import org.apache.shiro.authc.UnknownAccountException;

import org.apache.shiro.subject.Subject;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.mail.javamail.MimeMessageHelper;

import org.springframework.stereotype.Service;

import com.miv.core.constant.DatabaseConstants;

import com.miv.core.json.JsonResponse;

import com.miv.core.utils.CommonUtils;

import com.miv.core.utils.DateUtils;

import com.miv.core.utils.FreeMarkerUtils;

import com.miv.core.utils.PropertiesUtil;

import com.miv.dao.PasswordDao;

import com.miv.dao.UsersDao;

import com.miv.entity.Passwords;

import com.miv.entity.User;

import com.miv.form.LoginView;

import com.miv.shiro.common.MIVshiroToken;

import com.miv.shiro.common.ShiroEncryption;

@Service

public class LoginService {

    final Logger logger = LoggerFactory.getLogger(LoginService.class);

    @Autowired

    private UsersDao userDao;

    @Autowired

    private PasswordDao passwordDao;

    @Autowired

    private org.springframework.mail.javamail.JavaMailSenderImpl mailSender;

    // 通过username和password登录

    public User findUserByUsernameAndPassword(User user) throws Exception {

        return userDao.findUserByUsernameAndPassword(user);

    }

    // 通过username查询属性

    public User findUserByUsername(User user) throws Exception {

        return userDao.findUserByUsername(user);

    }

    public User findAllByLoginName(String loginName) throws Exception {

        return userDao.getUnique(User.class, "loginName", loginName);

    }

    // 验证密码修改后登录

    public boolean checkPassword(String loginName) throws Exception {

        User user = new User();

        user.setLoginName(loginName);

        userDao.findUserByUsername(user);

        if (DatabaseConstants.PASSWORD_STATUS_1.intValue() == user.getPassswordStatus()) {

            return true;

        } else {

            return false;

        }

    }

    // 停用后自动登录

    public boolean checkDisableStatus(String loginName) {

        User user = new User();

        user.setLoginName(loginName);

        userDao.findUserByUsername(user);

        if (DatabaseConstants.STATUS_2.intValue() == user.getStatus()) {

            return true;

        } else {

            return false;

        }

    }

    public boolean updatePasswordStatus(User user) throws Exception {

        if (user.getPassswordStatus() == DatabaseConstants.PASSWORD_STATUS_1.intValue()) {

            user.setPassswordStatus(DatabaseConstants.PASSWORD_STATUS_0);

            userDao.update(user);

            return true;

        } else {

            return false;

        }

    }

    public JsonResponse findLogin(boolean rememberMe, LoginView user) throws Exception {

        JsonResponse jsonResponse = new JsonResponse();

        jsonResponse.setSuccess(true);

        Subject subject = SecurityUtils.getSubject();

        String password = CommonUtils.getMD5(user.getPassword());

        Integer ROLE_CODE = ShiroEncryption.decryption(user.get_cmd());

        MIVshiroToken token = new MIVshiroToken(user.getLoginName(), password, ROLE_CODE, false);

        token.setRememberMe(rememberMe);

        try {

            subject.login(token);

        } catch (UnknownAccountException uae) {

            logger.info(String.format("who %s , where %s , warn : %s", token.getUsername(), token.getHost(), uae));

            jsonResponse.setSuccess(false);

            jsonResponse.setData("用户名或密码错误,请重试。");

        } catch (LockedAccountException lae) {

            logger.warn(String.format("who %s , where %s , warn : %s", token.getUsername(), token.getHost(), lae));

            jsonResponse.setSuccess(false);

            jsonResponse.setData("帐号已被停用,请联系管理员!");

        } catch (Exception ee) {

            logger.info(String.format("who %s , where %s , warn : %s", token.getUsername(), token.getHost(), ee));

            jsonResponse.setSuccess(false);

            jsonResponse.setData("用户名或密码错误,请重试。");

        }

        if (jsonResponse.isSuccess()) {

            // 默认shiro使用request.getSession

            User user_ = this.findAllByLoginName(user.getLoginName());

            if (rememberMe) {// 修改密码后成功记住我登陆

                user_.setPassswordStatus(DatabaseConstants.PASSWORD_STATUS_0);

                this.updatePasswordStatus(user_);

            }

            subject.getSession(false).setAttribute("principals", user_);

            jsonResponse.setSuccess(true);

            jsonResponse.setData(ShiroEncryption.decryptionURL(ROLE_CODE, ShiroEncryption.SUCCESS));

        }

        return jsonResponse;

    }

    /**

     * 第一步:校验用户名与邮箱准确性; 第二步:更新所有以前的找回密码状态为失效 ;第三步:插入新的找回密码

     * 

     * @param loginName

     * @param email

     * @return

     * @throws Exception

     */

    public boolean insertApplyPassword(String loginName, String email) throws Exception {

        boolean flag = false;

        List<User> list = passwordDao.check(loginName, email);// 1

        if (list != null && list.size() > 0) {

            flag = true;

        } else {

            return false;

        }

        flag = passwordDao.updateApplyPassword(loginName, DatabaseConstants.PASSWORD_IS_VALID_0);// 2

        if (!flag) {

            return false;

        }

        Passwords password = new Passwords();// 3

        Date date = new Date();

        password.setCreatedTime(date);

        password.setEmail(email);

        password.setIndate(org.apache.commons.lang.time.DateUtils.addDays(date, 1));

        password.setIsValid(DatabaseConstants.PASSWORD_IS_VALID_1);

        password.setLoginName(loginName);

        password.setOldPassword(list.get(0).getPassword());

        Passwords passwords = (Passwords) passwordDao.save(password);

        passwords.setApplyKey(CommonUtils.getMD5(CommonUtils.getMD5(passwords.getId().toString())));

        passwordDao.update(passwords);

        flag = this.mailSender(loginName, email, passwords);

        return flag;

    }

    /**

     * @throws Exception

     * @throws MessagingException

     * 

     */

    public boolean mailSender(String loginName, String email, Passwords passwords) {

        // 生成HTML

        String sourceDir = FreeMarkerUtils.getSourceDir();

        String sourceName = "test.ftl";

        String targetDir = PropertiesUtil.getProperties("html_file_patch");

        String targetName = passwords.getApplyKey() + ".html";

        String data = PropertiesUtil.getProperties("http_miv") + passwords.getApplyKey();

        try {

            FreeMarkerUtils.generateHtml(sourceDir, sourceName, targetDir, targetName, data);

        } catch (Exception e1) {

            // TODO Auto-generated catch block

            e1.printStackTrace();

            return false;

        }

        try {

            MimeMessage mailMessage = mailSender.createMimeMessage();

            // 设置utf-8或GBK编码,否则邮件会有乱码

            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

            // 设置收件人,寄件人

            messageHelper.setTo(email);

            messageHelper.setFrom(mailSender.getUsername());

            messageHelper.setSubject("测试HTML邮件!");

            // true 表示启动HTML格式的邮件

            messageHelper.setText(FreeMarkerUtils.getHtml(targetDir, targetName), true);

            // 发送邮件

            mailSender.send(mailMessage);

            return true;

        } catch (MessagingException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

            return false;

        }

    }

    /**

     * 查用户名

     * 

     * @param applyKey

     * @return

     */

    public boolean updateApplyPassword(String applyKey) {

        boolean flag = false;

        Date sender = new Date();

        Passwords passwords = passwordDao.getUnique(Passwords.class, "applyKey", applyKey);

        flag = passwords != null && DateUtils.greaterThan(passwords.getIndate(), sender)

                && (DatabaseConstants.PASSWORD_IS_VALID_1.intValue() == passwords.getIsValid());

        if (flag) {

            passwords.setIsValid(DatabaseConstants.PASSWORD_IS_VALID_2);

            passwords.setRetrieveTime(sender);

            passwordDao.update(passwords);

        }

        return flag;

    }

    /**

     * 校验applyKey,并更改密码

     * 

     * @param applyKey

     * @return

     */

    public boolean updateApplyPassword(String applyKey, String newPassword) {

        boolean flag = false;

        Date sender = new Date();

        Passwords passwords = passwordDao.getUnique(Passwords.class, "applyKey", applyKey);

        flag = passwords != null && DateUtils.greaterThan(passwords.getIndate(), sender)

                && (DatabaseConstants.PASSWORD_IS_VALID_2.intValue() == passwords.getIsValid());

        if (flag) {

            userDao.updatePassword(passwords.getLoginName(), CommonUtils.getMD5(newPassword));

            passwords.setNewPassword(newPassword);

            passwords.setIsValid(DatabaseConstants.PASSWORD_IS_VALID_0);

            passwords.setRetrieveTime(sender);

            passwordDao.update(passwords);

        }

        return flag;

    }

    public User findUserByApplyKey(String applyKey) {

        Passwords passwords = passwordDao.getUnique(Passwords.class, "applyKey", applyKey);

        User user = new User();

        user.setLoginName(passwords.getLoginName());

        user = userDao.findUserByUsername(user);

        return user;

    }

}

相关推荐