关于调用短信接口实现手机验证码密码重置功能

前端

<template>
  <div class="logo">
    <div class="l_main">
      <div class="w1000 clearfix">

        <div class="login">
          <p class="zhdl">
            <span style="color:#fe7a02;font-size:24px;">登录</span>{{ uiInfo_name }}
          </p>
          <form>
            <div id="err_area" class="login_err_panel">
              <span style="display:inline-block;vertical-align:middle;">
                <i class="icon24-login" style="margin-top:-0.2em;"></i>
              </span>
              <span id="err_tip"></span>
            </div>
            <div class="box" style="margin-top:20px;">
              <b class="userbg"></b>
              <input id="userId" v-model="loginForm.username" v-support placeholder="用户名" :autofocus="true" clearable
                     @blur="loginForm.username = inputChange($event)"/>
            </div>
            <div class="box pos" style="margin-bottom:40px;">
              <b class="passwordbg"></b>
              <input id="password1" v-model="loginForm.password" type="password" clearable
                     @blur="loginForm.password = inputChange($event)"/>
            </div>
            <a id="openLockBtn" href="javascript:;" class="btn_openLock" v-if="openLock" @click="dialogVisible = true">密码找回</a>
            <!--            <a id="restPwdBtn" href="javascript:;" class="btn_restPwd">重置密码</a>-->
            <a id="loginBtn" href="javascript:;" class="btn_login" @click="handleLogin">登录</a>
          </form>
        </div>
      </div>
    </div>
    <div class="l_foot">
      <p style="margin-top:8px;">系统要求:建议使用最新的chrome、firefox、IE8.0以上版本;建议分辨率:1920*1080</p>
      <p>{{ copyrightText }}</p>
    </div>
<!--    <el-dialog-->
<!--      title="账号解锁"-->
<!--      :visible.sync="dialogVisible"-->
<!--      width="30%"-->
<!--    >-->
<!--      <div style="display: inline-block">-->
<!--        <input placeholder="请输入手机号" v-model="openLockForm.AccNbrNum"/>-->
<!--        <a id="sendInfo" href="http://195.4.100.112:10002/esb/admin/SmsPush/1.0?authcode=R1hfVUNDUCNAYXV0aEAjM2ZZZFFJa2Q">发送短信</a>-->
<!--      </div>-->
<!--          <el-input placeholder="请输入验证码" v-model="openLockForm.OrderContent"></el-input>-->
<!--          <span slot="footer" class="dialog-footer">-->
<!--    <el-button @click="dialogVisible = false">取 消</el-button>-->
<!--    <el-button type="primary" @click="handelOpenLock">解 锁</el-button>-->
<!--  </span>-->
<!--    </el-dialog>-->
    <el-dialog
      title="账号解锁"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form :model="openLockForm" :rules="rules" ref="ruleForm" label-width="100px" :inline="true" status-icon>
        <el-form-item label="手机号码" prop="AccNbr">
            <el-input v-model="openLockForm.AccNbr" clearable>
              <template slot="append">
                <el-button type="success" @click="sendSMS" v-if="!isDisabled">{{content}}</el-button>
                <el-button type="success" v-if="isDisabled">{{content}}</el-button>
              </template>
            </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="OrderContent">
          <el-input v-model="openLockForm.OrderContent" clearable></el-input>
        </el-form-item>
<!--        <el-form-item label="新密码" prop="newPassword">-->
<!--          <el-input v-model="openLockForm.newPassword" type="password" show-password clearable></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="确认密码" prop="confirmPassword">-->
<!--          <el-input v-model="openLockForm.confirmPassword" type="password" show-password clearable></el-input>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handelOpenLock('ruleForm')">解 锁</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import {login,sendSms,validCode} from '../../../api/login'
  import $ from 'jquery'
  import md5 from 'js-md5'

  export default {
    name: 'Login',
    data() {
      var validatephone=(rules, AccNbr, callback)=>{
        var phoneReg=/^1[3-9]\d{9}$/
          if (!phoneReg.test(AccNbr)){
              callback(new Error('请输入正确的手机号!'))
          }
          callback();
      }
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.openLockForm.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        uiInfo_name: window.SITE_CONFIG['uiInfo_name'],
        copyrightText: window.SITE_CONFIG['copyrightText'],
        loginForm: {
          username: '',
          password: ''
        },
        isDisabled: false, //控制按钮是否可以点击(false:可以点击,true:不可点击)
        content: '获取短信验证码', // 发送验证码按钮的初始显示文字
        timer: null,
        count: '',
        openLock: false,
        dialogVisible: false,
        openLockForm: {
          AccNbr:'',
          LanId: "1100",
          SceneId: "428",
          ContentParam: null,

          OrderContent:'',//验证码
          newPassword:'',
          confirmPassword:'',
        },
        rules:{
          AccNbr:[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            {validator: validatephone, trigger: 'blur' },
          ],
          OrderContent: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
          ],
          newPassword: [
            { required: true, message: '请输入密码', trigger: 'blur' },
          ],
          confirmPassword: [
            { required: true, message: '请确认密码', trigger: 'blur' },
            {validator: validatePass2, trigger: 'blur' },
          ],
        }
      }
    },
    methods: {
      handelOpenLock(formName){
        this.$refs[formName].validate((valid)=>{
          if (valid) {
            //提交表单
            validCode({
              'valid_code': this.openLockForm.OrderContent,
              'user_id':this.loginForm.username
            },true).then(data =>{
              if (data.msgFlag) {
                this.dialogVisible=false
                this.$message.success(data.msgDesc,3)
                this.openLock = false
                $('#err_area').hide()
                $('#err_tip').html("")
              } else {
                this.$message.error(data.msgDesc)
              }
            })
          } else {
            return false;
          }
        })
      },
      sendSMS(){
        let vm = this
        // 控制倒计时及按钮是否可以点击
        const TIME_COUNT = 60
        vm.count = TIME_COUNT
        vm.timer = window.setInterval(() => {
          if (vm.count > 0 && vm.count <= TIME_COUNT){
            // 倒计时时不可点击
            vm.isDisabled = true
            // 计时秒数
            vm.count--
            // 更新按钮的文字内容
            vm.content = vm.count + 's后重新获取'
          } else {
            // 倒计时完,可点击
            vm.isDisabled = false
            // 更新按钮文字内容
            vm.content = '获取短信验证码'
            // 清空定时器!!!
            clearInterval(vm.timer)
            vm.timer = null
          }
        }, 1000)
        //发送短信
        sendSms({
          'phone': this.openLockForm.AccNbr,
          'user_id':this.loginForm.username
        }, true).then(data => {
          if (data.msgFlag) {
            debugger
            this.$message.success("验证码发送成功!")
          } else {
            this.$message.error(data.msgDesc)
          }
        }).catch(data => {
          this.$message.error("验证码发送失败!")
        })
      },
      handleLogin() {
        const _this = this
        if (this.loginForm.username === '') {
          $('#err_area').show()
          $('#err_tip').html('您还没有输入用户名!')
          return
        }
        if (this.loginForm.password === '') {
          $('#err_area').show()
          $('#err_tip').html('您还没有输入密码!')
          return
        }
        const password = md5(this.loginForm.username + '' + this.loginForm.password)
        this.loading = true
        login({
          'userId': this.loginForm.username,
          'password': password
        }, true).then(data => {
          if (data.msgFlag) {
            _this.$cookie.set('token', data.token)
            localStorage.setItem('tokenValue', data.token)
            if (this.redirect && this.redirect.match(/iframe\/(\S*)\//) && this.redirect.match(/iframe\/(\S*)\//)[1]) {
              const url = encodeURIComponent(this.redirect.match(/iframe\/(\S*)\//)[1]) // 截取两个字符串之间的内容
              const name = this.redirect.substring(this.redirect.lastIndexOf('\/') + 1, this.redirect.length)
              this.redirect = '/iframe/' + url + '/' + name
            }
            this.$router.push({path: this.redirect || '/'})
          } else {
            $('#err_area').show()
            $('#err_tip').html(data.msgDesc)
            $('#password1').val('')
            if (data.msgDesc === '账户被锁定!') {
              this.openLock = true
              this.$router.push({path: '/login'})
            }else{
              this.openLock =false
            }
          }
        }).catch(data => {
          // console.log(data)
          this.loading = false
          $('#err_area').show()
          $('#err_tip').html(data.msgDesc)
          $('#password1').val('')
        })
      }
    }
  }
</script>
<style src="../../../../src/res/css/login.css" scoped>
</style>
<style src="../../../../src/res/css/reset.css" scoped>
</style>
<style scoped>
  .logo {
    background: url("../../../../src/res/images/login_background.jpg");
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    min-width: 1000px;
    z-index: -10;
    zoom: 1;
    background-color: #fff;
    background-repeat: no-repeat;
    background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-position: center 0;
  }

  .btn_restPwd {
    color: red;
  }

  .btn_openLock {
    color: red;
  }
</style>

后端

1.controller

package usi.sys.controller;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import usi.sys.dto.SendSmsParamsDTO;
import usi.sys.dto.StaffInfo;
import usi.sys.entity.Staff;
import usi.sys.service.SendSms;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import usi.sys.service.StaffService;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/sendSms")
public class    SmsApiController {
    @Autowired
    private SendSms sendSms;
    @Resource
    private StaffService staffService;

    private static String Url = "自己的url";

    @RequestMapping(
            value = {"/send.action"},
            method = {RequestMethod.POST}
    )
    public  Map<String, Object>  sendSms(@RequestBody Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        String phone= map.get("phone").toString();
        String user_id= map.get("user_id").toString();
        //检查phone 是否匹配
        List<Map<String, Object>> list=staffService.getMobileNumByUserId(user_id);
        if(list.size()==0){
            result.put("msg", null);
            result.put("code", 200);
            result.put("msgFlag", false);
            result.put("msgDesc", "花名册内未找出此登录工号信息,请联系管理员核对花名册信息");
            return result;
        }else {
            String phonechecked=list.get(0).get("FRE_FIELD2").toString();
            if(!phonechecked.equals(phone)){
                result.put("msg", null);
                result.put("code", 200);
                result.put("msgFlag", false);
                result.put("msgDesc", "您输入的手机号与花名册手机号码不匹配,请核对");
                return result;
            }
        }
        InputStream inputStream = null;
        try {
            int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);

            String content = new String("您的验证码是:" + mobile_code + "。(6分钟有效)请不要把验证码泄露给其他人。");
            String params = "{\n" +
                    "\"AccNbr\":\"" + phone + "\",    \n" +
                    "\"LanId\":\"1100\",\n" +
                    "\"SceneId\":\"428\",\n" +
                    "\"OrderContent\":\"" + content + "\",\n" +
                    "\"ContentParam\":null\n" +
                    "\n" +
                    "}";
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(Url);
            postMethod.setRequestHeader("Content-Type", "application/json");
            RequestEntity requestEntity = new StringRequestEntity(params, "application/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            httpClient.executeMethod(postMethod);// 执行请求
            inputStream = postMethod.getResponseBodyAsStream();// 获取返回的流
            BufferedReader br = null;
            StringBuffer buffer = new StringBuffer();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
//            log.info("接口返回内容为:" + buffer);
            System.out.println(buffer.toString());
            JSONObject object=JSONObject.parseObject(buffer.toString());
            if(  "0000".equals(object.get("RespCode"))){
               return  staffService.updateVaildCode(user_id,mobile_code+"");
                //存验证码 失效时间 到数据库
            }else {	result.put("msg", null);
                    result.put("code", 200);
                    result.put("msgFlag", false);
                    result.put("msgDesc", "验证码发送失败!");
            }
        } catch (Exception e) {
//            log("请求异常" +e.getMessage());
            result.put("msg", null);
            result.put("code", 200);
            result.put("msgFlag", false);
            result.put("msgDesc", "验证码发送失败!");
            throw new RuntimeException(e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @RequestMapping(
            value = {"/validCode.action"},
            method = {RequestMethod.POST}
    )
    public  Map<String, Object>  validCode(@RequestBody Map<String, Object> map) {
        Date date =new Date();
        Map<String, Object> result = new HashMap<String, Object>();
        String valid_code= map.get("valid_code").toString();
        String user_id= map.get("user_id").toString();
        StaffInfo staff =staffService.queryStaffByUserId(user_id);
        if(!valid_code.equals(staff.getValidCode())){
            //reset
            result.put("msg", null);
            result.put("code", 200);
            result.put("msgFlag", false);
            result.put("msgDesc", "验证码错误");
        }else if(date.getTime()-staff.getValidCodeEndTime().getTime()>(1000*60*6)) {
            //
            result.put("msg", null);
            result.put("code", 200);
            result.put("msgFlag", false);
            result.put("msgDesc", "验证码已超时");
        }else{
            Staff staff1=new Staff();
            staff1.setUserId(staff.getUserId());
            staff1.setStaffId(staff.getStaffId());
            staffService.resetPwd(staff1);
            result.put("msg", null);
            result.put("code", 200);
            result.put("msgFlag", true);
            result.put("msgDesc", "密码重置成功");
        }
        return result;
    }

//    @RequestMapping(
//            value = {"/getMobile.action"},
//            method = {RequestMethod.POST}
//    )
//    public  Map<String, Object> getMobile(@RequestBody Map<String, Object> map) {
//        staffService.queryStaffByUserId();
//        return null;
//    }


}

2.service

/**
		查询花名册存放的手机号码
	 */
	public List<Map<String, Object>> getMobileNumByUserId(String userId){
		return staffDao.getMobileNumByUserId(userId);
	}
@Transactional(rollbackFor=Exception.class)
	public Map<String, Object> updateVaildCode(String user_id,  String vaildCode) {
		Map<String, Object> magMap = new HashMap<String, Object>();
		if(staffDao.updateVaildCode(user_id, vaildCode)==1) {
			magMap.put("msg", null);
			magMap.put("code", 200);
			magMap.put("msgFlag", true);
			magMap.put("msgDesc", "验证码发送成功!");
		} else {
			magMap.put("msg", null);
			magMap.put("code", 200);
			magMap.put("msgFlag", false);
			magMap.put("msgDesc", "系统异常,稍后重试!");
		}
		return magMap;
	}
public StaffInfo queryStaffByUserId(String userId){
		return staffDao.queryStaffByUserId(userId);
	}
/**
	 * 重置密码
	 * @param staff
	 */
	@Transactional(rollbackFor=Exception.class)
	public void resetPwd(Staff staff){
		//密码加盐加密
		String password = CommonUtil.getMd5(staff.getUserId()+ConstantUtil.DEFAULT_PASSWORD);
		staff.setPassword(password);
		staffDao.resetPwd(staff);
	}

3.dao

 /**
     * 通过用户id,获取其手机号码
     * @param userId
     * @return
     */
    @Override
    public List<Map<String, Object>> getMobileNumByUserId(String userId) {
        String sql = "SELECT t.FRE_FIELD2 FROM sys_base_info_one t WHERE t.JOB_NUMBER = ?";
        try {
            return this.getJdbcTemplate().queryForList(sql,  new Object[]{userId});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 @Override
    public int updateVaildCode(String user_id, String vaildCode) {
        String sql = "update sys_staff set valid_code=?, valid_code_end_time= date_add(now(), interval 6 minute) where user_id=?";
        return this.getJdbcTemplate().update(sql, vaildCode, user_id);
    }
@Override
    public StaffInfo queryStaffByUserId(String userId) {
        String sql = "select t1.staff_id,"
                + "t1.valid_code_end_time,"
                + "t1.valid_code,"
                + "t1.user_id,"
                + "t1.org_id,"
                + "t1.operator_name,"
                + "t1.password,"
                + "t1.duration,"
                + "t1.pwd_last_mod_time,"
                + "t1.station_code,"
                + "t1.is_employee,"
                + "t1.is_onduty,"
                + "t1.is_lock,"
                + "t2.mobile_nbr,"
                + "t3.org_name,"
                + "t3.org_seq,"
                + "(case "
                + "when ( char_length(t3.org_seq) - char_length( replace(t3.org_seq, '.' , ''))) >1 then "
                + "substr(t3.org_seq,instr(t3.org_seq, '.') + 1, "
                + "locate('.',t3.org_seq," + (ConstantUtil.FIRST_LEVEL_ORG_LENGTH + 2) + ") - instr(t3.org_seq, '.') - 1) "
                + "else "
                + "substr(t3.org_seq, 0, instr(t3.org_seq, '.') - 1) "
                + "end) area_org_id,"
                + "substr(t3.org_seq, 0, instr(t3.org_seq, '.') - 1) root_org_id, "
                + "(case when (unix_timestamp(now())-unix_timestamp(lst_err_pwd_time))<1800 and is_lock=1 then 1 else 0 end) real_lock "
                + "from sys_staff t1, sys_staff_attr t2, sys_org t3 "
                + "where t1.staff_id = t2.staff_id "
                + "and t1.org_id = t3.org_id " + "and t1.user_id = ? "
                + "and t1.status = 1 " + "and t1.is_onduty = 1";

        List<StaffInfo> staffs = this.getJdbcTemplate().query(sql, new RowMapper<StaffInfo>() {
            @Override
            public StaffInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                StaffInfo staff = new StaffInfo();
                staff.setStaffId(rs.getLong("staff_id"));
                staff.setUserId(rs.getString("user_id"));
                staff.setOrgId(rs.getLong("org_id"));
                staff.setMobileNum(rs.getString("mobile_nbr"));
                staff.setOrgSeq(rs.getString("org_seq"));
                staff.setAreaOrgId(rs.getLong("area_org_id"));
                staff.setRootOrgId(rs.getLong("root_org_id"));
                staff.setOrgName(rs.getString("org_name"));
                staff.setOperatorName(rs.getString("operator_name"));
                staff.setPassword(rs.getString("password"));
                staff.setDuration(rs.getInt("duration"));
                if (rs.getTimestamp("pwd_last_mod_time") != null) {
                    staff.setPwdlastModTime(new Date(rs.getTimestamp("pwd_last_mod_time").getTime()));
                } else {
                    staff.setPwdlastModTime(null);
                }
                staff.setRealLock(rs.getInt("real_lock"));
                staff.setStationCode(rs.getString("station_code"));
                staff.setIsEmployee(rs.getInt("is_employee"));
                staff.setIsOnduty(rs.getInt("is_onduty"));
                staff.setIsLock(rs.getInt("is_lock"));
                staff.setValidCode(rs.getString("valid_code"));
                staff.setValidCodeEndTime(rs.getTimestamp("valid_code_end_time"));
                return staff;
            }
        }, userId);
        return staffs.size() == 0 ? null : staffs.get(0);
    }
@Override
    public void resetPwd(final Staff staff) {
        String sql = "update sys_staff set password=?,is_lock=0,PWD_ERR_TIMES=0 where staff_id=? ";
        this.getJdbcTemplate().update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1, staff.getPassword());
                ps.setLong(2, staff.getStaffId());
            }
        });
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值