MobileUserController.java 7.81 KB
package com.huaheng.mobile.general;

import com.huaheng.auth.form.LoginBody;
import com.huaheng.common.core.constant.CacheConstants;
import com.huaheng.common.core.constant.Constants;
import com.huaheng.common.core.constant.UserConstants;
import com.huaheng.common.core.domain.R;
import com.huaheng.common.core.enums.UserStatus;
import com.huaheng.common.core.exception.BaseException;
import com.huaheng.common.core.utils.IdUtils;
import com.huaheng.common.core.utils.StringUtils;
import com.huaheng.common.core.web.domain.AjaxResult;
import com.huaheng.common.redis.service.RedisService;
import com.huaheng.common.security.utils.SecurityUtils;
import com.huaheng.system.api.RemoteCompanyService;
import com.huaheng.system.api.RemoteLogService;
import com.huaheng.system.api.RemoteUserService;
import com.huaheng.system.api.RemoteWarehouseService;
import com.huaheng.system.api.domain.Company;
import com.huaheng.system.api.domain.SysUser;
import com.huaheng.system.api.model.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.huaheng.common.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Enzo Cotter
 * @date 2019/12/15
 */
@RestController
@Api(tags = {"移动端用户信息"}, value = "移动端用户信息MobileUserController")
public class MobileUserController extends BaseController {

    @Resource
    private RemoteCompanyService companyService;
    @Resource
    private RemoteLogService remoteLogService;
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private RemoteWarehouseService warehouseService;
    @Autowired
    private RedisService redisService;

    private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60 * 60;
    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
    protected static final long MILLIS_SECOND = 1000;

    @ApiOperation(value = "用户登录")
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录get
        LoginUser userInfo = login(form.getUsername(), form.getPassword(), form.getWarehouseCode());
        // 获取登录token
        return R.ok(createToken(userInfo));
    }

    @PostMapping("/getCompanyInfo")
    @ApiOperation("获取公司信息")
    public AjaxResult getCompanyInfo(@RequestBody  Map<String, String> param){
        String userId = param.get("userId");
        String warehouseCode = param.get("warehouseCode");
        List<Company> companies = companyService.selectCompanyByCurrentUserId(userId, warehouseCode);
        List<CompanyInfo> companyInfos = new ArrayList<CompanyInfo>();
        for(Company company : companies) {
            companyInfos.add(new CompanyInfo(company.getId(), company.getCode(), company.getName()));
        }
        return AjaxResult.success(companyInfos);
    }

    /**
     * 登录
     */
    public LoginUser login(String username, String password, String warehouseCode) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password, warehouseCode)) {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new BaseException("用户/密码必须填写");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new BaseException("用户名不在指定范围");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, warehouseCode);
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new BaseException("登录用户:" + username + " 不存在");
        }
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "对不起,您的账号已被删除");

            throw new BaseException("对不起,您的账号:" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户已停用,请联系管理员");
            throw new BaseException("对不起,您的账号:" + username + " 已停用");
        }
        if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户密码错误");
            throw new BaseException("用户不存在/密码错误");
        }
        remoteLogService.saveLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser)
    {
        // 生成token
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        loginUser.setUserid(loginUser.getSysUser().getUserId());
        loginUser.setUsername(loginUser.getSysUser().getUserName());
        loginUser.setSysUser(null);
        refreshToken(loginUser);

        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", token);
        map.put("expires_in", EXPIRE_TIME);
        map.put("warehouseCode", loginUser.getWarehouseCode());
        map.put("companies", loginUser.getCompanies());
        map.put("userId", loginUser.getUserid());
        redisService.setCacheObject(ACCESS_TOKEN + token, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
        return map;
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public Long refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_SECOND);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
        return EXPIRE_TIME;
    }

    private String getTokenKey(String token)
    {
        return ACCESS_TOKEN + token;
    }





//
//    @PostMapping("/reservation")
//    public AjaxResult reservation(String localDate, String warehouseCode) {
//        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        LocalDate date2 = LocalDate.parse(localDate, fmt);
//        return AjaxResult.success(reservationService.reservationTime(date2, warehouseCode));
//    }
//
//    /**
//     * 新增保存预约
//     */
//    @ApiOperation(value = "新增预约 ", notes = "新增预约 ", httpMethod = "POST")
//    @PostMapping("/addSave")
//    @ResponseBody
//    public AjaxResult addSave(@RequestBody @ApiParam(value="WarehouseId和warehouseCode的Map集合") Reservation reservation) {
//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
//        reservation.setBeginTime(LocalDateTime.parse(reservation.getUserDef1()));
//        reservation.setEndTime(LocalDateTime.parse(reservation.getUserDef2()));
//        reservation.setUserDef1(null);
//        reservation.setUserDef2(null);
//        return toAjax(reservationService.save(reservation));
//    }
}