<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/Advertisement.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * Advertisement表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@EntityDoc(note = "Advertisement", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("Advertisement")
public class Advertisement {

    @EntityDoc(note = "Id")
    @TableId(value = "Id", type = IdType.AUTO)
    private Integer Id;

    @EntityDoc(note = "ImgUrl")
    @TableField("ImgUrl")
    private String ImgUrl;

    @EntityDoc(note = "Title")
    @TableField("Title")
    private String Title;

    @EntityDoc(note = "Url")
    @TableField("Url")
    private String Url;

    @EntityDoc(note = "Remark")
    @TableField("Remark")
    private String Remark;

    @EntityDoc(note = "Createdate")
    @TableField("Createdate")
    private Date Createdate;

}



<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/PasswordLib.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * PasswordLib表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@EntityDoc(note = "PasswordLib", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("PasswordLib")
public class PasswordLib{

    @EntityDoc(note = "PLID")
    @TableId(value = "PLID", type = IdType.AUTO)
    private Integer PLID ;

    @EntityDoc(note = "IsDeleted")
    @TableField("IsDeleted")
    private Boolean IsDeleted ;

    @EntityDoc(note = "plURL")
    @TableField("plURL")
    private String plURL ;

    @EntityDoc(note = "plPWD")
    @TableField("plPWD")
    private String plPWD ;

    @EntityDoc(note = "plAccountName")
    @TableField("plAccountName")
    private String plAccountName ;

    @EntityDoc(note = "plStatus")
    @TableField("plStatus")
    private Integer plStatus ;

    @EntityDoc(note = "plErrorCount")
    @TableField("plErrorCount")
    private Integer plErrorCount ;

    @EntityDoc(note = "plHintPwd")
    @TableField("plHintPwd")
    private String plHintPwd ;

    @EntityDoc(note = "plHintquestion")
    @TableField("plHintquestion")
    private String plHintquestion ;

    @EntityDoc(note = "plCreateTime")
    @TableField("plCreateTime")
    private Date plCreateTime ;

    @EntityDoc(note = "plUpdateTime")
    @TableField("plUpdateTime")
    private Date plUpdateTime ;

    @EntityDoc(note = "plLastErrTime")
    @TableField("plLastErrTime")
    private Date plLastErrTime ;

    @EntityDoc(note = "test")
    @TableField("test")
    private String test ;

}



<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/domain/dto/User.java<|end_filename|>
package club.neters.domain.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User implements UserDetails {

    /**
     * 用户名称
     */
    private String userName;

    /**
     * 用户角色
     */
    private String userRole;
    private Set<? extends GrantedAuthority> authorities;
    /**
     * 用户密码
     */
    private String userPassword;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    public void setAuthorities(Set<? extends GrantedAuthority> authorities) {
        this.authorities = authorities;
    }

    @Override
    public String getPassword() {
        return <PASSWORD>;
    }

    @Override
    public String getUsername() {
        return this.userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/infra/mapper/primary/SysUserInfoMapper.java<|end_filename|>
package club.neters.shrio.demo.infra.mapper.primary;

import club.neters.shrio.demo.domain.entity.SysUserInfo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author laozhang
 * @since 2021-06-25
 */
@Repository
public interface SysUserInfoMapper extends BaseMapper<SysUserInfo> {

    @Select("select * from SysUserInfo where uID = #{uID}")
    @Results(id="UserMap",value={
            @Result(property = "roles",column = "uID",
                    many = @Many(select = "club.neters.shrio.demo.infra.mapper.primary.RoleMapper.findAllByUId",
                            fetchType = FetchType.LAZY))
    })
    List<SysUserInfo> allSysUserInfo(Integer uID);
}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/core/exception/ServiceException.java<|end_filename|>
package club.neters.shrio.demo.core.exception;

/**
 * custom exception
 *
 * @author wuare
 * @date 2021/6/16
 */
public class ServiceException extends RuntimeException {

    public ServiceException(String message) {
        super(message);
    }

    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }

    public ServiceException(Throwable cause) {
        super(cause);
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/TopicServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.app.service.ITopicService;
import club.neters.blog.domain.entity.Topic;
import club.neters.blog.infra.mapper.primary.TopicMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class TopicServiceImpl extends ServiceImpl<TopicMapper, Topic> implements ITopicService {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/SysUserInfoServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.app.service.ISysUserInfoService;
import club.neters.blog.infra.mapper.primary.SysUserInfoMapper;
import club.neters.blog.domain.entity.SysUserInfo;
import club.neters.blog.domain.request.user.UserInfoRequest;
import club.neters.blog.domain.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUserInfo> implements ISysUserInfoService {

    @Override
    public List<UserInfoVo> findList(UserInfoRequest query) {
        LambdaQueryWrapper<SysUserInfo> wrapper = createWrapper(query);

        // 数据处理
        List<SysUserInfo> list = list(wrapper);

        return list.stream().map(v -> {
            UserInfoVo item = new UserInfoVo();
            BeanUtils.copyProperties(v, item);
            return item;
        }).collect(Collectors.toList());
    }

    @Override
    public SysUserInfo findOne(String name, String pass) {
        LambdaQueryWrapper<SysUserInfo> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysUserInfo::getTdIsDelete, 0)
                .eq(SysUserInfo::getULoginName, name)
                .eq(SysUserInfo::getULoginPWD, pass.toUpperCase());
        return getOne(wrapper);
    }

    /**
     * 整理查询条件
     *
     * @param query 入参
     */
    private LambdaQueryWrapper<SysUserInfo> createWrapper(UserInfoRequest query) {

        LambdaQueryWrapper<SysUserInfo> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysUserInfo::getTdIsDelete, 0);

        // 自定义条件
        if (query != null) {

            if (!ObjectUtils.isEmpty(query.getUID())) {
                wrapper.eq(SysUserInfo::getUID, query.getUID());
            }

            if (!ObjectUtils.isEmpty(query.getName())) {
                wrapper.like(SysUserInfo::getName, query.getName());
            }

            if (StringUtils.isNotBlank(query.getULoginName())) {
                wrapper.eq(SysUserInfo::getULoginName, query.getULoginName());
            }

            if (StringUtils.isNotBlank(query.getURealName())) {
                wrapper.eq(SysUserInfo::getURealName, query.getURealName());
            }

        }

        return wrapper;
    }
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/app/service/impl/RoleServiceImpl.java<|end_filename|>
package club.neters.app.service.impl;

import club.neters.app.service.IRoleService;
import club.neters.domain.entity.Role;
import club.neters.infra.mapper.primary.RoleMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    private final RoleMapper roleMapper;

    @Autowired
    public RoleServiceImpl(RoleMapper roleMapper){
        this.roleMapper = roleMapper;
    }

    @Override
    public List<Role> findAllByUId(Integer uID) {
        return roleMapper.findAllByUId(uID);
    }
}


<|start_filename|>ancba-authorizer-oauth2/Dockerfile<|end_filename|>
FROM apache/skywalking-base:8.3.0-es6
MAINTAINER laozhang <<EMAIL>>
VOLUME /tmp
COPY ./src/main/resources /opt
ARG JAR_FILE
ADD ${JAR_FILE} /app/app-oauth.jar
EXPOSE 8181
#指定server
#ENTRYPOINT ["java","-jar","/app/app.jar","0.0.0.0"]
CMD ["java", "-javaagent:/skywalking/agent/skywalking-agent.jar", "-jar", "-Xmx128M", "/app/app-oauth.jar","--spring.config.location=../opt/application.yml"]


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/TopicDetail.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * TopicDetail表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@EntityDoc(note = "TopicDetail", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("TopicDetail")


public class TopicDetail {

    @EntityDoc(note = "Id")
    @TableId(value = "Id", type = IdType.AUTO)
    private Integer Id;

    @EntityDoc(note = "tdLogo")
    @TableField("tdLogo")
    private String tdLogo;

    @EntityDoc(note = "tdName")
    @TableField("tdName")
    private String tdName;

    @EntityDoc(note = "tdContent")
    @TableField("tdContent")
    private String tdContent;

    @EntityDoc(note = "tdDetail")
    @TableField("tdDetail")
    private String tdDetail;

    @EntityDoc(note = "tdSectendDetail")
    @TableField("tdSectendDetail")
    private String tdSectendDetail;

    @EntityDoc(note = "tdIsDelete")
    @TableField("tdIsDelete")
    private Boolean tdIsDelete;

    @EntityDoc(note = "tdRead")
    @TableField("tdRead")
    private Integer tdRead;

    @EntityDoc(note = "tdCommend")
    @TableField("tdCommend")
    private Integer tdCommend;

    @EntityDoc(note = "tdGood")
    @TableField("tdGood")
    private Integer tdGood;

    @EntityDoc(note = "tdCreatetime")
    @TableField("tdCreatetime")
    private Date tdCreatetime;

    @EntityDoc(note = "tdUpdatetime")
    @TableField("tdUpdatetime")
    private Date tdUpdatetime;

    @EntityDoc(note = "tdTop")
    @TableField("tdTop")
    private Integer tdTop;

    @EntityDoc(note = "tdAuthor")
    @TableField("tdAuthor")
    private String tdAuthor;

    @EntityDoc(note = "TopicId")
    @TableField("TopicId")
    private Integer TopicId;

}



<|start_filename|>ancba-user/src/main/java/club/neters/user/core/util/HandlerMethodUtil.java<|end_filename|>
package club.neters.user.core.util;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wuare
 * @date 2021/7/2
 */
public class HandlerMethodUtil {

    public static HandlerMethod getHandlerMethod(HttpServletRequest request) {
        DispatcherServlet dispatcherServlet = ApplicationContextUtil.getBean(DispatcherServlet.class);
        try {
            HandlerExecutionChain handlerExecutionChain = findHandler(dispatcherServlet, request);
            if (handlerExecutionChain == null) {
                return null;
            }
            Object handler = handlerExecutionChain.getHandler();
            if (!(handler instanceof HandlerMethod)) {
                return null;
            }
            return (HandlerMethod) handler;
        } catch (Exception ignored) {
            return null;
        }
    }

    private static HandlerExecutionChain findHandler(DispatcherServlet dispatcherServlet, HttpServletRequest request) throws Exception {
        if (dispatcherServlet.getHandlerMappings() != null) {
            for (HandlerMapping mapping : dispatcherServlet.getHandlerMappings()) {
                HandlerExecutionChain handler = mapping.getHandler(request);
                if (handler != null) {
                    return handler;
                }
            }
        }
        return null;
    }
}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/core/util/JsonUtil.java<|end_filename|>
package club.neters.shrio.demo.core.util;

import club.neters.shrio.demo.core.exception.ServiceException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

/**
 * Json Util
 *
 * @author wuare
 * @date 2021/6/16
 */
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private JsonUtil() {
    }

    /**
     * json to bean
     */
    public static <T> T toBean(String content, Class<T> valueType) {
        try {
            return objectMapper.readValue(content, valueType);
        } catch (JsonProcessingException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * json to map
     */
    public static <K, V> Map<K, V> toMap(String content) {
        try {
            return objectMapper.readValue(content, new TypeReference<Map<K, V>>() {
            });
        } catch (JsonProcessingException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * json to list
     */
    public static <E> List<E> toList(String content) {
        try {
            return objectMapper.readValue(content, new TypeReference<List<E>>() {
            });
        } catch (JsonProcessingException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * object to json
     */
    public static <T> String toJson(T value) {
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new ServiceException(e);
        }
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/infra/mapper/primary/TestMuchTableResultMapper.java<|end_filename|>
package club.neters.blog.infra.mapper.primary;

import club.neters.blog.domain.entity.TestMuchTableResult;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
public interface TestMuchTableResultMapper extends BaseMapper<TestMuchTableResult> {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/Module.java<|end_filename|>
package club.neters.blog.domain.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * <p>
 * 
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("Module")
public class Module implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "Id", type = IdType.AUTO)
    private Integer Id;

    @TableField("IsDeleted")
    private Boolean IsDeleted;

    @TableField("ParentId")
    private Integer ParentId;

    @TableField("Name")
    private String Name;

    @TableField("LinkUrl")
    private String LinkUrl;

    @TableField("Area")
    private String Area;

    @TableField("Controller")
    private String Controller;

    @TableField("Action")
    private String Action;

    @TableField("Icon")
    private String Icon;

    @TableField("Code")
    private String Code;

    @TableField("OrderSort")
    private Integer OrderSort;

    @TableField("Description")
    private String Description;

    @TableField("IsMenu")
    private Boolean IsMenu;

    @TableField("Enabled")
    private Boolean Enabled;

    @TableField("CreateId")
    private Integer CreateId;

    @TableField("CreateBy")
    private String CreateBy;

    @TableField("CreateTime")
    private LocalDateTime CreateTime;

    @TableField("ModifyId")
    private Integer ModifyId;

    @TableField("ModifyBy")
    private String ModifyBy;

    @TableField("ModifyTime")
    private LocalDateTime ModifyTime;


}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/AncbaBlogApplication.java<|end_filename|>
package club.neters.blog;

import club.neters.common.annotaion.EnableAncbaSwagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableAncbaSwagger(basePackage = "club.neters.blog", title = "接口文档", description = "博客模块接口文档")
@SpringBootApplication
@EnableDiscoveryClient
public class AncbaBlogApplication {

    public static void main(String[] args) {
        SpringApplication.run(AncbaBlogApplication.class, args);
        System.out.println("=================blog微服务启动成功=============");
    }

}


<|start_filename|>ancba-user/src/main/java/club/neters/user/core/config/security/CustomAccessDecisionVoter.java<|end_filename|>
package club.neters.user.core.config.security;

import club.neters.user.core.annotation.AnonAllowed;
import club.neters.user.core.constant.CommonConstant;
import club.neters.user.core.util.HandlerMethodUtil;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @author wuare
 * @date 2021/7/1
 */
public class CustomAccessDecisionVoter implements AccessDecisionVoter<FilterInvocation> {

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, FilterInvocation invocation, Collection<ConfigAttribute> attributes) {
        HttpServletRequest request = invocation.getRequest();
        // OPTIONS全放开
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            return ACCESS_GRANTED;
        }
        // 匿名注解允许无权限访问
        HandlerMethod handlerMethod = HandlerMethodUtil.getHandlerMethod(request);
        if (handlerMethod != null) {
            AnonAllowed annotation = handlerMethod.getMethodAnnotation(AnonAllowed.class);
            if (annotation != null) {
                return ACCESS_GRANTED;
            }
        }

        // TODO 扩展
        String[] whiteList = CommonConstant.SECURITY_WHITELIST;
        String[] permissionRequests = {"/test"};

        // 白名单全放开
        for (String url : whiteList) {
            RequestMatcher pathMatcher = new AntPathRequestMatcher(url);
            if (pathMatcher.matches(request)) {
                return ACCESS_GRANTED;
            }
        }

        // 开始处理授权验证逻辑
        // TODO 此处可从数据库扩展处理，也可以使用任意其他的声明
        String userNameVal = "";
        try {
            Jwt jwt = (Jwt) authentication.getPrincipal();
            userNameVal = String.valueOf(jwt.getClaims().get("username"));
        } catch (Exception ignored) {
        }
        for (String url : permissionRequests) {
            RequestMatcher pathMatcher = new AntPathRequestMatcher(url);
            if (pathMatcher.matches(request) && userNameVal.equals("test")) {
                return ACCESS_GRANTED;
            }
        }
        return ACCESS_DENIED;
    }
}


<|start_filename|>ancba-user/src/main/java/club/neters/user/core/config/security/AdminAccessDeineHandler.java<|end_filename|>
package club.neters.user.core.config.security;

import club.neters.user.core.util.JsonUtil;
import club.neters.user.domain.vo.ApiResultVo;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AdminAccessDeineHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/javascript;charset=utf-8");
        response.getWriter().print(JsonUtil.toJson(ApiResultVo.forbidden("授权失败，请联系管理员！")));
    }

}

<|start_filename|>ancba-common/src/main/java/club/neters/common/config/swagger/SwaggerRegistrar.java<|end_filename|>
package club.neters.common.config.swagger;

import club.neters.common.annotaion.EnableAncbaSwagger;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

/**
 * @author wuare
 * @date 2021/6/29
 */
public class SwaggerRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        Map<String, Object> attrMap = importingClassMetadata.getAnnotationAttributes(EnableAncbaSwagger.class.getName());
        if (attrMap == null) {
            return;
        }
        String basePackage = (String) attrMap.get("basePackage");
        String title = (String) attrMap.get("title");
        String description = (String) attrMap.get("description");
        String version = (String) attrMap.get("version");
        String email = (String) attrMap.get("email");
        boolean oauth = (boolean) attrMap.get("oauth");

        BeanDefinitionBuilder bd1 = BeanDefinitionBuilder.rootBeanDefinition(SwaggerConfigProperties.class);
        bd1.addPropertyValue("basePackage", basePackage);
        bd1.addPropertyValue("title", title);
        bd1.addPropertyValue("description", description);
        bd1.addPropertyValue("version", version);
        bd1.addPropertyValue("email", email);
        bd1.addPropertyValue("oauth", oauth);
        registry.registerBeanDefinition("swaggerConfigProperties", bd1.getBeanDefinition());

        BeanDefinitionBuilder bd0 = BeanDefinitionBuilder.rootBeanDefinition(SwaggerConfig.class);
        bd0.addPropertyReference("swaggerConfigProperties", "swaggerConfigProperties");
        registry.registerBeanDefinition(SwaggerConfig.class.getName(), bd0.getBeanDefinition());
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/OperateLogServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.domain.entity.OperateLog;
import club.neters.blog.infra.mapper.primary.OperateLogMapper;
import club.neters.blog.app.service.IOperateLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class OperateLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements IOperateLogService {

}


<|start_filename|>ancba-user/src/main/java/club/neters/user/api/controller/UserController.java<|end_filename|>
package club.neters.user.api.controller;

import club.neters.user.app.service.UserApiService;
import club.neters.user.core.annotation.AnonAllowed;
import club.neters.user.domain.entity.BlogArticle;
import club.neters.user.domain.request.UserInfoRequestFromBlog;
import club.neters.user.domain.vo.ApiResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author wuare
 * @date 2021/7/1
 */
@RestController
public class UserController {
    @Autowired
    private UserApiService userApiService;

    @GetMapping("/test")
    public String test() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        System.out.println(authentication.getAuthorities());
        return "test";
    }

    @GetMapping("/test1")
    public String test1() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        System.out.println(authentication.getAuthorities());
        return "test1";
    }

    @GetMapping("/user/testNo")
    @AnonAllowed
    public ApiResultVo<List<BlogArticle>> testNo() {
        return userApiService.loadUserListPage(new UserInfoRequestFromBlog());
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/infra/mapper/primary/RoleModulePermissionMapper.java<|end_filename|>
package club.neters.blog.infra.mapper.primary;

import club.neters.blog.domain.entity.RoleModulePermission;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
public interface RoleModulePermissionMapper extends BaseMapper<RoleModulePermission> {

}


<|start_filename|>ancba-user/src/main/java/club/neters/user/core/constant/CommonConstant.java<|end_filename|>
package club.neters.user.core.constant;

public class CommonConstant {
    public static final String JWT_HMAC256_SECRET = "<KEY>";
    public static final String JWT_ISSUER = "Blog.Core";
    public static final String[] SECURITY_WHITELIST = {"/", "/actuator/health", "/actuator", "/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/v2/**", "/error"};
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/OperateLog.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * OperateLog表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@EntityDoc(note = "OperateLog", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("OperateLog")


public class OperateLog {

    @EntityDoc(note = "Id")
    @TableId(value = "Id", type = IdType.AUTO)
    private Integer Id;

    @EntityDoc(note = "IsDeleted")
    @TableField("IsDeleted")
    private Boolean IsDeleted;

    @EntityDoc(note = "Area")
    @TableField("Area")
    private String Area;

    @EntityDoc(note = "Controller")
    @TableField("Controller")
    private String Controller;

    @EntityDoc(note = "Action")
    @TableField("Action")
    private String Action;

    @EntityDoc(note = "IPAddress")
    @TableField("IPAddress")
    private String IPAddress;

    @EntityDoc(note = "Description")
    @TableField("Description")
    private String Description;

    @EntityDoc(note = "LogTime")
    @TableField("LogTime")
    private Date LogTime;

    @EntityDoc(note = "LoginName")
    @TableField("LoginName")
    private String LoginName;

    @EntityDoc(note = "UserId")
    @TableField("UserId")
    private Integer UserId;

}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/PasswordLibServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.domain.entity.PasswordLib;
import club.neters.blog.infra.mapper.primary.PasswordLibMapper;
import club.neters.blog.app.service.IPasswordLibService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * WMBLOG_MSSQL_2 服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class PasswordLibServiceImpl extends ServiceImpl<PasswordLibMapper, PasswordLib> implements IPasswordLibService {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/ModulePermission.java<|end_filename|>

package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * ModulePermission表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode(callSuper = false)
@EntityDoc(note = "ModulePermission", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("ModulePermission")


public class ModulePermission extends BaseEntity {

    @EntityDoc(note = "ModuleId")
    @TableField("ModuleId")
    private Integer ModuleId;

    @EntityDoc(note = "PermissionId")
    @TableField("PermissionId")
    private Integer PermissionId;

}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/IRoleService.java<|end_filename|>
package club.neters.blog.app.service;

import club.neters.blog.domain.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
public interface IRoleService extends IService<Role> {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/core/config/Security/OAuth2ResourceServerConfig.java<|end_filename|>
//package club.neters.blog.core.config.Security;
//
//import club.neters.common.constant.CommonConstant;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.http.SessionCreationPolicy;
//import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
//import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
//import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
//import org.springframework.security.oauth2.provider.token.TokenStore;
//import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
//import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
//
//@Configuration
//public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
//
//    @Override
//    public void configure(final HttpSecurity http) throws Exception {
//        http.cors()
//                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//
//                .and()
//                .authorizeRequests()
//                .antMatchers("/").permitAll() // 任意访问
//                .antMatchers("/csrf").permitAll() // 任意访问
//                .antMatchers("/actuator").permitAll() // 任意访问
//                .antMatchers("/actuator/health").permitAll() // 任意访问
//                .antMatchers("/swagger-ui.html").permitAll() // 任意访问
//                .antMatchers("/swagger-resources/**").permitAll()
//                .antMatchers("/webjars/**").permitAll()
//                .antMatchers("/v2/**").permitAll()
//                .antMatchers("/api/**").authenticated()
//                .anyRequest().authenticated()
//                .and().csrf().disable();
//    }
//
//    @Override
//    public void configure(ResourceServerSecurityConfigurer resources) {
//        resources.resourceId("clientapp-res") // 配置资源id，这里的资源id和授权服务器中的资源id一致
//                .tokenStore(tokenStore()) //指定保存token的方式
//                .tokenServices(tokenServices())
//                .stateless(true); // 设置这些资源仅基于令牌认证
//    }
//
//    @Bean
//    public TokenStore tokenStore() {
//        return new JwtTokenStore(accessTokenConverter());
//    }
//
//    @Bean
//    public JwtAccessTokenConverter accessTokenConverter() {
//        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
//        converter.setSigningKey(CommonConstant.JWT_HMAC256_SECRET);
//        return converter;
//    }
//
//    @Bean
//    public DefaultTokenServices tokenServices() {
//        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
//        defaultTokenServices.setTokenStore(tokenStore());
//        return defaultTokenServices;
//    }
//}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/AdvertisementServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.domain.entity.Advertisement;
import club.neters.blog.infra.mapper.primary.AdvertisementMapper;
import club.neters.blog.app.service.IAdvertisementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class AdvertisementServiceImpl extends ServiceImpl<AdvertisementMapper, Advertisement> implements IAdvertisementService {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/request/user/UserInfoRequest.java<|end_filename|>
package club.neters.blog.domain.request.user;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * user information query object
 *
 * @author wuare
 * @date 2021/6/16
 */
@Data
public class UserInfoRequest {

    @ApiModelProperty(value = "id")
    private Integer uID;

    @ApiModelProperty(value = "登录名")
    private String uLoginName;

    @ApiModelProperty(value = "真实名")
    private String uRealName;

    @ApiModelProperty(value = "名字")
    private String name;
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/api/controller/UserController.java<|end_filename|>
package club.neters.api.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @RequestMapping("/api/me")
    public Object user() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication);
        return 100;
    }
}


<|start_filename|>ancba-user/src/main/java/club/neters/user/core/annotation/AnonAllowed.java<|end_filename|>
package club.neters.user.core.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author wuare
 * @date 2021/7/2
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnonAllowed {
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/infra/mapper/primary/PasswordLibMapper.java<|end_filename|>
package club.neters.blog.infra.mapper.primary;

import club.neters.blog.domain.entity.PasswordLib;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 * WMBLOG_MSSQL_2 Mapper 接口
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
public interface PasswordLibMapper extends BaseMapper<PasswordLib> {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/IModulesService.java<|end_filename|>
package club.neters.blog.app.service;

import club.neters.blog.domain.entity.Modules;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
public interface IModulesService extends IService<Modules> {

}


<|start_filename|>ancba-common/src/main/java/club/neters/common/config/swagger/SwaggerConfig.java<|end_filename|>
package club.neters.common.config.swagger;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author wuare
 * @date 2021/6/29
 */
@ConditionalOnBean(name = "swaggerConfigProperties")
@Configuration
@EnableSwagger2
@Import({BeanValidatorPluginsConfiguration.class, Swagger2DocumentationConfiguration.class})
@EnableKnife4j
@ConfigurationProperties(prefix = "swagger")
public class SwaggerConfig {

    private SwaggerConfigProperties swaggerConfigProperties;

    @Value("${security.server.url}")
    private String AUTH_SERVER;

    @Bean
    public Docket createRestApi() {

        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerConfigProperties.getBasePackage()))
                .paths(PathSelectors.any())
                .build();

        // 开启认证安全
        if (swaggerConfigProperties.getOauth()) {
            docket.securitySchemes(Collections.singletonList(securityScheme()))
                    .securityContexts(Collections.singletonList(securityContext()));
        } else {
            docket.securityContexts(Collections.singletonList(securityContexts()))
                    .securitySchemes(Collections.singletonList(securitySchemes()));
        }

        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerConfigProperties.getTitle())
                .description(swaggerConfigProperties.getDescription())
                .contact(new Contact("", "", swaggerConfigProperties.getEmail()))
                .version(swaggerConfigProperties.getVersion())
                .build();
    }


    private SecurityScheme securitySchemes() {
        return new ApiKey("Authorization", "Authorization", "header");
    }

    private SecurityContext securityContexts() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any())
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("xxx", "描述信息");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference("Authorization", authorizationScopes));
    }

    /**
     * 这个类决定了你使用哪种认证方式，我这里使用密码模式
     */
    private SecurityScheme securityScheme() {
        GrantType grantType = new ResourceOwnerPasswordCredentialsGrant(AUTH_SERVER);

        return new OAuthBuilder()
                .name("OAuth2")
                .grantTypes(Collections.singletonList(grantType))
                .scopes(Arrays.asList(scopes()))
                .build();
    }

    /**
     * 这里设置 swagger2 认证的安全上下文
     */
    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(Collections.singletonList(new SecurityReference("OAuth2", scopes())))
                .forPaths(PathSelectors.any())
                .build();
    }

    /**
     * 这里是写允许认证的scope
     */
    private AuthorizationScope[] scopes() {
        return new AuthorizationScope[]{
                new AuthorizationScope("all", "All scope is trusted!")
        };
    }

    public void setSwaggerConfigProperties(SwaggerConfigProperties swaggerConfigProperties) {
        this.swaggerConfigProperties = swaggerConfigProperties;
    }
}




<|start_filename|>ancba-user/src/main/java/club/neters/user/core/exception/ServiceException.java<|end_filename|>
package club.neters.user.core.exception;

/**
 * custom exception
 *
 * @author maven plugin
 * @date 2021/6/16
 */
public class ServiceException extends RuntimeException {

    public ServiceException(String message) {
        super(message);
    }

    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }

    public ServiceException(Throwable cause) {
        super(cause);
    }
}


<|start_filename|>ancba-user/src/main/java/club/neters/user/domain/vo/UserInfoVoFromBlog.java<|end_filename|>
package club.neters.user.domain.vo;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * user information view object
 *
 * @author wuare
 * @date 2021/6/16
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UserInfoVoFromBlog {
    private Integer uID;

    private String uLoginName;


    private String uRealName;

    private Integer uStatus;

    private String uRemark;

    protected Date uCreateTime;

    protected Date uUpdateTime;

    private String name;

    private Integer sex;

    private Integer age;

    protected Date birth;

    private String addr;


    /**
     * 手机号
     */
    private String phone;


    /**
     * 验证码 登录用
     */
    private String verifyCode;


    /**
     * 新密码
     */
    private String newPassword;
}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/app/service/impl/SysUserInfoServiceImpl.java<|end_filename|>
package club.neters.shrio.demo.app.service.impl;

import club.neters.shrio.demo.domain.entity.SysUserInfo;
import club.neters.shrio.demo.infra.mapper.primary.SysUserInfoMapper;
import club.neters.shrio.demo.app.service.ISysUserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-25
 */
@Service
public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUserInfo> implements ISysUserInfoService {

    private final SysUserInfoMapper sysUserInfoMapper;

    @Autowired
    public SysUserInfoServiceImpl(SysUserInfoMapper sysUserInfoMapper){
        this.sysUserInfoMapper = sysUserInfoMapper;
    }

    @Override
    public SysUserInfo findOne(String name, String pass) {
        LambdaQueryWrapper<SysUserInfo> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysUserInfo::getTdIsDelete, 0)
                .eq(SysUserInfo::getULoginName, name)
                .eq(SysUserInfo::getULoginPWD, pass.toUpperCase());
        return getOne(wrapper);
    }

    @Override
    public List<SysUserInfo> allSysUserInfo(Integer uID) {
        return sysUserInfoMapper.allSysUserInfo(uID);
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/TasksQzServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.app.service.ITasksQzService;
import club.neters.blog.domain.entity.TasksQz;
import club.neters.blog.infra.mapper.primary.TasksQzMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class TasksQzServiceImpl extends ServiceImpl<TasksQzMapper, TasksQz> implements ITasksQzService {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/Topic.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * Topic表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@EntityDoc(note = "Topic", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("Topic")
public class Topic {

    @EntityDoc(note = "Id")
    @TableId(value = "Id", type = IdType.AUTO)
    private Integer Id;

    @EntityDoc(note = "tLogo")
    @TableField("tLogo")
    private String tLogo;

    @EntityDoc(note = "tName")
    @TableField("tName")
    private String tName;

    @EntityDoc(note = "tDetail")
    @TableField("tDetail")
    private String tDetail;

    @EntityDoc(note = "tAuthor")
    @TableField("tAuthor")
    private String tAuthor;

    @EntityDoc(note = "tSectendDetail")
    @TableField("tSectendDetail")
    private String tSectendDetail;

    @EntityDoc(note = "tIsDelete")
    @TableField("tIsDelete")
    private Boolean tIsDelete;

    @EntityDoc(note = "tRead")
    @TableField("tRead")
    private Integer tRead;

    @EntityDoc(note = "tCommend")
    @TableField("tCommend")
    private Integer tCommend;

    @EntityDoc(note = "tGood")
    @TableField("tGood")
    private Integer tGood;

    @EntityDoc(note = "tCreatetime")
    @TableField("tCreatetime")
    private Date tCreatetime;

    @EntityDoc(note = "tUpdatetime")
    @TableField("tUpdatetime")
    private Date tUpdatetime;

}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/api/controller/CSRFController.java<|end_filename|>
package club.neters.blog.api.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;

@RestController
@ApiIgnore
public class CSRFController {
    @GetMapping(value = "/csrf")
    public ResponseEntity<CsrfToken> getToken(HttpServletRequest request) {
        return ResponseEntity.ok().body(new HttpSessionCsrfTokenRepository().generateToken(request));
    }
}

<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/AncbaShrioDemoApplication.java<|end_filename|>
package club.neters.shrio.demo;

import club.neters.common.annotaion.EnableAncbaSwagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author wuare
 * @date 2021/6/25
 */
@SpringBootApplication
@EnableAncbaSwagger(basePackage = "club.neters.shrio.demo", title = "接口文档", description = "Shiro案例模块接口文档", oauth = false)
public class AncbaShrioDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(AncbaShrioDemoApplication.class, args);
    }
}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/app/service/impl/RoleServiceImpl.java<|end_filename|>
package club.neters.shrio.demo.app.service.impl;

import club.neters.shrio.demo.infra.mapper.primary.RoleMapper;
import club.neters.shrio.demo.app.service.IRoleService;
import club.neters.shrio.demo.domain.entity.Role;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    private final RoleMapper roleMapper;

    @Autowired
    public RoleServiceImpl(RoleMapper roleMapper){
        this.roleMapper = roleMapper;
    }

    @Override
    public List<Role> findAllByUId(Integer uID) {
        return roleMapper.findAllByUId(uID);
    }
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/AncbaAuthorizerApplication.java<|end_filename|>
package club.neters;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author maven plugin
 * @date 2021/6/25
 */
@SpringBootApplication
@EnableDiscoveryClient
public class AncbaAuthorizerApplication {
    public static void main(String[] args) {
        SpringApplication.run(AncbaAuthorizerApplication.class, args);
        System.out.println("=================鉴权认证中心启动成功=============");
    }
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/app/service/IRoleService.java<|end_filename|>
package club.neters.app.service;

import club.neters.domain.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-30
 */
public interface IRoleService extends IService<Role> {
    List<Role> findAllByUId(Integer uID);
}


<|start_filename|>ancba-maven-archetype/src/main/resources/archetype-resources/src/main/java/core/exception/ServiceException.java<|end_filename|>
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.core.exception;

/**
 * custom exception
 *
 * @author maven plugin
 * @date 2021/6/16
 */
public class ServiceException extends RuntimeException {

    public ServiceException(String message) {
        super(message);
    }

    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }

    public ServiceException(Throwable cause) {
        super(cause);
    }
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/core/config/WebSecurityConfig.java<|end_filename|>
package club.neters.core.config;

import club.neters.app.service.UserDetailService;
import club.neters.core.constant.CommonConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.cors.CorsUtils;

import javax.annotation.Resource;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @author EalenXie create on 2020/11/3 13:00
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailService oauthAccountUserDetailsService;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 这些接口 对于认证中心来说无需授权
     */
    protected static final String[] PERMIT_ALL_URL = {"/oauth/**", "/actuator/**", "/error", "/open/api"};

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
                .cors()
                .and()
                // 取消禁用匿名，为健康检查做准备
//                .anonymous().disable()
                .csrf().disable()
                .authorizeRequests()
                //处理跨域请求中的Preflight请求
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers(PERMIT_ALL_URL).permitAll()
                .anyRequest()
                .authenticated()

                .and()
                .formLogin()
                .successHandler(authenticationSuccessHandler())
                .failureHandler(authenticationFailureHandler())
                .and().logout()
                .logoutSuccessHandler(logoutSuccessHandler())
                .and().httpBasic();
    }

    /**
     * 登录成功处理器
     */
    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        return (httpServletRequest, httpServletResponse, authentication) -> {
            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
            httpServletResponse.getWriter().write("login success~~~~~");
        };
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withSecretKey(new SecretKeySpec(
                CommonConstant.JWT_HMAC256_SECRET.getBytes(StandardCharsets.UTF_8), "HMAC256"))
                .build();
    }

    /**
     * 登出成功处理器
     */
    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        return (httpServletRequest, httpServletResponse, authentication) -> {
            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
            httpServletResponse.getWriter().write("logout success~~~~~~");
        };
    }

    /**
     * 常规登录失败处理器
     */
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return (httpServletRequest, httpServletResponse, e) -> {
            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            httpServletResponse.getWriter().write(HttpStatus.UNAUTHORIZED.value());
        };
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(oauthAccountUserDetailsService).passwordEncoder(passwordEncoder);
        auth.eraseCredentials(true);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/BlogArticle.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * BlogArticle表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@EntityDoc(note = "BlogArticle", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("BlogArticle")
public class BlogArticle {

    @EntityDoc(note = "bID")
    @TableId(value = "bID", type = IdType.AUTO)
    private Integer bID;

    @EntityDoc(note = "bsubmitter")
    @TableField("bsubmitter")
    private String bsubmitter;

    @EntityDoc(note = "btitle")
    @TableField("btitle")
    private String btitle;

    @EntityDoc(note = "bcategory")
    @TableField("bcategory")
    private String bcategory;

    @EntityDoc(note = "bcontent")
    @TableField("bcontent")
    private String bcontent;

    @EntityDoc(note = "btraffic")
    @TableField("btraffic")
    private Integer btraffic;

    @EntityDoc(note = "bcommentNum")
    @TableField("bcommentNum")
    private Integer bcommentNum;

    @EntityDoc(note = "bUpdateTime")
    @TableField("bUpdateTime")
    private Date bUpdateTime;

    @EntityDoc(note = "bCreateTime")
    @TableField("bCreateTime")
    private Date bCreateTime;

    @EntityDoc(note = "bRemark")
    @TableField("bRemark")
    private String bRemark;

    @EntityDoc(note = "IsDeleted")
    @TableField("IsDeleted")
    private Boolean IsDeleted;

}

<|start_filename|>ancba-gateway/src/main/java/club/neters/gateway/config/security/WebSecurityConfig.java<|end_filename|>
package club.neters.gateway.config.security;


import club.neters.common.constant.CommonConstant;
import club.neters.common.domain.vo.ApiResultVo;
import club.neters.common.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import reactor.core.publisher.Mono;

import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author
 */
//@Configuration
@EnableWebFluxSecurity
public class WebSecurityConfig {

    @Autowired
    private AccessManager accessManager;


    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        http.oauth2ResourceServer().jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter());

        http.authorizeExchange()
                .pathMatchers(CommonConstant.GW_SECURITY_WHITELIST).permitAll()
                .anyExchange().access(accessManager)
                .and()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler()) // 处理未授权
                .authenticationEntryPoint(authenticationEntryPoint()) //处理未认证
                .and().csrf().disable();

        return http.build();
    }

    /**
     * 未授权自定义响应
     */
    @Bean
    ServerAccessDeniedHandler accessDeniedHandler() {
        return (exchange, denied) -> Mono.defer(() -> Mono.just(exchange.getResponse()))
                .flatMap(response -> writeErrorInfo(response, JsonUtil.toJson(ApiResultVo.forbidden("网关鉴权失败：403！"))));
    }

    /**
     * token无效或者已过期自定义响应
     */
    @Bean
    ServerAuthenticationEntryPoint authenticationEntryPoint() {
        return (exchange, e) -> {
            Mono mono = Mono.defer(() -> Mono.just(exchange.getResponse()))
                    .flatMap(response -> writeErrorInfo(response, JsonUtil.toJson(ApiResultVo.unauthorized("网关鉴权失败：401！"))));
            return mono;
        };
    }

    public static Mono writeErrorInfo(ServerHttpResponse response, String body) {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().set("Access-Control-Allow-Origin", "*");
        response.getHeaders().set("Cache-Control", "no-cache");
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
        return response.writeWith(Mono.just(buffer))
                .doOnError(error -> DataBufferUtils.release(buffer));
    }

    /**
     * ServerHttpSecurity没有将jwt中authorities的负载部分当做Authentication
     * 需要把jwt的Claim中的authorities加入
     * 方案：重新定义ReactiveAuthenticationManager权限管理器，默认转换器JwtGrantedAuthoritiesConverter
     */
    @Bean
    public Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();

        // 把Jwt中的信息转化到SecurityContext#authentication#authorities中
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");

        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
    }

    @Bean
    public ReactiveJwtDecoder jwtDecoder() {
        return NimbusReactiveJwtDecoder.withSecretKey(new SecretKeySpec(
                CommonConstant.JWT_HMAC256_SECRET.getBytes(StandardCharsets.UTF_8), "HMAC256"))
                .build();
    }


}


<|start_filename|>ancba-gateway/src/main/java/club/neters/gateway/config/limit/LimitFilter.java<|end_filename|>
package club.neters.gateway.config.limit;

import club.neters.common.constant.CommonConstant;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

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

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.setResponseStatus;

@Configuration
@Order(-200)
public class LimitFilter implements WebFilter {

    @Resource
    private RedisRateLimiter redisRateLimiter;

    @Resource
    private KeyResolver keyResolver;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String pattern : CommonConstant.GW_SECURITY_WHITELIST) {
            if (antPathMatcher.match(pattern, exchange.getRequest().getURI().getPath())) {
                return chain.filter(exchange);
            }
        }

        return keyResolver.resolve(exchange).flatMap(key ->
                redisRateLimiter.isAllowed(RouteDefinitionRouteLocator.DEFAULT_FILTERS, key)
                        .flatMap(response -> {
                            for (Map.Entry<String, String> header : response.getHeaders().entrySet()) {
                                exchange.getResponse().getHeaders().add(header.getKey(), header.getValue());
                            }

                            if (response.isAllowed()) {
                                return chain.filter(exchange);
                            }

                            setResponseStatus(exchange, HttpStatus.TOO_MANY_REQUESTS);
                            return exchange.getResponse().setComplete();
                        }));
    }
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/app/service/UserDetailService.java<|end_filename|>
package club.neters.app.service;

import club.neters.domain.dto.User;
import club.neters.domain.entity.Role;
import club.neters.domain.entity.SysUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserDetailService implements UserDetailsService {
    @Resource
    private ISysUserInfoService sysUserInfoService;

    @Resource
    private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = new User();
        try {
            if (StringUtils.isBlank(userName)) {
                throw new UsernameNotFoundException("用户名为空！");
            }

            SysUserInfo userInfo = sysUserInfoService.getOne(new LambdaQueryWrapper<SysUserInfo>()
                    .eq(SysUserInfo::getTdIsDelete, false).eq(SysUserInfo::getULoginName, userName), false);
            if (userInfo == null) {
                throw new UsernameNotFoundException("用户数据不存在");
            }

            // 将用户的用户名+密码赋值服务
            String password = userInfo.getUL<PASSWORD>();
            user.setUserName(userInfo.getULoginName());
            user.setUserPassword(password);

            // 获取角色
            List<Role> roles = roleService.findAllByUId(userInfo.getUID());

            Set authoritiesSet = new HashSet();
            for (Role role : roles) {
                GrantedAuthority authority = new SimpleGrantedAuthority(role.getName());
                authoritiesSet.add(authority);
            }

            user.setAuthorities(authoritiesSet);

            return user;
        } catch (UsernameNotFoundException e) {
            throw new UsernameNotFoundException("用户数据有误！");
        } finally {
        }
    }
}

<|start_filename|>ancba-maven-archetype/src/main/resources/archetype-resources/src/main/java/__artifactIdBig__Application.java<|end_filename|>
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package};

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author maven plugin
 * @date 2021/6/25
 */
@SpringBootApplication
public class ${artifactIdBig}Application {

    public static void main(String[] args) {
        SpringApplication.run(${artifactIdBig}Application.class, args);
    }
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/core/config/CustomAuthenticationProvider.java<|end_filename|>
package club.neters.core.config;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

public class CustomAuthenticationProvider extends DaoAuthenticationProvider {
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        //  HttpServletRequest req = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        Object rawPassword = authentication.getCredentials();
        // 单独对密码器做处理，注意大小写
        String md5Pwd = DigestUtils.md5DigestAsHex(rawPassword.toString().getBytes(StandardCharsets.UTF_8));
        if (!md5Pwd.toUpperCase().equals(userDetails.getPassword())) {
            throw new AuthenticationServiceException("密码错误");
        }

        // String input_code = req.getParameter("code");
        // String verify = (String) req.getSession().getAttribute("verifyCode");
        // if (input_code == null || !input_code.equals(verify)) {
        //     throw new AuthenticationServiceException("验证码错误");
        // }

        super.additionalAuthenticationChecks(userDetails, authentication);
    }
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/domain/entity/BaseEntity.java<|end_filename|>
package club.neters.domain.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

/**
 * 基础实体类
 *
 * @author laozhang
 * @date 2021/06/12
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BaseEntity implements Serializable {

    @TableId(value = "Id", type = IdType.AUTO)
    private Integer Id;

    @TableField("CreateId")
    private Integer CreateId;

    @TableField("CreateBy")
    private String CreateBy;

    @TableField(value = "CreateTime", fill = FieldFill.INSERT)
    protected Date CreateTime;

    @TableField("ModifyId")
    private Integer ModifyId;

    @TableField("ModifyBy")
    private String ModifyBy;

    @TableField(value = "ModifyTime", fill = FieldFill.INSERT)
    protected Date ModifyTime;

    @TableField("tdIsDelete")
    private Boolean IsDeleted;

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/ModuleServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.domain.entity.Module;
import club.neters.blog.infra.mapper.primary.ModuleMapper;
import club.neters.blog.app.service.IModuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class ModuleServiceImpl extends ServiceImpl<ModuleMapper, Module> implements IModuleService {

}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/domain/entity/SysUserInfo.java<|end_filename|>
package club.neters.shrio.demo.domain.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import java.util.List;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * <p>
 * 
 * </p>
 *
 * @author laozhang
 * @since 2021-06-25
 */
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("SysUserInfo")
public class SysUserInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "uID", type = IdType.AUTO)
    private Integer uID;

    @TableField("uLoginName")
    private String uLoginName;

    @TableField("uLoginPWD")
    private String uLoginPWD;

    @TableField("uRealName")
    private String uRealName;

    @TableField("uStatus")
    private Integer uStatus;

    @TableField("uRemark")
    private String uRemark;

    @TableField("uCreateTime")
    private LocalDateTime uCreateTime;

    @TableField("uUpdateTime")
    private LocalDateTime uUpdateTime;

    @TableField("uLastErrTime")
    private LocalDateTime uLastErrTime;

    @TableField("uErrorCount")
    private Integer uErrorCount;

    @TableField("name")
    private String name;

    @TableField("sex")
    private Integer sex;

    @TableField("age")
    private Integer age;

    @TableField("birth")
    private LocalDateTime birth;

    @TableField("addr")
    private String addr;

    @TableField("tdIsDelete")
    private Boolean tdIsDelete;


    @TableField(exist = false)  //不是数据库字段,但必须使用
    private List<Role> roles;

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/SysUserInfo.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * 用户信息表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@EntityDoc(note = "系统用户", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("SysUserInfo")
public class SysUserInfo {

    @EntityDoc(note = "id")
    @TableId(value = "uID", type = IdType.AUTO)
    private Integer uID;

    @EntityDoc(note = "登录名")
    @TableField("uLoginName")
    private String uLoginName;

    @EntityDoc(note = "密码")
    @TableField("uLoginPWD")
    private String uLoginPWD;

    @EntityDoc(note = "真实名")
    @TableField("uRealName")
    private String uRealName;

    @EntityDoc(note = "状态")
    @TableField("uStatus")
    private Integer uStatus;

    @EntityDoc(note = "备注")
    @TableField("uRemark")
    private String uRemark;

    @EntityDoc(note = "创建时间")
    @TableField(value = "uCreateTime",fill = FieldFill.INSERT)
    protected Date uCreateTime;

    @EntityDoc(note = "更新时间")
    @TableField(value = "uUpdateTime",fill = FieldFill.INSERT)
    protected Date uUpdateTime;

    @EntityDoc(note = "报错时间")
    @TableField(value = "uLastErrTime",fill = FieldFill.INSERT)
    protected Date uLastErrTime;

    @EntityDoc(note = "错误次数")
    @TableField("uErrorCount")
    private Integer uErrorCount;

    @EntityDoc(note = "名字")
    @TableField("name")
    private String name;


    @EntityDoc(note = "性别")
    @TableField("sex")
    private Integer sex;

    @EntityDoc(note = "年龄")
    @TableField("age")
    private Integer age;

    @EntityDoc(note = "生日")
    @TableField("birth")
    protected Date birth;

    @EntityDoc(note = "地址")
    @TableField("addr")
    private String addr;

    @EntityDoc(note = "是否删除")
    @TableField("tdIsDelete")
    private Boolean tdIsDelete;

}


<|start_filename|>ancba-gateway/src/main/java/club/neters/gateway/config/loging/RequestLoggingFilter.java<|end_filename|>
package club.neters.gateway.config.loging;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebExchangeDecorator;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Configuration
public class RequestLoggingFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        ServerWebExchangeDecorator decorator =
                new ServerWebExchangeDecorator(serverWebExchange) {
                    @Override
                    public ServerHttpRequest getRequest() {
                        return new RequestLoggingDecorator(serverWebExchange.getRequest());
                    }
                };

        return webFilterChain.filter(decorator);
    }
}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/core/constant/CommonConstant.java<|end_filename|>
package club.neters.blog.core.constant;

public class CommonConstant {
    public static final String JWT_HMAC256_SECRET = "<KEY>";
    public static final String JWT_ISSUER = "Blog.Core";
}


<|start_filename|>ancba-common/src/main/java/club/neters/common/domain/vo/ApiResultVo.java<|end_filename|>
package club.neters.common.domain.vo;


/**
 * common vo
 *
 * @author wuare
 * @date 2021/6/16
 */
public class ApiResultVo<T> {

    /**
     * 错误代码
     */
    private long code;

    /**
     * 错误信息
     */
    private String message;

    /**
     * 返回数据
     */
    private T data;

    public static <T> ApiResultVo<T> ok(T data) {
        return ok(data, "success");
    }

    public static <T> ApiResultVo<T> ok(T data, String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setData(data);
        bean.setCode(200);
        bean.setMessage(msg);
        return bean;
    }


    public static <T> ApiResultVo<T> error(T data) {
        return error(data, "服务器异常");
    }

    public static <T> ApiResultVo<T> error(String msg) {
        return error(null, msg);
    }

    public static <T> ApiResultVo<T> error(T data, String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setData(data);
        bean.setCode(500);
        bean.setMessage(msg);
        return bean;
    }

    public static <T> ApiResultVo<T> badRequest(String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setCode(400);
        bean.setMessage(msg);
        return bean;
    }

    public static <T> ApiResultVo<T> unauthorized(String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setCode(401);
        bean.setMessage(msg);
        return bean;
    }

    public static <T> ApiResultVo<T> forbidden(String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setCode(403);
        bean.setMessage(msg);
        return bean;
    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/infra/shiro/UserRealm.java<|end_filename|>
package club.neters.shrio.demo.infra.shiro;

import club.neters.shrio.demo.app.service.IRoleService;
import club.neters.shrio.demo.app.service.ISysUserInfoService;
import club.neters.shrio.demo.core.util.JwtUtil;
import club.neters.shrio.demo.domain.entity.Role;
import club.neters.shrio.demo.domain.entity.SysUserInfo;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.BearerToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * realm
 *
 * @author wuare
 * @date 2021/6/25
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Resource
    private ISysUserInfoService sysUserInfoService;

    @Resource
    private IRoleService roleService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token != null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //如果用户未登录返回没有权限
        String token = principalCollection.toString();
        if (!(StringUtils.isNotEmpty(token) && JwtUtil.isNotExpired(token))) {
            return simpleAuthorizationInfo;
        }
        //添加角色和权限
        List<String> roleList = JwtUtil.getRoleFromToken(token);
        if (CollectionUtils.isEmpty(roleList)) {
            return simpleAuthorizationInfo;
        }
        for (String role : roleList) {
            simpleAuthorizationInfo.addRole(role);
            // 也可以进一步追加permission权限
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (authenticationToken instanceof UsernamePasswordToken) {
            String userName = (String) authenticationToken.getPrincipal();
            if (StringUtils.isBlank(userName) || (authenticationToken.getCredentials() == null)) {
                throw new UnknownAccountException("用户名或密码错误");
            }
            String password = new String((char[]) authenticationToken.getCredentials());

            SysUserInfo userInfo = sysUserInfoService.getOne(new LambdaQueryWrapper<SysUserInfo>()
                    .eq(SysUserInfo::getTdIsDelete, false).eq(SysUserInfo::getULoginName, userName), false);
            if (userInfo == null) {
                throw new UnknownAccountException("用户名或密码错误");
            }
            String md5Pwd = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
            if (!md5Pwd.equalsIgnoreCase(userInfo.getULoginPWD())) {
                throw new IncorrectCredentialsException("用户名或密码错误");
            }

            List<Role> roles = roleService.findAllByUId(userInfo.getUID());
            Map<String, String> map = new HashMap<>();
            map.put("userId", userInfo.getUID().toString());
            map.put("jti", userInfo.getUID().toString());
            map.put("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", userInfo.getULoginName());
            map.put("role", roles.stream().map(Role::getName).collect(Collectors.joining(",")));
            String tokenStr = JwtUtil.createToken(map);
            return new SimpleAuthenticationInfo(tokenStr, password, getName());

        } else if (authenticationToken instanceof BearerToken) {
            String token = ((BearerToken) authenticationToken).getToken();
            try {
                DecodedJWT decodedJWT = JwtUtil.verify(token);
                return new SimpleAuthenticationInfo(decodedJWT, authenticationToken.getCredentials(), getName());
            } catch (JWTVerificationException e) {
                throw new AuthenticationException(e);
            }
        }

        throw new AuthenticationException("认证失败");
    }
}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/api/controller/UserController.java<|end_filename|>
package club.neters.shrio.demo.api.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "用户管理")
@RestController
public class UserController {

    @ApiOperation(value = "测试授权AdminTest")
    @RequiresRoles({"AdminTest"})
    @GetMapping("/test")
    public String test(){
        return "xx";
    }

    @ApiOperation(value = "测试授权AdminTest2")
    @RequiresRoles({"AdminTest2"})
    @GetMapping("/test2")
    public String test2(){
        return "yy";
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/IRoleModulePermissionService.java<|end_filename|>
package club.neters.blog.app.service;

import club.neters.blog.domain.entity.RoleModulePermission;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
public interface IRoleModulePermissionService extends IService<RoleModulePermission> {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/UserRole.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * 用户角色关系表
 *
 * @author laozhang
 * @date 2021/06/16
 */
@EqualsAndHashCode(callSuper = false)
@EntityDoc(note = "用户角色关系表", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("UserRole")
public class UserRole extends BaseEntity {

    @EntityDoc(note = "UserId")
    @TableField("UserId")
    private Integer UserId;

    @EntityDoc(note = "RoleId")
    @TableField("RoleId")
    private Integer RoleId;

}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/api/controller/LoginController.java<|end_filename|>
package club.neters.shrio.demo.api.controller;

import club.neters.shrio.demo.domain.vo.ApiResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * login controller
 *
 * @author wuare
 * @date 2021/6/25
 */
@Api(tags = "登录管理")
@RestController
public class LoginController {

    @ApiOperation(value = "获取令牌")
    @GetMapping("/login")
    public ApiResultVo<String> login(String username, String password) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            return ApiResultVo.ok((String) subject.getPrincipal());
        } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
            return ApiResultVo.error(e.getMessage());
        } catch (AuthenticationException e) {
            return ApiResultVo.error("认证失败");
        }
    }

    /**
     * 退出
     */
    @ApiOperation(value = "退出")
    @GetMapping("/logout1")
    public ApiResultVo<String> logout1() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ApiResultVo.ok("退出成功");
    }
}


<|start_filename|>ancba-maven-archetype/src/main/resources/archetype-resources/src/main/java/core/config/MybatisPrimaryConfig.java<|end_filename|>
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.core.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * Mybatis primary config
 *
 * @author maven plugin
 * @date 2021/6/23
 */
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@ConditionalOnProperty(name = "spring.datasource.primary.jdbc-url")
@MapperScan(basePackages = "${package}.infra.mapper.primary", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class MybatisPrimaryConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    SqlSessionFactory primarySqlSessionFactory(DataSource primaryDataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(primaryDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/*.xml"));

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

    @Bean
    SqlSessionTemplate primarySqlSessionTemplate(SqlSessionFactory primarySqlSessionFactory) {

        return new SqlSessionTemplate(primarySqlSessionFactory);
    }

    @Bean
    @Primary
    public PlatformTransactionManager primaryPlatformTransactionManager() {
        return new DataSourceTransactionManager(primaryDataSource());
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/TestMuchTableResultServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.domain.entity.TestMuchTableResult;
import club.neters.blog.infra.mapper.primary.TestMuchTableResultMapper;
import club.neters.blog.app.service.ITestMuchTableResultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class TestMuchTableResultServiceImpl extends ServiceImpl<TestMuchTableResultMapper, TestMuchTableResult> implements ITestMuchTableResultService {

}


<|start_filename|>ancba-gateway/src/main/java/club/neters/gateway/controller/CSRFController.java<|end_filename|>
package club.neters.gateway.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class CSRFController {
    @Value("${demo.user}")
    private String userName;

    @GetMapping(value = "/v2/test")
    public String test() {
        return userName + "are u?";
    }
}

<|start_filename|>ancba-user/src/main/java/club/neters/user/domain/entity/BlogArticle.java<|end_filename|>
package club.neters.user.domain.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * BlogArticle表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BlogArticle {

    private Integer bID;

    private String bsubmitter;

    private String btitle;

    private String bcategory;

    private String bcontent;

    private Integer btraffic;

    private Integer bcommentNum;

    private Date bUpdateTime;

    private Date bCreateTime;

    private String bRemark;

    private Boolean IsDeleted;

}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/ModulePermissionServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.domain.entity.ModulePermission;
import club.neters.blog.infra.mapper.primary.ModulePermissionMapper;
import club.neters.blog.app.service.IModulePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class ModulePermissionServiceImpl extends ServiceImpl<ModulePermissionMapper, ModulePermission> implements IModulePermissionService {

}


<|start_filename|>ancba-common/src/main/java/club/neters/common/constant/CommonConstant.java<|end_filename|>
package club.neters.common.constant;

public class CommonConstant {
    public static final String JWT_HMAC256_SECRET = "sdfsdfsrty45634kkhllghtdgdfss345t678fs";
    public static final String JWT_ISSUER = "Blog.Core";
    public static final String AUTHORIZATION_PREFIX = "Bearer";
    public static final String REDIS_SECURITY_ROLE_API_KEY = "security:roles_apis:";
    public static final String[] GW_SECURITY_WHITELIST = {"/", "/doc.html", "/oauth/**",
            "/*/v2/api-docs",
            "/*/v2/api-docs-ext",
            "/actuator/**", "/error", "/open/api", "/actuator/health", "/actuator", "/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/v2/**", "/error"};
}


<|start_filename|>ancba-user/src/main/java/club/neters/user/AncbaUserApplication.java<|end_filename|>
package club.neters.user;

import club.neters.common.annotaion.EnableAncbaSwagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @author maven plugin
 * @date 2021/6/25
 */
@SpringBootApplication
@EnableAncbaSwagger(basePackage = "club.neters.user", title = "接口文档", description = "用户模块接口文档")
@EnableFeignClients
@EnableDiscoveryClient
public class AncbaUserApplication {

    public static void main(String[] args) {
        SpringApplication.run(AncbaUserApplication.class, args);
        System.out.println("================= user微服务启动成功 =============");
    }
}


<|start_filename|>ancba-user/src/main/java/club/neters/user/core/config/security/CustomWebSecurityConfigurer.java<|end_filename|>
package club.neters.user.core.config.security;

import club.neters.user.core.annotation.AnonAllowed;
import club.neters.user.core.constant.CommonConstant;
import club.neters.user.core.util.HandlerMethodUtil;
import club.neters.user.core.util.JsonUtil;
import club.neters.user.domain.vo.ApiResultVo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.method.HandlerMethod;

import javax.annotation.Resource;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 资源服务器配置
 *
 * @author wuare
 * @date 2021/7/1
 */
@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CustomWebSecurityConfigurer extends WebSecurityConfigurerAdapter implements ApplicationContextAware {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();
        http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
                .authenticationProvider(authenticationProvider());

        // 配置认证权限处理器
        http.authorizeRequests().accessDecisionManager(accessDecisionManager());
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
        // 配置401/403处理器
        http.exceptionHandling().accessDeniedHandler(new AdminAccessDeineHandler());
        // 不创建会话 - 即通过前端传token到后台过滤器中验证是否存在访问权限
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.anonymous().authenticationFilter(anonymousAuthenticationFilter());
        http.authorizeRequests()
                .anyRequest()
                .authenticated();
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(authenticationProvider());
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider(jwtDecoder());
        jwtAuthenticationProvider.setJwtAuthenticationConverter(jwtAuthenticationConverter());
        return jwtAuthenticationProvider;
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withSecretKey(new SecretKeySpec(
                CommonConstant.JWT_HMAC256_SECRET.getBytes(StandardCharsets.UTF_8), "HMAC256"))
                .build();
    }

    @Bean
    public JwtAuthenticationConverter jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        // 把Jwt中的信息转化到SecurityContext#authentication#authorities中
        grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");

        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
        return jwtAuthenticationConverter;
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return (request, response, accessDeniedException) -> {
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write(JsonUtil.toJson(ApiResultVo.forbidden("没有权限访问该资源")));
        };
    }

    @Bean
    public AccessDecisionManager accessDecisionManager() {
        List<AccessDecisionVoter<?>> voterList = new ArrayList<>();
        voterList.add(accessDecisionVoter());
        return new AffirmativeBased(voterList);
    }

    @Bean
    public AccessDecisionVoter<FilterInvocation> accessDecisionVoter() {
        return new CustomAccessDecisionVoter();
    }

    @Bean
    public AnonymousAuthenticationFilter anonymousAuthenticationFilter() {
        return new AnonymousAuthenticationFilter("ANONYMOUS") {
            @Override
            public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

                // TODO
                String[] urls = CommonConstant.SECURITY_WHITELIST;
                HttpServletRequest request = (HttpServletRequest) req;
                HttpServletResponse response = (HttpServletResponse) res;
                if (HttpMethod.OPTIONS.matches(request.getMethod())) {
                    super.doFilter(req, res, chain);
                    return;
                }
                for (String url : urls) {
                    RequestMatcher pathMatcher = new AntPathRequestMatcher(url);
                    if (pathMatcher.matches(request)) {
                        super.doFilter(req, res, chain);
                        return;
                    }
                }

                // 匿名注解允许匿名访问
                HandlerMethod handlerMethod = HandlerMethodUtil.getHandlerMethod(request);
                if (handlerMethod != null) {
                    AnonAllowed annotation = handlerMethod.getMethodAnnotation(AnonAllowed.class);
                    if (annotation != null) {
                        super.doFilter(req, res, chain);
                        return;
                    }
                }

                String header = request.getHeader(HttpHeaders.AUTHORIZATION);
                if (header == null || "".equals(header)) {
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("text/javascript;charset=utf-8");
                    response.getWriter().print(JsonUtil.toJson(ApiResultVo.unauthorized("未认证，请先登录！")));
                    response.setStatus(401);
                    return;
                }
                super.doFilter(req, res, chain);
            }
        };
    }


    @Resource
    private ApplicationContext applicationContext;

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/vo/ApiResultVo.java<|end_filename|>
package club.neters.blog.domain.vo;

import lombok.Data;
import org.springframework.http.HttpStatus;

/**
 * common vo
 *
 * @author wuare
 * @date 2021/6/16
 */
@Data
public class ApiResultVo<T> {

    /**
     * 错误代码
     */
    private long code;

    /**
     * 错误信息
     */
    private String message;

    /**
     * 返回数据
     */
    private T data;

    public static <T> ApiResultVo<T> ok(T data) {
        return ok(data, "success");
    }

    public static <T> ApiResultVo<T> ok(T data, String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setData(data);
        bean.setCode(200);
        bean.setMessage(msg);
        return bean;
    }


    public static <T> ApiResultVo<T> error(T data) {
        return error(data, "服务器异常");
    }

    public static <T> ApiResultVo<T> error(String msg) {
        return error(null, msg);
    }

    public static <T> ApiResultVo<T> error(T data, String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setData(data);
        bean.setCode(500);
        bean.setMessage(msg);
        return bean;
    }

    public static <T> ApiResultVo<T> badRequest(String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setCode(400);
        bean.setMessage(msg);
        return bean;
    }

    public static <T> ApiResultVo<T> unauthorized(String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setCode(401);
        bean.setMessage(msg);
        return bean;
    }

    public static <T> ApiResultVo<T> forbidden(String msg) {
        ApiResultVo<T> bean = new ApiResultVo<>();
        bean.setCode(403);
        bean.setMessage(msg);
        return bean;
    }
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/app/service/ISysUserInfoService.java<|end_filename|>
package club.neters.app.service;

import club.neters.domain.entity.SysUserInfo;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-30
 */
public interface ISysUserInfoService extends IService<SysUserInfo> {
    SysUserInfo findOne(String name, String pass);
    List<SysUserInfo> allSysUserInfo(Integer uID);
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/core/config/OAuth2AuthorizationServerConfig.java<|end_filename|>
package club.neters.core.config;

import club.neters.app.service.UserDetailService;
import club.neters.core.constant.CommonConstant;
import club.neters.core.util.UserPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.util.Collections;

/**
 * 客户端信息配置和access_token生成配置
 */
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private UserDetailService userDetailService;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                .tokenKeyAccess("permitAll()")
                // 验证获取Token的验证信息
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    /**
     * 配置授权终端（authorization）
     * 涉及：令牌（token）的增强器/转换器、token存储、令牌服务(token services)、密码编码器
     * TokenConverter: 配置签名、accessToken声明
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Collections.singletonList(accessTokenConverter()));
        endpoints.tokenStore(jwtTokenStore())
                .tokenEnhancer(tokenEnhancerChain)
                .authenticationManager(authentication -> daoAuhthenticationOauthProvider().authenticate(authentication));
    }

    /**
     * 客户端信息配置
     * 暂用内存模式
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        clients.inMemory()

                //Client1
                .withClient("clientapp1")
                .secret(passwordEncoder().encode("<PASSWORD>"))
                .authorizedGrantTypes("password", "refresh_token")
                .authorities("READ_ONLY_CLIENT")
                .scopes("all")
                .resourceIds("clientapp-res")
                .redirectUris("http://localhost:8181/login")
                .accessTokenValiditySeconds(5000)
                .refreshTokenValiditySeconds(50000)

                .and()
                //Client2
                .withClient("clientapp2")
                .secret(passwordEncoder().encode("secret"))
                .authorizedGrantTypes("implicit", "authorization_code", "client_credentials")
                .scopes("read", "write", "foo", "bar", "webclient")
                .autoApprove(true)
                .accessTokenValiditySeconds(3600)
                .redirectUris("http://localhost:8181/login");
    }


    @Bean
    public DefaultTokenServices tokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(jwtTokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }

    /**
     * 使用jwtTokenStore存储token
     */
    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public AuthenticationProvider daoAuhthenticationOauthProvider() {
        CustomAuthenticationProvider daoAuthenticationProvider = new CustomAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailService);
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setPasswordEncoder(new UserPasswordEncoder());
        return daoAuthenticationProvider;
    }

    /**
     * 用于生成jwt
     */
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        // RSA非对称加密串，生成及加解密签名验签
        converter.setVerifierKey(CommonConstant.JWT_HMAC256_SECRET);
        converter.setSigningKey(CommonConstant.JWT_HMAC256_SECRET);
        //使用自定义的 TokenConverter
        converter.setAccessTokenConverter(new JwtCustomerAccessTokenConverter());
        return converter;
    }

//    /**
//     * 使用非对称加密算法对token签名
//     */
//    @Bean
//    public JwtAccessTokenConverter jwtAccessTokenConverter() {
//        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
//        converter.setKeyPair(keyPair());
//        return converter;
//    }
//
//    /**
//     * 从classpath下的密钥库中获取密钥对(公钥+私钥)
//     */
//    @Bean
//    public KeyPair keyPair() {
//        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
//        KeyPair keyPair = factory.getKeyPair("jwt", "123456".toCharArray());
//        return keyPair;
//    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/core/util/UserPasswordEncoder.java<|end_filename|>
package club.neters.core.util;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

public class UserPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        return null;
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (rawPassword == null) {
            return false;
        }

        // 单独对密码器做处理，注意大小写
        String md5Pwd = DigestUtils.md5DigestAsHex(rawPassword.toString().getBytes(StandardCharsets.UTF_8));

        return md5Pwd.toUpperCase().equals(encodedPassword);
    }
}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/UserRoleServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.app.service.IUserRoleService;
import club.neters.blog.domain.entity.UserRole;
import club.neters.blog.infra.mapper.primary.UserRoleMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/Modules.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * Modules表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode(callSuper = false)
@EntityDoc(note = "Modules", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("Modules")
public class Modules extends BaseEntity {


    @EntityDoc(note = "Name")
    @TableField("Name")
    private String Name;

    @EntityDoc(note = "LinkUrl")
    @TableField("LinkUrl")
    private String LinkUrl;

    @EntityDoc(note = "Area")
    @TableField("Area")
    private String Area;

    @EntityDoc(note = "Controller")
    @TableField("Controller")
    private String Controller;

    @EntityDoc(note = "Action")
    @TableField("Action")
    private String Action;

    @EntityDoc(note = "Icon")
    @TableField("Icon")
    private String Icon;

    @EntityDoc(note = "Code")
    @TableField("Code")
    private String Code;

    @EntityDoc(note = "OrderSort")
    @TableField("OrderSort")
    private Integer OrderSort;

    @EntityDoc(note = "Description")
    @TableField("Description")
    private String Description;

    @EntityDoc(note = "IsMenu")
    @TableField("IsMenu")
    private Boolean IsMenu;

    @EntityDoc(note = "Enabled")
    @TableField("Enabled")
    private Boolean Enabled;


    @EntityDoc(note = "ParentId")
    @TableField("ParentId")
    private Integer ParentId;
}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/TasksQz.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * TasksQz表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@EntityDoc(note = "TasksQz", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("TasksQz")
public class TasksQz {

    @EntityDoc(note = "Id")
    @TableId(value = "Id", type = IdType.AUTO)
    private Integer Id;

    @EntityDoc(note = "Name")
    @TableField("Name")
    private String Name;

    @EntityDoc(note = "JobGroup")
    @TableField("JobGroup")
    private String JobGroup;

    @EntityDoc(note = "Cron")
    @TableField("Cron")
    private String Cron;

    @EntityDoc(note = "AssemblyName")
    @TableField("AssemblyName")
    private String AssemblyName;

    @EntityDoc(note = "ClassName")
    @TableField("ClassName")
    private String ClassName;

    @EntityDoc(note = "Remark")
    @TableField("Remark")
    private String Remark;

    @EntityDoc(note = "RunTimes")
    @TableField("RunTimes")
    private Integer RunTimes;

    @EntityDoc(note = "BeginTime")
    @TableField("BeginTime")
    private Date BeginTime;

    @EntityDoc(note = "EndTime")
    @TableField("EndTime")
    private Date EndTime;

    @EntityDoc(note = "TriggerType")
    @TableField("TriggerType")
    private Integer TriggerType;

    @EntityDoc(note = "IntervalSecond")
    @TableField("IntervalSecond")
    private Integer IntervalSecond;

    @EntityDoc(note = "IsStart")
    @TableField("IsStart")
    private Boolean IsStart;

    @EntityDoc(note = "JobParams")
    @TableField("JobParams")
    private String JobParams;

    @EntityDoc(note = "IsDeleted")
    @TableField("IsDeleted")
    private Boolean IsDeleted;

    @EntityDoc(note = "CreateTime")
    @TableField("CreateTime")
    private Date CreateTime;

}

<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/infra/shiro/AuthFilter.java<|end_filename|>
package club.neters.shrio.demo.infra.shiro;


import club.neters.shrio.demo.core.constant.CommonConstant;
import club.neters.shrio.demo.core.util.HttpContextUtil;
import club.neters.shrio.demo.core.util.JsonUtil;
import club.neters.shrio.demo.core.util.JwtUtil;
import club.neters.shrio.demo.domain.vo.ApiResultVo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.BearerToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthFilter extends BasicHttpAuthenticationFilter {

    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        ApiResultVo<Object> resultVo = ApiResultVo.error("授权认识失败");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        // 自定义返回内容
        response.getWriter().write(JsonUtil.toJson(resultVo));
    }

    /**
     * 生成自定义token
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        //获取请求token
        String token = JwtUtil.getRequestToken((HttpServletRequest) request);
        if (token != null) {
            token = token.replace("Bearer ", "");
        }
        return new BearerToken(token);
    }


    /**
     * 判断用户是否想要登入。
     * 检测header里面是否包含Authorization字段即可
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader(CommonConstant.JWT_TOKEN_HEADER);
        return authorization != null;
    }

    /**
     * 步骤1.所有请求全部拒绝访问
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());
    }

    /**
     * 步骤2，拒绝访问的请求，会调用onAccessDenied方法，
     * onAccessDenied方法先获取 token，
     * 再调用executeLogin方法
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token，如果token不存在，直接返回
        String token = JwtUtil.getRequestToken((HttpServletRequest) request);
        if (StringUtils.isBlank(token)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
            httpResponse.setCharacterEncoding("UTF-8");
            Map<String, Object> result = new HashMap<>();
            result.put("status", 400);
            result.put("msg", "请先登录");
            httpResponse.getWriter().print(JsonUtil.toJson(result));
            return false;
        }
        return executeLogin(request, response);
    }

    /**
     * token失效时候调用
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        httpResponse.setCharacterEncoding("UTF-8");
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            Map<String, Object> result = new HashMap<>();
            result.put("status", 400);
            result.put("msg", "登录凭证已失效，请重新登录");
            httpResponse.getWriter().print(JsonUtil.toJson(result));
        } catch (IOException ignored) {
        }
        return false;
    }

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/Permission.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * Permission表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode(callSuper = false)
@EntityDoc(note = "Permission", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("Permission")
public class Permission extends BaseEntity {

    @EntityDoc(note = "Code")
    @TableField("Code")
    private String Code;

    @EntityDoc(note = "Name")
    @TableField("Name")
    private String Name;

    @EntityDoc(note = "IsButton")
    @TableField("IsButton")
    private Boolean IsButton;

    @EntityDoc(note = "IsHide")
    @TableField("IsHide")
    private Boolean IsHide;

    @EntityDoc(note = "IskeepAlive")
    @TableField("IskeepAlive")
    private Boolean IskeepAlive;

    @EntityDoc(note = "Func")
    @TableField("Func")
    private String Func;

    @EntityDoc(note = "OrderSort")
    @TableField("OrderSort")
    private Integer OrderSort;

    @EntityDoc(note = "Icon")
    @TableField("Icon")
    private String Icon;

    @EntityDoc(note = "Description")
    @TableField("Description")
    private String Description;

    @EntityDoc(note = "Enabled")
    @TableField("Enabled")
    private Boolean Enabled;


    @EntityDoc(note = "Pid")
    @TableField("Pid")
    private int Pid;

    @EntityDoc(note = "Mid")
    @TableField("Mid")
    private int Mid;

}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/ISysUserInfoService.java<|end_filename|>
package club.neters.blog.app.service;

import club.neters.blog.domain.entity.SysUserInfo;
import club.neters.blog.domain.request.user.UserInfoRequest;
import club.neters.blog.domain.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
public interface ISysUserInfoService extends IService<SysUserInfo> {

    List<UserInfoVo> findList(UserInfoRequest query);

    SysUserInfo findOne(String name, String pass);
}


<|start_filename|>ancba-common/src/main/java/club/neters/common/config/swagger/SwaggerConfigProperties.java<|end_filename|>
package club.neters.common.config.swagger;

import org.springframework.core.Ordered;

/**
 * @author wuare
 * @date 2021/6/29
 */
public class SwaggerConfigProperties implements Ordered {

    private String basePackage;
    private String title;
    private String description;
    private String version;
    private String email;
    private Boolean oauth = true;

    public String getBasePackage() {
        return basePackage;
    }

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int getOrder() {
        return 0;
    }

    public Boolean getOauth() {
        return oauth;
    }

    public void setOauth(Boolean oauth) {
        this.oauth = oauth;
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/core/util/JwtUtils.java<|end_filename|>
package club.neters.blog.core.util;

import club.neters.blog.core.constant.CommonConstant;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JwtUtils {

    /**
     * 生成token header.payload.sing
     */
    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 1);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach(builder::withClaim);
        //生成token，头部默认jwt和Base64编码
        return builder
                .withExpiresAt(instance.getTime())   //设置过期时间
                .withIssuer(CommonConstant.JWT_ISSUER)   //设置issuer
                .sign(Algorithm.HMAC256(CommonConstant.JWT_HMAC256_SECRET));
    }

    /**
     * 验证 token 合法性
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(CommonConstant.JWT_HMAC256_SECRET)).build().verify(token);
    }

}

<|start_filename|>ancba-user/src/main/java/club/neters/user/app/service/UserApiService.java<|end_filename|>
package club.neters.user.app.service;

import club.neters.user.core.config.feign.FeignConfig;
import club.neters.user.domain.entity.BlogArticle;
import club.neters.user.domain.request.UserInfoRequestFromBlog;
import club.neters.user.domain.vo.ApiResultVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@FeignClient(value = "ancba-blog", configuration = {FeignConfig.class})
public interface UserApiService {
    /**
     * 查询用户数据
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    ApiResultVo<List<BlogArticle>> loadUserListPage(UserInfoRequestFromBlog query);
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/TestMuchTableResult.java<|end_filename|>
package club.neters.blog.domain.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * <p>
 * 
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("TestMuchTableResult")
public class TestMuchTableResult implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableField("moduleName")
    private String moduleName;

    @TableField("permName")
    private String permName;

    @TableField("rid")
    private Integer rid;

    @TableField("mid")
    private Integer mid;

    @TableField("pid")
    private Integer pid;


}


<|start_filename|>ancba-common/src/main/java/club/neters/common/util/JsonUtil.java<|end_filename|>
package club.neters.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Json Util
 *
 * @author wuare
 * @date 2021/6/16
 */
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private JsonUtil() {
    }

    /**
     * json to bean
     */
    public static <T> T toBean(String content, Class<T> valueType) {
        try {
            return objectMapper.readValue(content, valueType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * json to bean
     */
    public static <T> T toBean(String content, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(content, typeReference);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * object to json
     */
    public static <T> String toJson(T value) {
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/core/annotation/EntityDoc.java<|end_filename|>
package club.neters.blog.core.annotation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 实体类注释
 * 用于代码生成器获取实体类注释及其字段注释
 *
 * @author laozhang
 * @date 2021/06/12
 */
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface EntityDoc {

    /**
     * 注释
     * 类注释/字段注释
     *
     * @return note
     */
    String note() default "";

    /**
     * 是否属于类注释
     *
     * @return 是否是类
     */
    boolean isClass() default false;
}


<|start_filename|>ancba-user/src/main/java/club/neters/user/core/config/MybatisSecondConfig.java<|end_filename|>
package club.neters.user.core.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * Mybatis second config
 *
 * @author maven plugin
 * @date 2021/6/23
 */
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@ConditionalOnProperty(name = "spring.datasource.second.jdbc-url")
@MapperScan(basePackages = "club.neters.user.infra.mapper.second", sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class MybatisSecondConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.second")
    DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    SqlSessionFactory secondSqlSessionFactory(DataSource secondDataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(secondDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/second/*.xml"));

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

    @Bean
    SqlSessionTemplate secondSqlSessionTemplate(SqlSessionFactory secondSqlSessionFactory) {
        return new SqlSessionTemplate(secondSqlSessionFactory);
    }

    @Bean
    public PlatformTransactionManager secondPlatformTransactionManager() {
        return new DataSourceTransactionManager(secondDataSource());
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/GuestbookServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.domain.entity.Guestbook;
import club.neters.blog.infra.mapper.primary.GuestbookMapper;
import club.neters.blog.app.service.IGuestbookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class GuestbookServiceImpl extends ServiceImpl<GuestbookMapper, Guestbook> implements IGuestbookService {

}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/app/service/ISysUserInfoService.java<|end_filename|>
package club.neters.shrio.demo.app.service;

import club.neters.shrio.demo.domain.entity.SysUserInfo;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-25
 */
public interface ISysUserInfoService extends IService<SysUserInfo> {
    SysUserInfo findOne(String name, String pass);
    List<SysUserInfo> allSysUserInfo(Integer uID);
}


<|start_filename|>ancba-gateway/src/main/java/club/neters/gateway/config/loging/RequestLoggingDecorator.java<|end_filename|>
package club.neters.gateway.config.loging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import reactor.core.publisher.Flux;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;

public class RequestLoggingDecorator extends ServerHttpRequestDecorator {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggingDecorator.class);

    public RequestLoggingDecorator(ServerHttpRequest delegate) {
        super(delegate);
    }

    @Override
    public Flux<DataBuffer> getBody() {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        return super.getBody().doOnNext(dataBuffer -> {
            try {
                Channels.newChannel(byteArrayOutputStream).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
                String body = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
                LOGGER.info("Request: payload={}", body);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/RoleModulePermission.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * 用户模块菜单关系表
 *
 * @author laozhang
 * @date 2021/06/16
 */
@EqualsAndHashCode(callSuper = false)
@EntityDoc(note = "用户模块菜单关系表", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("RoleModulePermission")
public class RoleModulePermission extends BaseEntity {

    @EntityDoc(note = "RoleId")
    @TableField("RoleId")
    private Integer RoleId;

    @EntityDoc(note = "ModuleId")
    @TableField("ModuleId")
    private Integer ModuleId;

    @EntityDoc(note = "PermissionId")
    @TableField("PermissionId")
    private Integer PermissionId;

}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/core/util/JwtUtil.java<|end_filename|>
package club.neters.shrio.demo.core.util;

import club.neters.shrio.demo.core.constant.CommonConstant;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class JwtUtil {

    /**
     * 生成token header.payload.sing
     */
    public static String createToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 1);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach(builder::withClaim);
        //生成token，头部默认jwt和Base64编码
        return builder
                .withExpiresAt(instance.getTime())   //设置过期时间
                .withIssuer(CommonConstant.JWT_ISSUER)   //设置issuer
                .sign(Algorithm.HMAC256(CommonConstant.JWT_HMAC256_SECRET));
    }

    /**
     * 获取请求的token
     */
    public static String getRequestToken(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader(HttpHeaders.AUTHORIZATION);
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter(HttpHeaders.AUTHORIZATION);
        }
        return token;
    }

    /**
     * 验证 token 合法性
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(CommonConstant.JWT_HMAC256_SECRET)).build().verify(token);
    }

    /**
     * 验证 token 是否过期
     */
    public static boolean isNotExpired(String token) {
        try {
            token = token.replace("Bearer ","");
            DecodedJWT jwt = verify(token);
            Map<String, Claim> claims = jwt.getClaims();
            Integer exp = Optional.ofNullable(claims.get("exp")).map(Claim::asInt).orElse(0);
            return System.currentTimeMillis() / 1000L <= exp;
        } catch (JWTVerificationException exception) {
            return false;
        }
    }

    /**
     * 获取当前token下的角色列表
     */
    public static List<String> getRoleFromToken(String token) {
        token = token.replace("Bearer ","");
        Algorithm algorithm = Algorithm.HMAC256(CommonConstant.JWT_HMAC256_SECRET);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(CommonConstant.JWT_ISSUER)
                .build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        String roles = Optional.ofNullable(claims.get("role")).map(Claim::asString).orElse("");
        return  StringUtils.isNotEmpty(roles) ? Arrays.asList(roles.split(",")) : null;
    }
}

<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/core/constant/CommonConstant.java<|end_filename|>
package club.neters.core.constant;

public class CommonConstant {
    public static final String JWT_HMAC256_SECRET = "<KEY>";
    public static final String JWT_ISSUER = "Blog.Core";
    public static final String JWT_TOKEN_HEADER = "Authorization";
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/RoleServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.app.service.IRoleService;
import club.neters.blog.domain.entity.Role;
import club.neters.blog.infra.mapper.primary.RoleMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/TopicDetailServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.app.service.ITopicDetailService;
import club.neters.blog.domain.entity.TopicDetail;
import club.neters.blog.infra.mapper.primary.TopicDetailMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class TopicDetailServiceImpl extends ServiceImpl<TopicDetailMapper, TopicDetail> implements ITopicDetailService {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/ModulesServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.domain.entity.Modules;
import club.neters.blog.infra.mapper.primary.ModulesMapper;
import club.neters.blog.app.service.IModulesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class ModulesServiceImpl extends ServiceImpl<ModulesMapper, Modules> implements IModulesService {

}


<|start_filename|>ancba-common/src/main/java/club/neters/common/annotaion/EnableAncbaSwagger.java<|end_filename|>
package club.neters.common.annotaion;

import club.neters.common.config.swagger.SwaggerRegistrar;
import org.springframework.context.annotation.Import;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author wuare
 * @date 2021/6/29
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(SwaggerRegistrar.class)
public @interface EnableAncbaSwagger {

    String basePackage();

    String title() default "Api Documentation";

    String description() default "Api Documentation";

    String version() default "1.0";

    String email() default "<EMAIL>";

    boolean oauth() default true;
}


<|start_filename|>ancba-maven-archetype/src/main/resources/archetype-resources/src/main/java/core/exception/CommonExceptionHandler.java<|end_filename|>
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.core.exception;

import ${package}.domain.vo.ApiResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * common exception handler
 *
 * @author maven plugin
 * @date 2021/6/16
 */
@Slf4j
@ControllerAdvice
public class CommonExceptionHandler {

    /**
     * <code>@Valid @RequestBody</code>抛出的异常
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public ApiResultVo<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return handleValidException(e);
    }

    /**
     * <code>@Valid</code>没有@RequestBody时抛出的异常
     */
    @ExceptionHandler(value = {BindException.class})
    @ResponseBody
    public ApiResultVo<?> handleBindException(BindException e) {
        return handleValidException(e);
    }

    private ApiResultVo<?> handleValidException(BindException e) {
        log.error("参数绑定异常", e);
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            return ApiResultVo.error(allErrors.get(0).getDefaultMessage());
        }
        return ApiResultVo.error("参数错误");
    }

    /**
     * 自定义异常处理
     */
    @ExceptionHandler(value = {ServiceException.class})
    @ResponseBody
    public ApiResultVo<?> handleServiceException(final ServiceException e) {
        log.error("未处理Service异常", e);
        return ApiResultVo.error(e.getMessage());
    }

    /**
     * 处理异常
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public ApiResultVo<?> handleException(Exception e) {
        log.error("未处理异常", e);
        return ApiResultVo.error("服务异常 " + e.getMessage());
    }
}


<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/infra/mapper/primary/RoleMapper.java<|end_filename|>
package club.neters.infra.mapper.primary;


import club.neters.domain.entity.Role;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Repository
public interface RoleMapper extends BaseMapper<Role> {
    @Select("select * from Role where Id in (select RoleId from UserRole where UserId = #{uID})")
    List<Role> findAllByUId(Integer uID);
}


<|start_filename|>ancba-gateway/src/main/java/club/neters/gateway/AncbaGateWayApplication.java<|end_filename|>
package club.neters.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * gateway
 *
 * @author wuare
 * @date 2021/6/25
 */

@SpringBootApplication
@EnableDiscoveryClient
public class AncbaGateWayApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(AncbaGateWayApplication.class, args);
        // 读取启用配置文件中的属性
        String authorName = applicationContext.getEnvironment().getProperty("demo");
        System.out.println("================= gw网关服务启动成功，作者：" + authorName + "=============");
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/domain/entity/Guestbook.java<|end_filename|>
package club.neters.blog.domain.entity;

import club.neters.blog.core.annotation.EntityDoc;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * Guestbook表
 *
 * @author laozhang
 * @date 2021/06/12
 */
@EqualsAndHashCode()
@EntityDoc(note = "Guestbook", isClass = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("Guestbook")
public class Guestbook {

    @EntityDoc(note = "Id")
    @TableId(value = "Id", type = IdType.AUTO)
    private Integer Id;

    @EntityDoc(note = "blogId")
    @TableField("blogId")
    private Integer blogId;

    @EntityDoc(note = "createdate")
    @TableField("createdate")
    private Date createdate;

    @EntityDoc(note = "username")
    @TableField("username")
    private String username;

    @EntityDoc(note = "phone")
    @TableField("phone")
    private String phone;

    @EntityDoc(note = "QQ")
    @TableField("QQ")
    private String QQ;

    @EntityDoc(note = "body")
    @TableField("body")
    private String body;

    @EntityDoc(note = "ip")
    @TableField("ip")
    private String ip;

    @EntityDoc(note = "isshow")
    @TableField("isshow")
    private Boolean isshow;
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/api/controller/BlogController.java<|end_filename|>
package club.neters.blog.api.controller;

import club.neters.blog.app.service.IBlogArticleService;
import club.neters.blog.domain.entity.BlogArticle;
import club.neters.blog.domain.request.user.UserInfoRequest;
import club.neters.blog.domain.vo.ApiResultVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 *
 * @author laozhang
 * @date 2021/06/12
 */
@Api(tags = "用户管理")
@RestController
public class BlogController {


    private final IBlogArticleService blogArticleService;

    @Autowired
    public BlogController(IBlogArticleService blogArticleService) {
        this.blogArticleService = blogArticleService;
    }


    /**
     * 列表查询
     *
     * @return 用户列表
     */
    @ApiOperation(value = "获取用户列表")
    @GetMapping(value = "list")
    public ApiResultVo<List<BlogArticle>> listPage(UserInfoRequest query) {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        System.out.println(authentication != null ? authentication.getAuthorities() : "no login");
        System.out.println(query);

        LambdaQueryWrapper<BlogArticle> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BlogArticle::getIsDeleted, false)
                .orderByDesc(BlogArticle::getBID)
                .last("limit 3");

        List<BlogArticle> list = blogArticleService.list(wrapper);
        return ApiResultVo.ok(list);
    }

    @PreAuthorize("hasAnyAuthority('AdminTest')")
    @ApiOperation(value = "测试接口授权")
    @GetMapping(value = "test")
    public String test() {
        return "当前角色需要admin权限，恭喜你访问成功了!";
    }


    @ApiOperation(value = "测试网关是否正常传递Post-body")
    @PostMapping(value = "testBody")
    public UserInfoRequest testBody(@RequestBody UserInfoRequest userInfoRequest) {
        return userInfoRequest;
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/RoleModulePermissionServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.app.service.IRoleModulePermissionService;
import club.neters.blog.domain.entity.RoleModulePermission;
import club.neters.blog.infra.mapper.primary.RoleModulePermissionMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class RoleModulePermissionServiceImpl extends ServiceImpl<RoleModulePermissionMapper, RoleModulePermission> implements IRoleModulePermissionService {

}


<|start_filename|>ancba-gateway/src/main/java/club/neters/gateway/config/limit/LimitConfig.java<|end_filename|>
package club.neters.gateway.config.limit;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import reactor.core.publisher.Mono;

@Configuration
public class LimitConfig {

    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }


    @Bean
    @Order(-100)
    public RedisRateLimiter redisRateLimiter() {
        return new RedisRateLimiter(1, 2);
    }
}



<|start_filename|>ancba-gateway/src/main/java/club/neters/gateway/config/security/AccessManager.java<|end_filename|>
package club.neters.gateway.config.security;

import club.neters.common.constant.CommonConstant;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class AccessManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    /**
     * 使用Redis处理api-role的关系
     * Todo 待扩展
     */
//    private RedisTemplate redisTemplate;
    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        ServerHttpRequest request = authorizationContext.getExchange().getRequest();

        // 1、OPTIONS全部放过
        if (request.getMethod() == HttpMethod.OPTIONS) {
            return Mono.just(new AuthorizationDecision(true));
        }

        // 取出路径+token
        PathMatcher pathMatcher = new AntPathMatcher();
        String path = request.getURI().getPath();
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        // 2、token为空全部拒绝
        if (!(StringUtils.isNotBlank(token) && token.startsWith(CommonConstant.AUTHORIZATION_PREFIX))) {
            return Mono.just(new AuthorizationDecision(false));
        }


        // 3、从Redis中获取role-api关系集合
//        Map<String, Object> roleApiMap = redisTemplate.opsForHash().entries(CommonConstant.REDIS_SECURITY_ROLE_API_KEY);
        Map<String, Object> roleApiMap = new HashMap<String, Object>();
        // 测试数据，演示效果
        ArrayList<String> rolesOfUserTestPath = new ArrayList<>();
        rolesOfUserTestPath.add("AdminTest");
        roleApiMap.put("/user/test", rolesOfUserTestPath);

        // 4、不在roleApiMap中的，全部放过，仅做认证即可
        boolean doNotMoreAuthorizationCheck = true;
        Set<String> rolesOfCurrentPath = CollectionUtil.newHashSet();
        for (Map.Entry<String, Object> permRoles : roleApiMap.entrySet()) {
            String perm = permRoles.getKey();
            if (pathMatcher.match(perm, path)) {
                rolesOfCurrentPath.addAll(Convert.toList(String.class, permRoles.getValue()));
                doNotMoreAuthorizationCheck = false;
            }
        }
        if (doNotMoreAuthorizationCheck) {
            return Mono.just(new AuthorizationDecision(true));
        }

        // 5、判断用户JWT中携带的角色是否有能通过权限拦截的角色
        Mono<AuthorizationDecision> authorizationDecisionMono = mono
                .filter(Authentication::isAuthenticated)
                .flatMapIterable(Authentication::getAuthorities)
                .map(GrantedAuthority::getAuthority)
                .any(authority -> {
                    String role = authority.substring("SCOPE_".length());
                    return !CollectionUtils.isEmpty(rolesOfCurrentPath) && rolesOfCurrentPath.contains(role);
                })
                .map(AuthorizationDecision::new)
                .defaultIfEmpty(new AuthorizationDecision(false));
        return authorizationDecisionMono;
    }
}

<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/core/config/ShiroConfig.java<|end_filename|>
package club.neters.shrio.demo.core.config;

import club.neters.shrio.demo.infra.shiro.AuthFilter;
import club.neters.shrio.demo.infra.shiro.UserRealm;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro config
 *
 * @author wuare
 * @date 2021/6/25
 */
@Configuration

public class ShiroConfig {

    /**
     * 自定义realm
     */
    @Bean("securityManager")
    public SecurityManager securityManager(UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        securityManager.setRememberMeManager(null);
        securityManager.setSubjectDAO(subjectDAO());
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }

    /**
     * 自定义过滤器
     */
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        //oauth过滤
        Map<String, Filter> filters = new HashMap<>();
        filters.put("authc", new AuthFilter());
        shiroFilter.setFilters(filters);

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/", "anon");
        filterMap.put("/login", "anon");
        filterMap.put("/logout1", "anon");

        filterMap.put("/swagger-ui.html", "anon");//swagger
        filterMap.put("/webjars/**", "anon");
        filterMap.put("/v2/**", "anon");
        filterMap.put("/swagger-resources/**", "anon");//swagger

        //可以手动配置，也可以打注解，推荐注解的方式
        filterMap.put("/test", "roles[AdminTest]");
        filterMap.put("/test2", "roles[AdminTest2]");
        filterMap.put("/list", "roles[admin,user]");
        filterMap.put("/delete", "perms[admin:delete]");


        filterMap.put("/**", "authc");
        shiroFilter.setFilterChainDefinitionMap(filterMap);

        return shiroFilter;
    }

    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     * 加入注解的使用，不加入这个注解不生效
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

    @Bean
    public DefaultSubjectDAO subjectDAO() {
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        subjectDAO.setSessionStorageEvaluator(sessionStorageEvaluator());
        return subjectDAO;
    }

    @Bean
    public DefaultSessionStorageEvaluator sessionStorageEvaluator() {
        DefaultSessionStorageEvaluator sessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        sessionStorageEvaluator.setSessionStorageEnabled(false);
        return sessionStorageEvaluator;
    }

    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionValidationSchedulerEnabled(false);
        return sessionManager;
    }

}


<|start_filename|>ancba-user/src/main/java/club/neters/user/core/config/feign/FeignConfig.java<|end_filename|>
package club.neters.user.core.config.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        requestTemplate.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION));
    }
}

<|start_filename|>ancba-authorizer-oauth2/src/main/java/club/neters/domain/entity/Role.java<|end_filename|>
package club.neters.domain.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * 角色信息表
 *
 * @author laozhang
 * @date 2021/06/16
 */
@EqualsAndHashCode(callSuper = false)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("Role")
public class Role extends BaseEntity {
    @TableField("Name")
    private String Name;

    @TableField("Description")
    private String Description;

    @TableField("OrderSort")
    private Integer OrderSort;

    @TableField("Enabled")
    private Boolean Enabled;

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/impl/BlogArticleServiceImpl.java<|end_filename|>
package club.neters.blog.app.service.impl;

import club.neters.blog.domain.entity.BlogArticle;
import club.neters.blog.infra.mapper.primary.BlogArticleMapper;
import club.neters.blog.app.service.IBlogArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
@Service
public class BlogArticleServiceImpl extends ServiceImpl<BlogArticleMapper, BlogArticle> implements IBlogArticleService {

}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/app/service/ITopicDetailService.java<|end_filename|>
package club.neters.blog.app.service;

import club.neters.blog.domain.entity.TopicDetail;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
public interface ITopicDetailService extends IService<TopicDetail> {

}


<|start_filename|>ancba-shrio-demo/src/main/java/club/neters/shrio/demo/core/generator/MyBatisPlusGenerator.java<|end_filename|>
package club.neters.shrio.demo.core.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;

/**
 * MyBatis-Plus code generator
 *
 * @author wuare
 * @date 2021/6/16
 */
public class MyBatisPlusGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + tip + "：");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir") + File.separator + "ancba-user";
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("laozhang");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // TODO 数据源名称
        String dsName = "primary";

        String fileName = "application.yml";
        // 数据源配置 从yaml文件中获取
//        Yaml yaml = new Yaml();
//        InputStream inputStream = Thread.currentThread().getContextClassLoader()
//                .getResourceAsStream(fileName);
//        Map<String, HashMap<String, Map<String, Object>>> map = yaml.load(inputStream);
//        String active = (String) map.get("spring").get("profiles").get("active");
//        String activeFileName = "application-" + active + ".yml";
//        InputStream inputStream1 = Thread.currentThread().getContextClassLoader()
//                .getResourceAsStream(activeFileName);
//        if (inputStream1 == null) {
//            System.out.println("未找到[" + activeFileName + "]配置文件");
//        }
//        Map<String, HashMap<String, Map<String, Object>>> activeMap = yaml.load(inputStream1);
//        Object datasource = activeMap.get("spring").get("datasource").get(dsName);
//        if (!(datasource instanceof Map)) {
//            System.out.println("未找到spring.datasource." + dsName + "配置");
//            return;
//        }
//        @SuppressWarnings({"unchecked"})
//        Map<String, String> dsMap = (Map<String, String>) datasource;
//        String dsUrl = dsMap.get("jdbc-url");
//        String dsDriverName = dsMap.get("driver-class-name");
//        String dsUserName = dsMap.get("username");
//        String dsPassword = dsMap.get("password");

        // 数据源配置 从prop文件中获取
        Properties properties = new Properties();
        InputStream inputStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(fileName);
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            System.out.println("Read File [" + fileName + "] error, please check it");
            System.exit(0);
            return;
        }
        String active = properties.getProperty("spring.profiles.active");
        if (active != null && !"".equals(active)) {
            String activeFileName = "application-" + active + ".properties";
            InputStream in = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(activeFileName);
            try {
                properties.load(in);
            } catch (IOException e) {
                System.out.println("Read File [" + activeFileName + "] error, please check it");
                System.exit(0);
                return;
            }
        }
        String dsUrl = properties.getProperty("spring.datasource.url");
        String dsDriverName = properties.getProperty("spring.datasource.driver-class-name");
        String dsUserName = properties.getProperty("spring.datasource.username");
        String dsPassword = <PASSWORD>("<PASSWORD>");
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(dsUrl);
        // dsc.setSchemaName("public");
        dsc.setDriverName(dsDriverName);
        dsc.setUsername(dsUserName);
        dsc.setPassword(<PASSWORD>);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        // pc.setModuleName(scanner("模块名"));
        pc.setParent("club.neters.user");
        pc.setService("app.service");
        pc.setServiceImpl("app.service.impl");
        pc.setEntity("domain.entity");
        pc.setMapper("infra.mapper." + dsName);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/" + dsName + "/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录，自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在，不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        templateConfig.setController(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setEntityTableFieldAnnotationEnable(true);
        // 公共父类
        // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        // strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        // strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}


<|start_filename|>ancba-blog/src/main/java/club/neters/blog/infra/mapper/primary/AdvertisementMapper.java<|end_filename|>
package club.neters.blog.infra.mapper.primary;

import club.neters.blog.domain.entity.Advertisement;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author laozhang
 * @since 2021-06-23
 */
public interface AdvertisementMapper extends BaseMapper<Advertisement> {

}
