提交 24c142ab 编写于 作者: ibizdev's avatar ibizdev

ibizdev提交

上级 a2e3b81c
......@@ -13,6 +13,7 @@
<id property="dictid" column="ibzdictid" /><!--主键字段映射-->
<result property="dictname" column="ibzdictname" />
</resultMap>
......
......@@ -15,6 +15,7 @@
<result property="itemval" column="dictitemval" />
<result property="dictid" column="dictid" />
<!--通过mybatis自动注入关系属性[主实体],fetchType="lazy"为懒加载配置 -->
<association property="dict" javaType="cn.ibizlab.core.dict.domain.IBZDict" column="dictid" select="cn.ibizlab.core.dict.mapper.IBZDictMapper.selectById" fetchType="lazy"></association>
</resultMap>
......
......@@ -49,5 +49,10 @@
<artifactId>jjwt</artifactId>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>problem-spring-web</artifactId>
</dependency>
</dependencies>
</project>
package cn.ibizlab.util.errors;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class BadRequestAlertException extends AbstractThrowableProblem {
private final String entityName;
private final String errorKey;
public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) {
this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey);
}
public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) {
super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey));
this.entityName = entityName;
this.errorKey = errorKey;
}
public String getEntityName() {
return entityName;
}
public String getErrorKey() {
return errorKey;
}
private static Map<String, Object> getAlertParameters(String entityName, String errorKey) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("message", "error." + errorKey);
parameters.put("params", entityName);
return parameters;
}
}
package cn.ibizlab.util.errors;
import org.zalando.problem.AbstractThrowableProblem;
import java.util.HashMap;
import java.util.Map;
import static org.zalando.problem.Status.BAD_REQUEST;
public class CustomParameterizedException extends AbstractThrowableProblem {
private static final long serialVersionUID = 1L;
private static final String PARAM = "param";
public CustomParameterizedException(String message, String... params) {
this(message, toParamMap(params));
}
public CustomParameterizedException(String message, Map<String, Object> paramMap) {
super(ErrorConstants.PARAMETERIZED_TYPE, "处理发生异常", BAD_REQUEST, null, null, null, toProblemParameters(message, paramMap));
}
public static Map<String, Object> toParamMap(String... params) {
Map<String, Object> paramMap = new HashMap<>();
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i++) {
paramMap.put(PARAM + i, params[i]);
}
}
return paramMap;
}
public static Map<String, Object> toProblemParameters(String message, Map<String, Object> paramMap) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("message", message);
parameters.put("params", paramMap);
return parameters;
}
}
package cn.ibizlab.util.errors;
import java.net.URI;
public final class ErrorConstants {
public static final String ERR_CONCURRENCY_FAILURE = "处理请求发生错误";
public static final String ERR_VALIDATION = "数据校验发生错误";
public static final String PROBLEM_BASE_URL = "";
public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message");
public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation");
public static final URI PARAMETERIZED_TYPE = URI.create(PROBLEM_BASE_URL + "/parameterized");
private ErrorConstants() {
}
}
package cn.ibizlab.util.errors;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.zalando.problem.DefaultProblem;
import org.zalando.problem.Problem;
import org.zalando.problem.ProblemBuilder;
import org.zalando.problem.Status;
import org.zalando.problem.spring.web.advice.ProblemHandling;
import org.zalando.problem.spring.web.advice.validation.ConstraintViolationProblem;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
@ControllerAdvice
public class ExceptionTranslator implements ProblemHandling {
@Override
public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) {
if (entity == null || entity.getBody() == null) {
return entity;
}
Problem problem = entity.getBody();
if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) {
return entity;
}
ProblemBuilder builder = Problem.builder()
.withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType())
.withStatus(problem.getStatus())
.withTitle(problem.getTitle())
.with("path", request.getNativeRequest(HttpServletRequest.class).getRequestURI());
if (problem instanceof ConstraintViolationProblem) {
builder
.with("violations", ((ConstraintViolationProblem) problem).getViolations())
.with("message", ErrorConstants.ERR_VALIDATION);
return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
} else {
builder
.withCause(((DefaultProblem) problem).getCause())
.withDetail(problem.getDetail())
.withInstance(problem.getInstance());
problem.getParameters().forEach(builder::with);
if (!problem.getParameters().containsKey("message") && problem.getStatus() != null) {
builder.with("message", "error.http." + problem.getStatus().getStatusCode());
}
return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
}
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getDefaultMessage()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle(ErrorConstants.ERR_VALIDATION)
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION )
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@ExceptionHandler(BadRequestAlertException.class)
public ResponseEntity<Problem> handleBadRequestAlertException(BadRequestAlertException ex, NativeWebRequest request) {
return create(ex, request, createFailureAlert(ex.getEntityName(), ex.getErrorKey(), ex.getMessage()));
}
@ExceptionHandler(ConcurrencyFailureException.class)
public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) {
Problem problem = Problem.builder()
.withStatus(Status.CONFLICT)
.with("message", ErrorConstants.ERR_CONCURRENCY_FAILURE)
.build();
return create(ex, problem, request);
}
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-ibz-error", "error." + errorKey);
headers.add("X-ibz-params", entityName);
return headers;
}
}
package cn.ibizlab.util.errors;
import java.io.Serializable;
public class FieldErrorVM implements Serializable {
private static final long serialVersionUID = 1L;
private final String objectName;
private final String field;
private final String message;
public FieldErrorVM(String dto, String field, String message) {
this.objectName = dto;
this.field = field;
this.message = message;
}
public String getObjectName() {
return objectName;
}
public String getField() {
return field;
}
public String getMessage() {
return message;
}
}
package cn.ibizlab.util.errors;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
public class InternalServerErrorException extends AbstractThrowableProblem {
public InternalServerErrorException(String message) {
super(ErrorConstants.DEFAULT_TYPE, message, Status.INTERNAL_SERVER_ERROR);
}
}
......@@ -5,15 +5,13 @@ import cn.ibizlab.util.security.AuthenticationInfo;
import cn.ibizlab.util.security.AuthenticationUser;
import cn.ibizlab.util.security.AuthorizationLogin;
import cn.ibizlab.util.security.AuthTokenUtil;
import cn.ibizlab.util.service.IBZUSERService;
import cn.ibizlab.util.service.AuthenticationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
......@@ -21,8 +19,6 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/")
public class AuthenticationController
{
@Value("${ibiz.auth.pwencry:false}")
private boolean pwencry;
@Value("${ibiz.jwt.header:Authorization}")
private String tokenHeader;
......@@ -31,16 +27,12 @@ public class AuthenticationController
private AuthTokenUtil jwtTokenUtil;
@Autowired
@Qualifier("AuthenticationUserService")
private UserDetailsService userDetailsService;
@Autowired
private IBZUSERService userService;
private AuthenticationUserService userDetailsService;
@PostMapping(value = "${ibiz.auth.path:v7/login}")
public ResponseEntity<AuthenticationInfo> login(@Validated @RequestBody AuthorizationLogin authorizationLogin){
userService.resetByUsername(authorizationLogin.getUsername());
final AuthenticationUser authuserdetail = (AuthenticationUser) userDetailsService.loadUserByUsername(authorizationLogin.getUsername());
userDetailsService.resetByUsername(authorizationLogin.getUsername());
final AuthenticationUser authuserdetail = userDetailsService.loadUserByLogin(authorizationLogin.getDomain(),authorizationLogin.getLoginname(),authorizationLogin.getPassword());
// 生成令牌
final String token = jwtTokenUtil.generateToken(authuserdetail);
// 返回 token
......@@ -58,7 +50,7 @@ public class AuthenticationController
authuserdetail= (AuthenticationUser)userDetails;
}
else {
authuserdetail= (AuthenticationUser)userDetailsService.loadUserByUsername(userDetails.getUsername());
authuserdetail= userDetailsService.loadUserByUsername(userDetails.getUsername());
}
return ResponseEntity.ok().body(authuserdetail);
}
......
......@@ -26,7 +26,7 @@ public class AuthorizationTokenFilter extends OncePerRequestFilter {
private final AuthTokenUtil authTokenUtil;
private final String tokenHeader;
public AuthorizationTokenFilter(@Qualifier("AuthenticationUserService") UserDetailsService userDetailsService, AuthTokenUtil authTokenUtil, @Value("${ibiz.jwt.header:Authorization}") String tokenHeader) {
public AuthorizationTokenFilter(AuthenticationUserService UserDetailsService userDetailsService, AuthTokenUtil authTokenUtil, @Value("${ibiz.jwt.header:Authorization}") String tokenHeader) {
this.userDetailsService = userDetailsService;
this.authTokenUtil = authTokenUtil;
this.tokenHeader = tokenHeader;
......
package cn.ibizlab.util.service;
import javax.annotation.Resource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.util.security.AuthenticationUser;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import cn.ibizlab.util.mapper.IBZUSERMapper;
import cn.ibizlab.util.domain.IBZUSER;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.IService;
/**
......@@ -19,11 +8,4 @@ import com.baomidou.mybatisplus.extension.service.IService;
*/
public interface IBZUSERService extends IService<IBZUSER> {
@Cacheable( value="ibzdict_users",key = "'getByUsername:'+#p0")
AuthenticationUser getByUsername(String username);
@CacheEvict( value="ibzdict_users",key = "'getByUsername:'+#p0")
void resetByUsername(String username);
AuthenticationUser createUserDetails(IBZUSER user);
}
\ No newline at end of file
}
\ No newline at end of file
package cn.ibizlab.util.service;
import javax.annotation.Resource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.util.security.AuthenticationUser;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cglib.beans.BeanCopier;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.helper.CachedBeanCopier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import cn.ibizlab.util.mapper.IBZUSERMapper;
import cn.ibizlab.util.domain.IBZUSER;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
/**
* 实体[IBZUSER] 服务对象接口实现
*/
@Service
public class IBZUSERServiceImpl extends ServiceImpl<IBZUSERMapper, IBZUSER> implements IBZUSERService{
@Service("IBZUSERService")
public class IBZUSERServiceImpl extends ServiceImpl<IBZUSERMapper, IBZUSER> implements IBZUSERService,AuthenticationUserService{
@Resource
private IBZUSERMapper ibzuserMapper;
public AuthenticationUser getByUsername(String username){
@Value("${ibiz.auth.pwencrymode:0}")
private int pwencrymode;
@Override
public AuthenticationUser loadUserByUsername(String username) {
if(StringUtils.isEmpty(username))
throw new UsernameNotFoundException("用户名为空");
QueryWrapper<IBZUSER> conds=new QueryWrapper<IBZUSER>();
......@@ -40,25 +40,42 @@ public class IBZUSERServiceImpl extends ServiceImpl<IBZUSERMapper, IBZUSER> impl
if(!StringUtils.isEmpty(domains))
conds.eq("domains",domains);
IBZUSER user = this.getOne(conds);
if (user == null)
{
if (user == null) {
throw new UsernameNotFoundException("用户" + username + "未找到");
}
else
{
else {
user.setUsername(username);
return createUserDetails(user);
}
}
public void resetByUsername(String username)
{
@Override
public AuthenticationUser loadUserByLogin(String username, String password){
AuthenticationUser authuserdetail = loadUserByUsername(username);
if(pwencrymode==1)
password = DigestUtils.md5DigestAsHex(password.getBytes());
else if(pwencrymode==2)
password = DigestUtils.md5DigestAsHex(String.format("%1$s||%2$s", username, password).getBytes());
if(!authuserdetail.getPassword().equals( password )){
throw new BadRequestAlertException("用户名密码错误","IBZUSER",username);
}
return authuserdetail;
}
@Override
public AuthenticationUser loadUserByLogin(String domain, String username, String password) {
if(!StringUtils.isEmpty(domain))
username = username+"|"+domain;
return loadUserByLogin(username,password);
}
public void resetByUsername(String username) {
}
public AuthenticationUser createUserDetails(IBZUSER user) {
AuthenticationUser userdatail = new AuthenticationUser();
BeanCopier copier=BeanCopier.create(IBZUSER.class,AuthenticationUser.class,false);
copier.copy(user,userdatail,null);
CachedBeanCopier.copy(user,userdatail);
return userdatail;
}
}
\ No newline at end of file
}
\ No newline at end of file
package cn.ibizlab.util.service;
import cn.ibizlab.util.security.AuthenticationUser;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
/**
* 实体[IBZUSER] 服务对象接口实现
*/
@Service
public class SimpleUserService {
@Primary
@Service("SimpleUserService")
public class SimpleUserService implements AuthenticationUserService{
public AuthenticationUser getByUsername(String username) {
@Override
public AuthenticationUser loadUserByUsername(String username) {
AuthenticationUser user = new AuthenticationUser();
String[] data=username.split("[|]");
String loginname=username;
String domains="";
String password="";
if(data.length==3) {
loginname=data[0].trim();
domains=data[1].trim();
password=data[2].trim();
}
else if(data.length==2) {
loginname=data[0].trim();
password=data[1].trim();
}
user.setUserid(DigestUtils.md5DigestAsHex(username.getBytes()));
user.setUsercode(loginname);
user.setUsername(username);
user.setLoginname(loginname);
user.setPersonname(loginname);
user.setDomain(domains);
user.setPassword(password);
user.setOrgid(domains);
user.setOrgcode(domains);
user.setOrgname(domains);
return user;
}
@Override
public AuthenticationUser loadUserByLogin(String username, String password) {
password = DigestUtils.md5DigestAsHex(String.format("%1$s||%2$s", username, password).getBytes());
AuthenticationUser authuserdetail = loadUserByUsername(username+"|"+password);
return authuserdetail;
}
@Override
public AuthenticationUser loadUserByLogin(String domain, String username, String password) {
if(!StringUtils.isEmpty(domain))
username = username+"|"+domain;
return loadUserByLogin(username,password);
}
@Override
public void resetByUsername(String username) {
}
}
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册