UserService.java 2.58 KB
package cn.com.glsx.app.modules.service;

import cn.com.glsx.app.common.enums.AuthType;
import cn.com.glsx.app.common.enums.LoginType;
import cn.com.glsx.app.modules.entity.UserAuthRel;
import cn.com.glsx.app.modules.entity.UserThirdAuth;
import cn.com.glsx.app.modules.mapper.UserAuthRelMapper;
import cn.com.glsx.app.modules.mapper.UserLocalAccountMapper;
import cn.com.glsx.app.modules.mapper.UserThirdAuthMapper;
import cn.com.glsx.app.modules.model.AppUser;
import cn.hutool.core.lang.UUID;
import com.glsx.plat.common.utils.ObjectUtils;
import com.glsx.plat.jwt.base.ComJwtUser;
import com.glsx.plat.jwt.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private JwtUtils<ComJwtUser> jwtUtils;

    @Resource
    private UserAuthRelMapper userAuthRelMapper;

    @Resource
    private UserThirdAuthMapper userThirdAuthMapper;

    @Resource
    private UserLocalAccountMapper userLocalAccountMapper;

    /**
     * 生成带用户信息的token
     *
     * @param user
     * @return
     */
    public String createToken(AppUser user) {
        Assert.notNull(user, "获取当前用户信息失败");
        String uuid = UUID.randomUUID().toString(); //JWT 随机ID,做为验证的key
        String jwtId = jwtUtils.getApplication() + ":" + uuid + "_" + jwtUtils.JWT_SESSION_PREFIX + user.getUserId();
        ComJwtUser jwtUser = new ComJwtUser();
        jwtUser.setApplication(jwtUtils.getApplication());
        jwtUser.setJwtId(jwtId);
        jwtUser.setUserId(String.valueOf(user.getUserId()));
        jwtUser.setAccount(user.getAccount());
        jwtUser.setBelong(user.getUserType());
        Map<String, Object> userMap = (Map<String, Object>) ObjectUtils.objectToMap(jwtUser);
        return jwtUtils.createToken(userMap);
    }

    public AppUser getAppUserByUserId(Long userId) {
        //获取用户本地信息
        return userLocalAccountMapper.selectAppUserByUserId(userId);
    }

    public AppUser getAppUserByAuthId(LoginType loginType, Long authId) {
        //获取具体第三方授权
        UserThirdAuth thirdAuth = userThirdAuthMapper.selectByLoginTypeAndAuthId(loginType.getType(), authId);
        //获取第三方授权关联
        UserAuthRel userAuthRel = userAuthRelMapper.selectByAuthTypeAndAuthId(AuthType.THIRD.getType(), thirdAuth.getId());
        //获取用户本地信息
        return this.getAppUserByUserId(userAuthRel.getUserId());
    }

}