LoginController.java 12.3 KB
package com.glsx.usedcar.web.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.util.PhoneUtil;
import com.glsx.usedcar.module.account.domain.AccountInfo;
import com.glsx.usedcar.module.account.entity.Account;
import com.glsx.usedcar.module.account.service.AccountService;
import com.glsx.usedcar.module.security.domain.MaLoginRequest;
import com.glsx.usedcar.util.NameUtil;
import com.glsx.usedcar.web.AccountJwtProvider;
import com.glsx.usedcar.web.dto.LoginRequest;
import jakarta.annotation.Resource;
import jakarta.security.auth.message.AuthException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSession;
import me.chanjar.weixin.common.session.WxSessionManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.summerframework.core.exception.FieldException;
import org.summerframework.log.OplogType;
import org.summerframework.log.entity.Oplog;
import org.summerframework.log.service.OplogService;
import org.summerframework.security.Authenticity;
import org.summerframework.web.util.IpUtils;

import java.util.Objects;

import static com.glsx.usedcar.web.WebConstants.LOGIN_ACCOUNT;


@Slf4j
@RestController
@RequestMapping("/api")
public class LoginController extends LoginCommonController {

    @Resource
    private AccountService accountService;

    @Resource
    private OplogService oplogService;

    @Resource
    private AccountJwtProvider jwtProvider;

    @Resource
    private WxSessionManager wxSessionManager;

    @Resource
    private WxMaService wxMaService;

    @PostMapping("login")
    public Authenticity doLogin(@ModelAttribute LoginRequest loginRequest, HttpServletRequest request) {
        Account account;
        Authenticity authenticity = new Authenticity(0, "");
        try {
            String userName = loginRequest.getUserName();
            if (StringUtils.isNoneBlank(userName)) {
                //账户密码登录
                //手机号/邮箱登录密码登录
                boolean mobile = PhoneUtil.isMobile(userName);
                if (mobile) {
                    account = accountService.getAccountByMobile(userName);
                } else if (userName.contains("@")) {
//                    customer = customerService.getCustomerByEmail(userName);
                } else {
                    throw new AuthException("请输入正确的手机或者邮箱");
                }
//                if (Objects.isNull(account) || !new BCryptPasswordEncoder().matches(loginRequest.getPassword(), account.getPassword())) {
//                    throw new AuthException("手机或者邮箱或者密码错误");
//                }
            } else {
                //手机验证码登录
                account = accountService.getAccountByMobile(loginRequest.getMobile());
                if (Objects.isNull(account)) {
                    throw new AuthException("手机号码尚未注册");
                }
            }
        } catch (AuthException authException) {
            log.info("登录失败:{}", authException.getMessage());
//            authenticity.setSuccess(false);
//            authenticity.setErrorText(authException.getMessage());
            return authenticity;
        }

//        if (!account.isEnabled()) {
//            authenticity.setErrorText("账户被锁定,请联系管理员");
//            return authenticity;
//        }
//        oplogService.pushOplog(new Oplog(OplogType.LOGIN, "", "【客户端】登录成功", "", "", account.getAccountName(), IpUtils.getIpAddress(request)));
//        authenticity.setSuccess(true);
//        authenticity.setCustomer(account);
//        authenticity.setToken(jwtProvider.generateAccount(account));
//        request.getSession().setAttribute(LOGIN_ACCOUNT, account);
        return authenticity;
    }

    /**
     * <pre>
     * 小程序手机号登录
     * </pre>
     */
    @PostMapping("/ma/{appid}/phoneLogin")
    public AccountInfo phone(@PathVariable String appid, @RequestBody MaLoginRequest maLoginRequest, HttpSession httpSession, HttpServletRequest request) throws FieldException, WxErrorException {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
        }
        String code = maLoginRequest.getCode();
        String encryptedData = maLoginRequest.getEncryptedData();
        String iv = maLoginRequest.getIv();
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
        String sessionKey = session.getSessionKey();
        String openid = session.getOpenid();
        // 解密
        String phoneNumber;
        try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
            phoneNumber = phoneNoInfo.getPhoneNumber();
        } catch (Exception e) {
            log.error("小程序登录失败:解密失败", e);
            throw new WxErrorException("获得手机号码失败");
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
        AccountInfo accountInfo = new AccountInfo();
        Account account = accountService.getAccountByMobile(phoneNumber);
        if (Objects.isNull(account)) {
            // 创建新用户
            account = new Account();
            account.setOpenId(openid);
            account.setAccountName(phoneNumber);
            account.setMobile(phoneNumber);
            account.setNickName(NameUtil.getName());
            account.setEnabled(true);
            account.setCertifiedState(Account.CertifiedState.UNCERTIFIED);
            account.setAccountType(Account.AccountType.COMMON);
            account = accountService.addAccount(account);
        } else {
            if (!account.isEnabled()) {
                accountInfo.setStatus(403);
                accountInfo.setMessage("账户被锁定,请联系管理员");
                return accountInfo;
            }
            accountService.updateAccountLoginTime(account.getAccountId());
        }

        if (StringUtils.isNoneBlank(openid) && !openid.equals(account.getOpenId())) {
            accountService.updateWxOpenId(account.getAccountId(), openid);
        }
        oplogService.pushOplog(new Oplog(OplogType.LOGIN, "", "【小程序】登录成功", "", "", account.getAccountName(), IpUtils.getIpAddress(request)));
        accountInfo.setToken(jwtProvider.generateAccount(account));
        accountInfo.setAccountInfo(account);
        request.getSession().setAttribute(LOGIN_ACCOUNT, account);
        return accountInfo;
    }

//    /**
//     * 扫小程序码登录
//     */
//    @GetMapping("/maWxCode")
//    public WxCodeResult maWxCode() {
//        WxCodeResult wxCodeResult = new WxCodeResult();
//        String random = RandomStringUtils.randomAlphanumeric(16);
//        try {
//            byte[] trials = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes(random, null, false, "release", 320,
//                    true, null, true);
//            String encode = "data:image/png;base64," + Base64.encode(trials);
//            wxCodeResult.setSuccess(true);
//            wxCodeResult.setScene(random);
//            wxCodeResult.setWxCodeBase64(encode);
//        } catch (Exception e) {
//            e.printStackTrace();
//            wxCodeResult.setSuccess(false);
//            wxCodeResult.setMsg("小程序码获取失败,请刷新页面重试");
//        }
//        return wxCodeResult;
//    }

//    @GetMapping("/getMaWxCodeStatus")
//    public ResponseResult getMaWxCodeStatus(@RequestParam String scene, HttpServletRequest request) {
//        Account customer = redisService.getCodeLogin(scene);
//        if (Objects.nonNull(customer)) {
//            request.getSession().setAttribute(LOGIN_ACCOUNT, customer);
//            oplogService.pushOplog(new Oplog(OplogType.LOGIN, "", "【web扫码】登录成功", "", "", customer.getAccountName(), IpUtils.getIpAddress(request)));
//            Authenticity authenticity = new Authenticity(0, "");
////            authenticity.setCustomer(customer);
//            authenticity.setToken(jwtProvider.generateAccount(customer));
//            return new ResponseResult(ResponseResult.Result.SUCCESS, authenticity);
//        } else {
//            return new ResponseResult(ResponseResult.Result.FAILURE);
//        }
//    }


    /**
     * 个人账户中绑定微信号
     *
     * @param ticket
     * @param login
     * @return
     * @throws FieldException
     */
    @GetMapping("getQrCodeStatus")
    public boolean getQrCodeStatus(@RequestParam("qid") String ticket, @RequestAttribute(LOGIN_ACCOUNT) Account login) throws FieldException {
        WxSession session = wxSessionManager.getSession(ticket);
        if (Objects.nonNull(session)) {
            Object status = session.getAttribute("status");
            Object openId = session.getAttribute("openId");
            if ("ok".equals(status) && Objects.nonNull(openId)) {
                // 扫码通过
                String wxOpenId = openId.toString();
                Account customer = accountService.getAccountByOpenId(wxOpenId);
                if (Objects.isNull(customer)) {
                    accountService.updateWxOpenId(login.getAccountId(), wxOpenId);
                } else {
                    throw new FieldException("wx", null, "该微信号已绑定账户");
                }
                session.removeAttribute("status");
                return true;
            }
        }
        return false;
    }

    /**
     * 个人账户修改手机原号码校验
     *
     * @param loginRequest
     * @param request
     * @return
     * @throws FieldException
     */
    @PostMapping("checkSmsCode")
    public String checkSmsCode(@RequestBody LoginRequest loginRequest, HttpServletRequest request) throws FieldException {
        HttpSession httpSession = request.getSession();
        String mobile = loginRequest.getMobile();
        String smsCode = loginRequest.getSmsCode();
        log.info("原号码校验:{},{}", mobile, smsCode);
        String code;
        try {
            validateSmsCode(httpSession, mobile, smsCode);
            // 提交新号码时带回用于新号码校验
            code = new BCryptPasswordEncoder().encode(mobile);
            // 5分钟内有效
            httpSession.setAttribute(code, System.currentTimeMillis() + 60 * 5000);
        } catch (AuthException e) {
            log.info("原号码校验失败:{}", e.getMessage());
            throw new FieldException("smsCode", null, e.getMessage());
        }
        return code;
    }

    /**
     * 个人账户修改手机新号码校验
     *
     * @param loginRequest
     * @param request
     * @param customer
     * @return
     * @throws FieldException
     */
    @PostMapping("checkSmsCodeByNewMobile")
    public boolean checkSmsCodeByNewMobile(@RequestBody LoginRequest loginRequest, HttpServletRequest request, @RequestAttribute(LOGIN_ACCOUNT) Account customer) throws FieldException {
        HttpSession httpSession = request.getSession();
        String mobile = loginRequest.getMobile();
        String smsCode = loginRequest.getSmsCode();
        log.info("新号码校验:{},{}", mobile, smsCode);
        try {
            validateSmsCode(httpSession, mobile, smsCode);
            Long val = (Long) httpSession.getAttribute(loginRequest.getCode());
            customer = accountService.getAccountById(customer.getAccountId());
            if (Objects.nonNull(customer.getMobile()) && Objects.nonNull(val) && System.currentTimeMillis() - val > 0L) {
                throw new FieldException("smsCode", null, "原号码验证已过期,请重新修改");
            }
            customer.setMobile(mobile);
            accountService.updateMobile(customer);
        } catch (AuthException e) {
            log.info("新号码校验失败:{}", e.getMessage());
            throw new FieldException("smsCode", null, e.getMessage());
        }
        return true;
    }


}