1. 程式人生 > >Java實現郵箱驗證

Java實現郵箱驗證

(2)在AdminUserService中:
@Service
public class AdminUserService {
    @Autowired
    private AdminUserDao adminUserDao;
    @Autowired
    private AdminAuthDao adminAuthDao;

    private static String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機產生的字串

    private static long expireTime = 24 * 60 * 60 * 1000;

    public static String generateVcode(String cellphone) {
        StringBuilder tmp = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 6; i++) {
            tmp.append(getRandomString(rand.nextInt(36)));
        }
        return tmp.toString();
    }

    public static String getRandomString(int num){
        return String.valueOf(randString.charAt(num));
    }

    /**
     * 郵箱傳送驗證碼
     * @param userEmail
     * @return
     */
    public String genSendVecode(String userEmail) {
        // 1. 校驗郵箱是否正確
        // 2. 校驗郵箱是否合法
        // 3. 生成驗證碼
        // 4. 將驗證碼傳送至指定郵箱
        if (!RegexUtil.emailVerify(userEmail) || !userEmail.endsWith("@wolaibao.com") || !userEmail.endsWith("@zhongbao.email") ) {
            throw new WlbException("使用者賬戶錯誤,請重新輸入");
        }
        AdminUser adminUser = findAdminByAccount(userEmail);
        if (null == adminUser || StringUtils.isBlank(adminUser.getUsername())
                || adminUser.getStatus()!=0) {
            throw new WlbException("使用者賬戶錯誤,請重新輸入");
        }
        AdminAuth lastAuth = adminAuthDao.selectLastVcode(userEmail);
        if (lastAuth != null && System.currentTimeMillis() - lastAuth.getUpdateTime().getTime() < (1 * 60 * 1000)) {
            throw new WlbException("驗證碼已經發送至郵箱請勿重複獲取");
        }

        String vcode;
        if (lastAuth == null || System.currentTimeMillis() - lastAuth.getExpireTime() > 0) {
            vcode = generateVcode(userEmail);
            AdminAuth adminAuth = new AdminAuth();
            adminAuth.setEmail(userEmail);
            adminAuth.setVcode(vcode);
            adminAuth.setExpireTime(System.currentTimeMillis() + expireTime);
            adminAuthDao.insert(adminAuth);
        } else {
            vcode = lastAuth.getVcode();
            adminAuthDao.update(lastAuth);
        }
        MsgService.sendMail(userEmail, "管理後臺登入驗證", "管理後臺登入驗證碼為:" + vcode + "\n有效期為24小時!");
        return "我有效期為24來保管理後臺登入驗證已經發送至郵箱,小時,請注意保管驗證碼";
    }

    private AdminUser findAdminByAccount(String userEmail) {
        return adminUserDao.selectByAccount(userEmail);
    }
}