Search in sources :

Example 1 with SysUser

use of com.tansci.domain.system.SysUser in project tansci by typ1805.

the class AuthorizedServiceImpl method wxCallback.

@Override
public void wxCallback(String code, String state) {
    AuthorizedVo authorizedVo = AuthorizedVo.builder().msg("登录成功").status(200).build();
    // 获取 access_token
    String accessTokenUrl = AuthorizedConfig.WX_BASE_ACCESS_TOKEN_URL + "?appid=" + AuthorizedConfig.WX_APP_ID + "&secret=" + AuthorizedConfig.WX_APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
    log.info("=======获取 access_token URL:{}==============", accessTokenUrl);
    String tokenResult = restTemplate.getForObject(accessTokenUrl, String.class);
    JSONObject tokenJson = JSON.parseObject(tokenResult);
    log.info("========获取 access_token 结果========:{}", tokenJson);
    if (Objects.isNull(tokenResult) || Objects.isNull(tokenJson.get("openid"))) {
        authorizedVo.setMsg("获取access_token失败");
        authorizedVo.setStatus(500);
    }
    String accessToken = String.valueOf(tokenJson.get("access_token"));
    String openid = String.valueOf(tokenJson.get("openid"));
    // 查询数据库当前用用户是否曾经使用过微信登录
    SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getOpenId, openid));
    if (Objects.isNull(user)) {
        log.info("==========新用户注册============");
        // 访问微信的资源服务器,获取用户信息
        String baseUserInfoUrl = AuthorizedConfig.WX_BASE_USER_INFO_URL + "?access_token=" + accessToken + "&openid=" + openid;
        String userInfo = restTemplate.getForObject(baseUserInfoUrl, String.class);
        JSONObject userJson = JSON.parseObject(userInfo);
        log.info("========获取微信用户信息结果========:{}", userJson);
        if (Objects.isNull(userInfo) || Objects.isNull(userJson.get("nickname"))) {
            authorizedVo.setMsg("获取微信用户信息失败");
            authorizedVo.setStatus(500);
        }
        String nickname = String.valueOf(userJson.get("nickname"));
        try {
            nickname = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("=====nickname 转码失败======={}", e);
        }
        // 向数据库中插入一条记录
        user = SysUser.builder().username(UUIDUtils.getUUID(15)).nickname(nickname).openId(openid).type(2).password(new BCryptPasswordEncoder().encode("wx123456")).updateTime(LocalDateTime.now()).createTime(LocalDateTime.now()).delFlag(Constants.NOT_DEL_FALG).remarks("微信扫描注册用户").build();
        sysUserService.save(user);
        // 默认用户角色为普通用户
        sysUserRoleService.save(SysUserRole.builder().roleId(2).userId(user.getId()).build());
    }
    // 生成token
    if (Objects.equals(200, authorizedVo.getStatus())) {
        authorizedVo.setLoginTime(LocalDateTime.now());
        authorizedVo.setUsername(user.getUsername());
        authorizedVo.setNickname(user.getNickname());
        authorizedVo.setToken(JwtTokenUtils.createToken(SysUser.builder().id(user.getId()).username(user.getUsername()).password(user.getPassword()).type(user.getType()).role("2").build(), true));
    }
    try {
        // 发送通知
        log.info("===发送通知====id:{}=====:{}", state, JSON.toJSONString(authorizedVo));
        WebSocketServer.sendMessage(state, JSON.toJSONString(authorizedVo));
    } catch (IOException e) {
        log.error("=======发送通知异常=========={}", e);
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) SysUser(com.tansci.domain.system.SysUser) AuthorizedVo(com.tansci.domain.system.vo.AuthorizedVo) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)

Example 2 with SysUser

use of com.tansci.domain.system.SysUser in project tansci by typ1805.

the class JWTAuthorizationFilter method getAuthentication.

/**
 * @MonthName: getAuthentication
 * @Description: 从token中获取用户信息并新建一个token
 * @Author: tanyp
 * @Date: 2021/10/22 17:55
 * @Param: [tokenHeader]
 * @return: org.springframework.security.authentication.UsernamePasswordAuthenticationToken
 */
private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) {
    String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
    boolean expiration = JwtTokenUtils.isExpiration(token);
    if (expiration) {
        throw new BusinessException(Enums.AUTH_NO_TOKEN.getValue());
    } else {
        String username = JwtTokenUtils.getUsername(token);
        String role = JwtTokenUtils.getUserRole(token);
        SysUser user = JwtTokenUtils.getUser(token);
        if (username != null) {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, Collections.singleton(new SimpleGrantedAuthority(role)));
            authenticationToken.setDetails(user);
            return authenticationToken;
        }
    }
    return null;
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) BusinessException(com.tansci.common.exception.BusinessException) SysUser(com.tansci.domain.system.SysUser) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Aggregations

SysUser (com.tansci.domain.system.SysUser)2 JSONObject (com.alibaba.fastjson.JSONObject)1 BusinessException (com.tansci.common.exception.BusinessException)1 AuthorizedVo (com.tansci.domain.system.vo.AuthorizedVo)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)1 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)1 BCryptPasswordEncoder (org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)1