Commit faec4b5b by 王衍超

增加司机端登录接口;

parent 88ebb063
......@@ -48,6 +48,7 @@ import com.beecode.bcp.web.context.AminoContextService;
import com.beecode.inz.authentication.filter.INZTenantAuthenticationFilter;
import com.beecode.inz.authentication.filter.InzConcurrentSessionFilter;
import com.beecode.inz.authentication.filter.InzWebAuthenticationFilter;
import com.beecode.inz.authentication.handler.DriverUserAuthenticationSuccessHandler;
import com.beecode.inz.authentication.handler.RESTAppAuthenticationSuccessHandler;
import com.beecode.inz.authentication.handler.RESTAuthenticationEntryPoint;
import com.beecode.inz.authentication.handler.RESTAuthenticationFailureHandler;
......@@ -55,9 +56,12 @@ import com.beecode.inz.authentication.handler.RESTAuthenticationSuccessHandler;
import com.beecode.inz.authentication.handler.RESTWarehouseUserAuthenticationSuccessHandler;
import com.beecode.inz.authentication.handler.SandUserAuthenticationSuccessHandler;
import com.beecode.inz.authentication.provider.AppUserAuthenticationProvider;
import com.beecode.inz.authentication.provider.DriverUserAuthProvider;
import com.beecode.inz.authentication.provider.SandUserAuthProvider;
import com.beecode.inz.authentication.provider.UserAuthenticationProvider;
import com.beecode.inz.authentication.provider.WarehouseUserAuthenticationProvider;
import com.beecode.inz.basis.context.driver.DriverUserContextPersistenceFilter;
import com.beecode.inz.basis.context.driver.DriverUserContextRepository;
import com.beecode.inz.basis.context.sand.SandUserContextPersistenceFilter;
import com.beecode.inz.basis.context.sand.SandUserContextRepository;
import com.beecode.inz.basis.context.warehouse.WarehouseUserContextPersistenceFilter;
......@@ -123,12 +127,18 @@ public class SecurityConfig {
//采砂用户
@Autowired
private SandUserAuthenticationSuccessHandler sandUserAuthenticationSuccessHandler;
@Autowired
private SandUserAuthProvider sandUserAuthProvider;
@Autowired
private SandUserContextRepository sandUserContextRepository;
//司机用户
@Autowired
private DriverUserAuthenticationSuccessHandler driverUserAuthenticationSuccessHandler;
@Autowired
private DriverUserAuthProvider driverUserAuthProvider;
@Autowired
private DriverUserContextRepository driverUserContextRepository;
@Autowired
private RestLogoutHandler CLogoutHandler;
......@@ -358,9 +368,89 @@ public class SecurityConfig {
return super.authenticationManager();
}
}
@Configuration
@Order(6)
public class DriverUserSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
List<SessionAuthenticationStrategy> delegateStrategies = new ArrayList<SessionAuthenticationStrategy>();
delegateStrategies.add(concurrentSessionControlAuthenticationStrategy);
http.sessionManagement().maximumSessions(1);
http.csrf().disable();
http.cors().disable();
http.antMatcher("/driver/user/login").authorizeRequests().anyRequest().authenticated();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
InzWebAuthenticationFilter filter = new InzWebAuthenticationFilter();
filter.setAuthenticationSuccessHandler(driverUserAuthenticationSuccessHandler);
filter.setAuthenticationFailureHandler(authenticationFailureHandler);
filter.setAuthenticationManager(authenticationManager());
filter.setSessionAuthenticationStrategy(new CompositeSessionAuthenticationStrategy(delegateStrategies));
RequestMatcher requestMatcher = new AntPathRequestMatcher("/driver/user/login", "POST");
filter.setRequiresAuthenticationRequestMatcher(requestMatcher);
http.addFilterAt(filter, UsernamePasswordAuthenticationFilter.class);
InzConcurrentSessionFilter inzConcurrentSessionFilter = new InzConcurrentSessionFilter(sessionRegistry) ;
http.addFilterAt(inzConcurrentSessionFilter, ConcurrentSessionFilter.class);
DriverUserContextPersistenceFilter contextPersistenceFilter = new DriverUserContextPersistenceFilter(metadataRuntime, driverUserContextRepository);
http.addFilterAfter(contextPersistenceFilter, SecurityContextPersistenceFilter.class);
http.addFilterAfter(new INZTenantAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(driverUserAuthProvider);
}
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
@Configuration
@Order(7)
public class DriverApiConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
List<SessionAuthenticationStrategy> delegateStrategies = new ArrayList<SessionAuthenticationStrategy>();
delegateStrategies.add(concurrentSessionControlAuthenticationStrategy);
http.sessionManagement().maximumSessions(1);
http.csrf().disable();
http.cors().disable();
http.antMatcher("/driver/user/**").authorizeRequests()
// .antMatchers("/sand/user").permitAll()
.anyRequest().authenticated();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
InzConcurrentSessionFilter inzConcurrentSessionFilter = new InzConcurrentSessionFilter(sessionRegistry) ;
http.addFilterAt(inzConcurrentSessionFilter, ConcurrentSessionFilter.class);
DriverUserContextPersistenceFilter contextPersistenceFilter = new DriverUserContextPersistenceFilter(metadataRuntime, driverUserContextRepository);
http.addFilterAfter(contextPersistenceFilter, SecurityContextPersistenceFilter.class);
http.addFilterAfter(new INZTenantAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
http.logout().logoutUrl("/driver/user/logout")
.addLogoutHandler(logoutHandler).invalidateHttpSession(true)
.permitAll();
}
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
@Configuration
@Order(8)
public class WebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
......
......@@ -15,6 +15,7 @@ import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import com.beecode.inz.authentication.handler.DriverUserAuthenticationSuccessHandler;
import com.beecode.inz.authentication.handler.RESTAppAuthenticationSuccessHandler;
import com.beecode.inz.authentication.handler.RESTAuthenticationEntryPoint;
import com.beecode.inz.authentication.handler.RESTAuthenticationFailureHandler;
......@@ -24,6 +25,7 @@ import com.beecode.inz.authentication.handler.SandUserAuthenticationSuccessHandl
import com.beecode.inz.authentication.internal.service.SMSsendingCustomerServiceImpl;
import com.beecode.inz.authentication.internal.service.SMSsendingServiceImpl;
import com.beecode.inz.authentication.provider.AppUserAuthenticationProvider;
import com.beecode.inz.authentication.provider.DriverUserAuthProvider;
import com.beecode.inz.authentication.provider.SandUserAuthProvider;
import com.beecode.inz.authentication.provider.WarehouseUserAuthenticationProvider;
import com.beecode.inz.authentication.service.SMSsendingCustomerService;
......@@ -132,5 +134,13 @@ public class AuthenticationConfiguration {
public SandUserAuthenticationSuccessHandler sandUserAuthenticationSuccessHandler() {
return new SandUserAuthenticationSuccessHandler();
}
@Bean
public DriverUserAuthProvider driveUserAuthProvider() {
return new DriverUserAuthProvider();
}
@Bean
public DriverUserAuthenticationSuccessHandler driveUserAuthenticationSuccessHandler() {
return new DriverUserAuthenticationSuccessHandler();
}
}
package com.beecode.inz.authentication.handler;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.beecode.inz.authentication.constants.AuthcConstants;
import com.beecode.inz.authentication.constants.LoginLogConstants;
import com.beecode.inz.authentication.constants.TenantUserConstants;
import com.beecode.inz.authentication.datamodel.LoginLog;
import com.beecode.inz.authentication.enumeration.LoginModeEnum;
import com.beecode.inz.authentication.enumeration.LoginStateEnum;
import com.beecode.inz.authentication.enumeration.LoginTerminalEnum;
import com.beecode.inz.authentication.service.LoginLogService;
import com.beecode.inz.authentication.util.LoginLogUtil;
import com.beecode.inz.basis.pojo.DriverUser;
/**
* 处理司机用户登录成功后的返回
*
* @author Jackpot
* @date 2021年5月19日
*/
@Component
public class DriverUserAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Autowired
private LoginLogService loginLogService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
clearAuthenticationAttributes(request);
LoginLog loginLog = getLoginLog(request);
try {
String tenant = request.getParameter(AuthcConstants.TENANT);
DriverUser driverUser = (DriverUser) authentication.getPrincipal();
if (driverUser != null) {
JSONObject returnJson = new JSONObject();
request.getSession().setAttribute(AuthcConstants.SESSION_TENANTID, tenant);
request.getSession().setAttribute(AuthcConstants.USERID, driverUser.getId());
request.getSession().setAttribute(AuthcConstants.USERNAME, driverUser.getUsername());
request.getSession().setAttribute(AuthcConstants.TELEPHONE, driverUser.getTelephone());
request.getSession().setAttribute(AuthcConstants.TITLE, driverUser.getTitle());
request.getSession().setAttribute("driverId", driverUser.getDriverId());
request.getSession().setAttribute("mobile", true);
request.getSession().setMaxInactiveInterval(30 * 24 * 60 * 60);
loginLog.setTenantId(tenant);
loginLog.setDescription("driverUser login");
loginLogService.insert(loginLog);
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
returnJson.put(AuthcConstants.USERID, driverUser.getId());
returnJson.put(AuthcConstants.USERNAME, driverUser.getUsername());
returnJson.put(AuthcConstants.TELEPHONE, driverUser.getTelephone());
returnJson.put(AuthcConstants.TITLE, driverUser.getTitle());
returnJson.put("driverId", driverUser.getDriverId());
returnJson.put(AuthcConstants.MESSAGE, "success");
returnJson.put(AuthcConstants.TOKEN, attr.getSessionId());
returnJson.put(AuthcConstants.TENANT, tenant);
response.setCharacterEncoding("UTF-8");
response.getWriter().append(returnJson.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public LoginLog getLoginLog(HttpServletRequest request) {
LoginLog loginLog = new LoginLog();
String userAgent = request.getHeader(LoginLogConstants.USER_AGENT);
if (userAgent.contains(LoginLogConstants.WINDOWS)) {
loginLog.setLoginTerminal(LoginTerminalEnum.WEB.getValue());
} else if (userAgent.contains(LoginLogConstants.ANDROID)) {
loginLog.setLoginTerminal(LoginTerminalEnum.ANDROID.getValue());
} else if (userAgent.contains(LoginLogConstants.IOS)) {
loginLog.setLoginTerminal(LoginTerminalEnum.ISO.getValue());
} else {
loginLog.setLoginTerminal(LoginTerminalEnum.WEB.getValue());
}
loginLog.setAccountNumber(request.getParameter(TenantUserConstants.USERNAME));
loginLog.setLoginMode(request.getParameter(TenantUserConstants.USERNAME) == null
? LoginModeEnum.QRCODELODIN.getValue() : LoginModeEnum.USERNAMEPASSWORD.getValue());
loginLog.setIp(LoginLogUtil.getClientIp(request));
loginLog.setLoginTime(new Date());
loginLog.setLoginState(LoginStateEnum.SUCCESS.getValue());
return loginLog;
}
}
package com.beecode.inz.authentication.provider;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.beecode.inz.basis.pojo.DriverUser;
import com.beecode.inz.basis.service.DriverUserService;
/**
* 司机用户验证器
*
* @author Jackpot
* @date 2021年3月19日
*/
public class DriverUserAuthProvider implements AuthenticationProvider {
@Autowired
DriverUserService driverUserService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String passWord = (String) authentication.getCredentials();
DriverUser driverUser = driverUserService.getByUsername(username);
if(null == driverUser) {
throw new BadCredentialsException("用户名或密码错误!");
}
String pwd = driverUser.getPassword();
if (!passwordEncoder.matches(passWord, pwd)) {
throw new BadCredentialsException("密码错误!");
}
List<SimpleGrantedAuthority> roleList = new ArrayList<SimpleGrantedAuthority>();
return new UsernamePasswordAuthenticationToken(driverUser, passWord, roleList);
}
@Override
public boolean supports(Class<?> authentication) {
return authentication != null && authentication == UsernamePasswordAuthenticationToken.class;
}
}
package com.beecode.inz.basis.config;
import com.beecode.inz.basis.dao.DriverUserDao;
import com.beecode.inz.basis.internal.dao.DriverUserDaoImpl;
import com.beecode.inz.basis.internal.service.DriverUserServiceImpl;
import com.beecode.inz.basis.service.DriverUserService;
import com.beecode.inz.basis.web.DriverUserController;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.beecode.inz.basis.context.driver.DriverUserContextRepository;
import com.beecode.inz.basis.context.sand.SandUserContextRepository;
import com.beecode.inz.basis.dao.CustomerDao;
import com.beecode.inz.basis.dao.DriverUserDao;
import com.beecode.inz.basis.dao.WarehouseUserDao;
import com.beecode.inz.basis.handler.SMSsnedHandlers;
import com.beecode.inz.basis.internal.dao.CustomerDaoImpl;
import com.beecode.inz.basis.internal.dao.DriverUserDaoImpl;
import com.beecode.inz.basis.internal.dao.SandUserDaoImpl;
import com.beecode.inz.basis.internal.dao.WarehouseUserDaoImpl;
import com.beecode.inz.basis.internal.service.CustomerServiceImpl;
import com.beecode.inz.basis.internal.service.DriverUserServiceImpl;
import com.beecode.inz.basis.internal.service.SandUserServiceImpl;
import com.beecode.inz.basis.internal.service.WarehouseUserServiceImpl;
import com.beecode.inz.basis.service.CustomerService;
import com.beecode.inz.basis.service.DriverUserService;
import com.beecode.inz.basis.service.SandUserService;
import com.beecode.inz.basis.service.WarehouseUserService;
import com.beecode.inz.basis.sms.internal.SMSsendingServiceImpl;
import com.beecode.inz.basis.sms.service.SMSsendingService;
import com.beecode.inz.basis.web.DriverUserController;
import com.beecode.inz.basis.web.SandUserController;
import com.beecode.inz.basis.web.WarehouseUserController;
......@@ -99,6 +100,10 @@ public class CommonConfig {
public SandUserContextRepository sandUserContextRepository() {
return new SandUserContextRepository();
}
@Bean
public DriverUserContextRepository driverUserContextRepository() {
return new DriverUserContextRepository();
}
//end
}
......@@ -15,5 +15,6 @@ public class DriverUserConstants extends CommonBaseConst{
public static final String TELEPHONE = "telephone";
public static final String ENABLED = "enabled";
public static final String TRANSPORT_COMPANY_ID = "transportCompanyId";
public static final String DRIVERID = "driverId";
}
package com.beecode.inz.basis.context.driver;
import java.io.Serializable;
import com.beecode.inz.basis.pojo.DriverUser;
/**
* 司机用户上下文
*
* @author Jackpot
* @date 2021年5月13日
*/
public interface DriverUserContext extends Serializable {
public DriverUser getDriverUser();
}
package com.beecode.inz.basis.context.driver;
public interface DriverUserContextConstants {
/**
* 当前用户
*/
public String CURRENT_USER = "currentDriverUser";
}
package com.beecode.inz.basis.context.driver;
import org.springframework.util.Assert;
public class DriverUserContextHolder {
private static final ThreadLocal<DriverUserContext> contextHolder = new ThreadLocal<DriverUserContext>();
/**
* Explicitly clears the context value from the current thread.
*/
public static void clearContext() {
contextHolder.remove();
}
/**
* Obtain the current <code>SecurityContext</code>.
*
* @return the security context (never <code>null</code>)
*/
public static DriverUserContext getContext() {
DriverUserContext ctx = contextHolder.get();
if (ctx == null) {
ctx = createEmptyContext();
contextHolder.set(ctx);
}
return ctx;
}
/**
* Associates a new <code>SecurityContext</code> with the current thread of
* execution.
*
* @param context
* the new <code>SecurityContext</code> (may not be
* <code>null</code>)
*/
public static void setContext(DriverUserContext context) {
Assert.notNull(context, "Only non-null AminoContext instances are permitted");
contextHolder.set(context);
}
/**
* Delegates the creation of a new, empty context to the configured
* strategy.
*/
public static DriverUserContext createEmptyContext() {
return new DriverUserContextImpl();
}
}
package com.beecode.inz.basis.context.driver;
import com.beecode.inz.basis.pojo.DriverUser;
public class DriverUserContextImpl implements DriverUserContext {
private static final long serialVersionUID = 7659762847744346459L;
private DriverUser driverUser;
@Override
public DriverUser getDriverUser() {
return driverUser;
}
public void setDriverUser(DriverUser driverUser) {
this.driverUser = driverUser;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((driverUser == null) ? 0 : driverUser.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
DriverUserContextImpl other = (DriverUserContextImpl) obj;
if (driverUser == null) {
if (other.driverUser != null) {
return false;
}
} else if (!driverUser.equals(other.driverUser)) {
return false;
}
return true;
}
@Override
public String toString() {
return "driverUserContextImpl [driverUser=" + driverUser + "]";
}
}
package com.beecode.inz.basis.context.driver;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.web.filter.GenericFilterBean;
import com.beecode.amino.metadata.runtime.MetadataRuntime;
public class DriverUserContextPersistenceFilter extends GenericFilterBean {
static final String FILTER_APPLIED = "__driver_user_acpf_applied";
private final MetadataRuntime metadataRuntime;
private final DriverUserContextRepository repo;
private boolean forceEagerSessionCreation = false;
public DriverUserContextPersistenceFilter(MetadataRuntime metadataRuntime) {
this(metadataRuntime, new DriverUserContextRepository());
}
public DriverUserContextPersistenceFilter(MetadataRuntime metadataRuntime, DriverUserContextRepository repo) {
this.metadataRuntime = metadataRuntime;
this.repo = repo;
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (request.getAttribute(FILTER_APPLIED) != null) {
// ensure that filter is only applied once per request
chain.doFilter(request, response);
return;
}
if (!metadataRuntime.isActive()) {
// TODO 元数据服务还没有启动好
return;
}
final boolean debug = logger.isDebugEnabled();
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
if (forceEagerSessionCreation) {
HttpSession session = request.getSession();
if (debug && session.isNew()) {
logger.debug("Eagerly created session: " + session.getId());
}
}
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
try {
DriverUserContext contextBeforeChainExecution = repo.loadContext(holder);
DriverUserContextHolder.setContext(contextBeforeChainExecution);
chain.doFilter(holder.getRequest(), holder.getResponse());
}
finally {
// Crucial removal of SecurityContextHolder contents - do this before anything
// else.
DriverUserContextHolder.clearContext();
request.removeAttribute(FILTER_APPLIED);
if (debug) {
logger.debug("DriverUserContextHolder now cleared, as request processing completed");
}
}
}
public void setForceEagerSessionCreation(boolean forceEagerSessionCreation) {
this.forceEagerSessionCreation = forceEagerSessionCreation;
}
}
package com.beecode.inz.basis.context.driver;
import javax.servlet.AsyncContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.util.OnCommittedResponseWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import com.beecode.inz.basis.pojo.DriverUser;
import com.beecode.inz.basis.service.DriverUserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DriverUserContextRepository {
@Autowired
private DriverUserService driverUserService;
@Autowired
private ObjectMapper objectMapper;
public static final String Driver_USER_CONTEXT_KEY = "DRIVER_USER_CONTEXT";
protected final Log logger = LogFactory.getLog(this.getClass());
private final Object contextObject = DriverUserContextHolder.createEmptyContext();
private boolean isServlet3 = ClassUtils.hasMethod(ServletRequest.class, "startAsync");
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
@Transactional(readOnly=true)
public DriverUserContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
HttpServletRequest request = requestResponseHolder.getRequest();
HttpServletResponse response = requestResponseHolder.getResponse();
HttpSession httpSession = request.getSession(false);
DriverUserContext context = generateNewContext(httpSession);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !trustResolver.isAnonymous(authentication)) {
DriverUserContextImpl contextImpl = (DriverUserContextImpl)context;
if(contextImpl.getDriverUser() == null) {
loadContext(httpSession, contextImpl);
}
}
SaveToSessionResponseWrapper wrappedResponse = new SaveToSessionResponseWrapper(response, request, httpSession != null, context);
requestResponseHolder.setResponse(wrappedResponse);
if (isServlet3) {
requestResponseHolder.setRequest(new Servlet3SaveToSessionRequestWrapper(request, wrappedResponse));
}
return context;
}
public boolean containsContext(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return false;
}
return session.getAttribute(Driver_USER_CONTEXT_KEY) != null;
}
protected DriverUserContext generateNewContext(HttpSession httpSession) {
return DriverUserContextHolder.createEmptyContext();
}
/**
* 获取当前用户context
* @throws Exception
*/
private void loadContext(HttpSession httpSession, DriverUserContextImpl contextImpl) {
if (null == httpSession) {
return;
}
DriverUser DriverUser = null;
String DriverUserJsonObj = (String)httpSession.getAttribute(DriverUserContextConstants.CURRENT_USER);
if (StringUtils.isEmpty(DriverUserJsonObj)) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(null == authentication) {
return;
}
String userName = authentication.getName();
if(StringUtils.isEmpty(userName)) {
return;
}
DriverUser = driverUserService.getByUsername(userName);
if(null == DriverUser) {
throw new RuntimeException("not found DriverUser#" + userName);
}
httpSession.setAttribute(DriverUserContextConstants.CURRENT_USER, objectMapper.writeValueAsString(DriverUser));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
} else if (DriverUserJsonObj instanceof String) {
try {
DriverUser = objectMapper.readValue(DriverUserJsonObj, DriverUser.class);
}catch(Exception e) {
e.printStackTrace();
httpSession.removeAttribute(DriverUserContextConstants.CURRENT_USER);
}
}
contextImpl.setDriverUser(DriverUser);
}
//~ Inner Classes ==================================================================================================
private static class Servlet3SaveToSessionRequestWrapper extends HttpServletRequestWrapper {
private final SaveToSessionResponseWrapper response;
public Servlet3SaveToSessionRequestWrapper(HttpServletRequest request, SaveToSessionResponseWrapper response) {
super(request);
this.response = response;
}
@Override
public AsyncContext startAsync() {
response.disableSaveOnResponseCommitted();
return super.startAsync();
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
throws IllegalStateException {
response.disableSaveOnResponseCommitted();
return super.startAsync(servletRequest, servletResponse);
}
}
final class SaveToSessionResponseWrapper extends OnCommittedResponseWrapper {
private final HttpServletRequest request;
private final boolean httpSessionExistedAtStartOfRequest;
public SaveToSessionResponseWrapper(HttpServletResponse response, HttpServletRequest request,
boolean httpSessionExistedAtStartOfRequest, DriverUserContext context) {
super(response);
this.request = request;
this.httpSessionExistedAtStartOfRequest = httpSessionExistedAtStartOfRequest;
// this.contextBeforeExecution = context;
// this.authBeforeExecution = context.getAuthentication();
}
public void disableSaveOnResponseCommitted() {
disableOnResponseCommitted();
}
protected void saveContext(DriverUserContext context) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
HttpSession httpSession = request.getSession(false);
// See SEC-776
if (authentication == null || trustResolver.isAnonymous(authentication)) {
if (logger.isDebugEnabled()) {
logger.debug(
"DriverUserContext is empty or contents are anonymous - context will not be stored in HttpSession.");
}
if (httpSession != null) {
// SEC-1587 A non-anonymous context may still be in the
// session
// SEC-1735 remove if the contextBeforeExecution was not
// anonymous
httpSession.removeAttribute(Driver_USER_CONTEXT_KEY);
}
return;
}
if (httpSession == null) {
httpSession = createNewSessionIfAllowed(context);
}
// If HttpSession exists, store current CustomerContext but only if
// it has
// actually changed in this thread (see SEC-37, SEC-1307, SEC-1528)
if (httpSession != null) {
// We may have a new session, so check also whether the context
// attribute
// is set SEC-1561
if (contextChanged(context) || httpSession.getAttribute(Driver_USER_CONTEXT_KEY) == null) {
// httpSession.setAttribute(customerContextKey, context);
if (logger.isDebugEnabled()) {
logger.debug("DriverUserContext '" + context + "' stored to HttpSession: '" + httpSession);
}
}
}
}
private boolean contextChanged(DriverUserContext context) {
return true;
}
private HttpSession createNewSessionIfAllowed(DriverUserContext context) {
if (httpSessionExistedAtStartOfRequest) {
return null;
}
// Generate a HttpSession only if we need to
if (contextObject.equals(context)) {
return null;
}
try {
return request.getSession(true);
} catch (IllegalStateException e) {
logger.warn("Failed to create a session, as response has been committed. Unable to store"
+ " DriverUserContext.");
}
return null;
}
@Override
protected void onResponseCommitted() {
saveContext(DriverUserContextHolder.getContext());
}
@Override
public final String encodeRedirectUrl(String url) {
return super.encodeURL(url);
}
}
}
......@@ -64,6 +64,7 @@ public class DriverUser implements UserDetails, Serializable {
*/
private String type;
private String driverId;
/**
* 手机号
*/
......@@ -148,6 +149,7 @@ public class DriverUser implements UserDetails, Serializable {
model.setTelephone(object.getString(DriverUserConstants.TELEPHONE));
model.setTransportCompanyId(object.getUuid(DriverUserConstants.TRANSPORT_COMPANY_ID));
model.setOrg(object.getString(DriverUserConstants.ORG));
model.setDriverId(object.getString(DriverUserConstants.DRIVERID));
model.setPath(object.getString(DriverUserConstants.PATH));
model.setRole(object.getString(DriverUserConstants.ROLE));
model.setDescription(object.getString(DriverUserConstants.DESCRIPTION));
......@@ -171,6 +173,15 @@ public class DriverUser implements UserDetails, Serializable {
return new ArrayList<SimpleGrantedAuthority>();
}
public String getDriverId() {
return driverId;
}
public void setDriverId(String driverId) {
this.driverId = driverId;
}
@Override
public boolean isAccountNonExpired() {
return true;
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-sequence">
<specification>1.0</specification>
<id>daff6a8c-1584-4c1f-ba4c-ca331a6b7dea</id>
<id>5480f69f-b378-463b-a927-c6ee6e8d0253</id>
<name>com.xyst.dinas.biz.bill.Position$sequence</name>
<title>岗位$sequence</title>
<description>岗位</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-serial">
<specification>1.0</specification>
<id>85251f6a-2d78-4684-b4fe-dc15cbfc21c8</id>
<id>40bd96cc-f14d-4a16-a9a5-5474d5a9ecd4</id>
<name>com.xyst.dinas.biz.bill.Position$serial</name>
<title>岗位$serial</title>
<description>岗位</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-biztype">
<specification>1.0</specification>
<id>51571ca3-6605-47d0-b28c-f148f837772f</id>
<id>0194b543-8936-47cf-850f-47c3c53c6e2f</id>
<name>com.xyst.dinas.biz.bill.Position</name>
<title>岗位</title>
<description>岗位</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-sequence">
<specification>1.0</specification>
<id>d8458038-b4c3-4fbc-86f8-fd383a4262af</id>
<id>e9f0906a-dfa0-4986-8082-4ee9edf46054</id>
<name>com.xyst.dinas.biz.bill.ShipInfo$sequence</name>
<title>船舶备案$sequence</title>
<description>船舶备案</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-serial">
<specification>1.0</specification>
<id>ae10cbfd-4e61-470a-81a4-c6d09c4795df</id>
<id>b255f17f-0372-45d2-8b19-0bd0989b54db</id>
<name>com.xyst.dinas.biz.bill.ShipInfo$serial</name>
<title>船舶备案$serial</title>
<description>船舶备案</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-biztype">
<specification>1.0</specification>
<id>509d896a-4336-46d5-b80e-116fa264a758</id>
<id>605dd203-3cfe-45d5-92de-73dbb6ebf0a3</id>
<name>com.xyst.dinas.biz.bill.ShipInfo</name>
<title>船舶备案</title>
<description>船舶备案</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-sequence">
<specification>1.0</specification>
<id>5f1a8c2f-1f67-42b0-a0e3-9d2543aa9160</id>
<id>0b5be47e-803b-49d7-8666-ceb6e905fb33</id>
<name>com.xyst.dinas.biz.bill.Station$sequence</name>
<title>场站$sequence</title>
<description>场站</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-serial">
<specification>1.0</specification>
<id>fb94c50e-3873-4c47-8ead-095ecc43122e</id>
<id>f1d6db39-6809-4fa0-b1aa-4eb1807bd928</id>
<name>com.xyst.dinas.biz.bill.Station$serial</name>
<title>场站$serial</title>
<description>场站</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-biztype">
<specification>1.0</specification>
<id>a9180feb-7abc-490b-ba10-cbc2f9702030</id>
<id>74a1e4d4-ef7f-46fc-8d5e-8eff7376fbad</id>
<name>com.xyst.dinas.biz.bill.Station</name>
<title>场站</title>
<description>场站</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-sequence">
<specification>1.0</specification>
<id>a5caf16c-a322-48aa-be5e-b75ac36b6017</id>
<id>9d678757-d229-46e6-9671-283364d5b026</id>
<name>com.xyst.dinas.biz.bill.xystOrganization$sequence</name>
<title>组织机构$sequence</title>
<description>组织机构</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-serial">
<specification>1.0</specification>
<id>eb04db62-e177-4c2a-8eb7-4e4998b68c0b</id>
<id>b28bb89a-60f9-435a-bfe8-1472f6324e53</id>
<name>com.xyst.dinas.biz.bill.xystOrganization$serial</name>
<title>组织机构$serial</title>
<description>组织机构</description>
......
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.beecode.cn/schema/amino-metadata" xmlns:m="http://www.beecode.cn/schema/bcp-biztype">
<specification>1.0</specification>
<id>4464799f-8863-41e4-b6ed-a16dee53506c</id>
<id>10309e1d-844b-4ef8-b547-2c944be172c7</id>
<name>com.xyst.dinas.biz.bill.xystOrganization</name>
<title>组织机构</title>
<description>组织机构</description>
......
......@@ -132,13 +132,13 @@
</m:properties>
</m:annotation>
</m:annotations>
<m:id>0933ceb1-f327-4372-a316-cffa1c80991a</m:id>
<m:id>cbb5b983-299b-4259-97d9-6470651bb18b</m:id>
<m:name>warnState</m:name>
<m:title>预警状态</m:title>
<m:type>int</m:type>
<m:description></m:description>
<m:default></m:default>
</m:attribute>
</m:attribute>
<m:attribute>
<m:annotations>
<m:annotation>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment