Commit 64d4f18d authored by bing zhang's avatar bing zhang
Browse files

1

parent 539344b2
package com.mindskip.xzs.configuration.property;
import java.time.Duration;
import java.util.List;
/**
* @version 3.5.0
* @description: The type Wx config.
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
public class WxConfig {
private String appid;
private String secret;
private Duration tokenToLive;
private List<String> securityIgnoreUrls;
/**
* Gets appid.
*
* @return the appid
*/
public String getAppid() {
return appid;
}
/**
* Sets appid.
*
* @param appid the appid
*/
public void setAppid(String appid) {
this.appid = appid;
}
/**
* Gets secret.
*
* @return the secret
*/
public String getSecret() {
return secret;
}
/**
* Sets secret.
*
* @param secret the secret
*/
public void setSecret(String secret) {
this.secret = secret;
}
/**
* Gets token to live.
*
* @return the token to live
*/
public Duration getTokenToLive() {
return tokenToLive;
}
/**
* Sets token to live.
*
* @param tokenToLive the token to live
*/
public void setTokenToLive(Duration tokenToLive) {
this.tokenToLive = tokenToLive;
}
/**
* Gets security ignore urls.
*
* @return the security ignore urls
*/
public List<String> getSecurityIgnoreUrls() {
return securityIgnoreUrls;
}
/**
* Sets security ignore urls.
*
* @param securityIgnoreUrls the security ignore urls
*/
public void setSecurityIgnoreUrls(List<String> securityIgnoreUrls) {
this.securityIgnoreUrls = securityIgnoreUrls;
}
}
package com.mindskip.xzs.configuration.spring.exception;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.base.SystemCode;
import com.mindskip.xzs.utility.ErrorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
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.stream.Collectors;
/**
* @version 3.5.0
* @description: The type Exception handle.
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@ControllerAdvice
public class ExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
/**
* Handler rest response.
*
* @param e the e
* @return the rest response
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public RestResponse handler(Exception e) {
logger.error(e.getMessage(), e);
return new RestResponse<>(SystemCode.InnerError.getCode(), SystemCode.InnerError.getMessage());
}
/**
* Handler rest response.
*
* @param e the e
* @return the rest response
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public RestResponse handler(MethodArgumentNotValidException e) {
String errorMsg = e.getBindingResult().getAllErrors().stream().map(file -> {
FieldError fieldError = (FieldError) file;
return ErrorUtil.parameterErrorFormat(fieldError.getField(), fieldError.getDefaultMessage());
}).collect(Collectors.joining());
return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
}
/**
* Handler rest response.
*
* @param e the e
* @return the rest response
*/
@ExceptionHandler(BindException.class)
@ResponseBody
public RestResponse handler(BindException e) {
String errorMsg = e.getBindingResult().getAllErrors().stream().map(file -> {
FieldError fieldError = (FieldError) file;
return ErrorUtil.parameterErrorFormat(fieldError.getField(), fieldError.getDefaultMessage());
}).collect(Collectors.joining());
return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
}
}
package com.mindskip.xzs.configuration.spring.mvc;
import com.mindskip.xzs.configuration.property.SystemConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import java.util.List;
/**
* @version 3.5.0
* @description: The type Web mvc configuration.
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
private final SystemConfig systemConfig;
/**
* Instantiates a new Web mvc configuration.
*
* @param systemConfig the system config
*/
@Autowired
public WebMvcConfiguration(SystemConfig systemConfig) {
this.systemConfig = systemConfig;
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "/student/index.html");
registry.addRedirectViewController("/student", "/student/index.html");
registry.addRedirectViewController("/admin", "/admin/index.html");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod(31556926);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> securityIgnoreUrls = systemConfig.getWx().getSecurityIgnoreUrls();
String[] ignores = new String[securityIgnoreUrls.size()];
super.addInterceptors(registry);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedMethods("*")
.allowedOrigins("*")
.allowedHeaders("*");
super.addCorsMappings(registry);
}
}
package com.mindskip.xzs.configuration.spring.security;
/**
* @version 3.5.0
* @description: The type Authentication bean.
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
public class AuthenticationBean {
private String userName;
private String password;
private boolean remember;
/**
* Gets user name.
*
* @return the user name
*/
public String getUserName() {
return userName;
}
/**
* Sets user name.
*
* @param userName the user name
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* Gets password.
*
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Sets password.
*
* @param password the password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Is remember boolean.
*
* @return the boolean
*/
public boolean isRemember() {
return remember;
}
/**
* Sets remember.
*
* @param remember the remember
*/
public void setRemember(boolean remember) {
this.remember = remember;
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.base.SystemCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @version 3.5.0
* @description: 未登录
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@Component
public final class LoginAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
/**
* Instantiates a new Login authentication entry point.
*/
public LoginAuthenticationEntryPoint() {
super("/api/user/login");
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
RestUtil.response(response, SystemCode.UNAUTHORIZED);
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.base.SystemCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @version 3.5.0
* @description: 没权限
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@Component
public class RestAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
RestUtil.response(httpServletResponse, SystemCode.AccessDenied);
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.base.SystemCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @version 3.5.0
* @description: 账号验证异常
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@Component
public class RestAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
RestUtil.response(response, SystemCode.AuthError.getCode(), exception.getMessage());
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.context.WebContext;
import com.mindskip.xzs.domain.enums.RoleEnum;
import com.mindskip.xzs.domain.enums.UserStatusEnum;
import com.mindskip.xzs.service.AuthenticationService;
import com.mindskip.xzs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
/**
* @version 3.5.0
* @description: 登录用户名密码验证
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@Component
public class RestAuthenticationProvider implements AuthenticationProvider {
private final AuthenticationService authenticationService;
private final UserService userService;
private final WebContext webContext;
/**
* Instantiates a new Rest authentication provider.
*
* @param authenticationService the authentication service
* @param userService the user service
* @param webContext the web context
*/
@Autowired
public RestAuthenticationProvider(AuthenticationService authenticationService, UserService userService, WebContext webContext) {
this.authenticationService = authenticationService;
this.userService = userService;
this.webContext = webContext;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
com.mindskip.xzs.domain.User user = userService.getUserByUserName(username);
if (user == null) {
throw new UsernameNotFoundException("用户名或密码错误");
}
boolean result = authenticationService.authUser(user, username, password);
if (!result) {
throw new BadCredentialsException("用户名或密码错误");
}
UserStatusEnum userStatusEnum = UserStatusEnum.fromCode(user.getStatus());
if (UserStatusEnum.Disable == userStatusEnum) {
throw new LockedException("用户被禁用");
}
ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.add(new SimpleGrantedAuthority(RoleEnum.fromCode(user.getRole()).getRoleName()));
User authUser = new User(user.getUserName(), user.getPassword(), grantedAuthorities);
return new UsernamePasswordAuthenticationToken(authUser, authUser.getPassword(), authUser.getAuthorities());
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.base.SystemCode;
import com.mindskip.xzs.domain.UserEventLog;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
/**
* @version 3.5.0
* @description: 登录成功返回
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@Component
public class RestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private final ApplicationEventPublisher eventPublisher;
private final UserService userService;
/**
* Instantiates a new Rest authentication success handler.
*
* @param eventPublisher the event publisher
* @param userService the user service
*/
@Autowired
public RestAuthenticationSuccessHandler(ApplicationEventPublisher eventPublisher, UserService userService) {
this.eventPublisher = eventPublisher;
this.userService = userService;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Object object = authentication.getPrincipal();
if (null != object) {
User springUser = (User) object;
com.mindskip.xzs.domain.User user = userService.getUserByUserName(springUser.getUsername());
if (null != user) {
UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
userEventLog.setContent(user.getUserName() + " 登录了学之思开源考试系统");
eventPublisher.publishEvent(new UserEvent(userEventLog));
com.mindskip.xzs.domain.User newUser = new com.mindskip.xzs.domain.User();
newUser.setUserName(user.getUserName());
newUser.setImagePath(user.getImagePath());
RestUtil.response(response, SystemCode.OK.getCode(), SystemCode.OK.getMessage(), newUser);
}
} else {
RestUtil.response(response, SystemCode.UNAUTHORIZED.getCode(), SystemCode.UNAUTHORIZED.getMessage());
}
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.domain.enums.RoleEnum;
import com.mindskip.xzs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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.Component;
import java.util.ArrayList;
/**
* @version 3.5.0
* @description: 验证通过之后,第二、三...请求,会调用此类
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@Component
public class RestDetailsServiceImpl implements UserDetailsService {
private final UserService userService;
/**
* Instantiates a new Rest details service.
*
* @param userService the user service
*/
@Autowired
public RestDetailsServiceImpl(UserService userService) {
this.userService = userService;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
com.mindskip.xzs.domain.User user = userService.getUserByUserName(username);
if (user == null) {
throw new UsernameNotFoundException("Username not found.");
}
ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.add(new SimpleGrantedAuthority(RoleEnum.fromCode(user.getRole()).getRoleName()));
return new User(user.getUserName(), user.getPassword(), grantedAuthorities);
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.configuration.property.CookieConfig;
import com.mindskip.xzs.utility.JsonUtil;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
/**
* @version 3.5.0
* @description: 登录参数序列化
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
public class RestLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final org.slf4j.Logger logger = LoggerFactory.getLogger(RestLoginAuthenticationFilter.class);
/**
* Instantiates a new Rest login authentication filter.
*/
public RestLoginAuthenticationFilter() {
super(new AntPathRequestMatcher("/api/user/login", "POST"));
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
UsernamePasswordAuthenticationToken authRequest;
try (InputStream is = request.getInputStream()) {
AuthenticationBean authenticationBean = JsonUtil.toJsonObject(is, AuthenticationBean.class);
request.setAttribute(TokenBasedRememberMeServices.DEFAULT_PARAMETER, authenticationBean.isRemember());
authRequest = new UsernamePasswordAuthenticationToken(authenticationBean.getUserName(), authenticationBean.getPassword());
} catch (IOException e) {
logger.error(e.getMessage(), e);
authRequest = new UsernamePasswordAuthenticationToken("", "");
}
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
/**
* Sets user details service.
*
* @param userDetailsService the user details service
*/
void setUserDetailsService(UserDetailsService userDetailsService) {
RestTokenBasedRememberMeServices tokenBasedRememberMeServices = new RestTokenBasedRememberMeServices(CookieConfig.getName(), userDetailsService);
tokenBasedRememberMeServices.setTokenValiditySeconds(CookieConfig.getInterval());
setRememberMeServices(tokenBasedRememberMeServices);
}
private void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.base.SystemCode;
import com.mindskip.xzs.domain.User;
import com.mindskip.xzs.domain.UserEventLog;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
* @version 3.5.0
* @description: 用户登出
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@Component
public class RestLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
private final ApplicationEventPublisher eventPublisher;
private final UserService userService;
/**
* Instantiates a new Rest logout success handler.
*
* @param eventPublisher the event publisher
* @param userService the user service
*/
@Autowired
public RestLogoutSuccessHandler(ApplicationEventPublisher eventPublisher, UserService userService) {
this.eventPublisher = eventPublisher;
this.userService = userService;
}
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
org.springframework.security.core.userdetails.User springUser = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
if (null != springUser) {
User user = userService.getUserByUserName(springUser.getUsername());
UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
userEventLog.setContent(user.getUserName() + " 登出了学之思开源考试系统");
eventPublisher.publishEvent(new UserEvent(userEventLog));
}
RestUtil.response(response, SystemCode.OK);
}
}
package com.mindskip.xzs.configuration.spring.security;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import javax.servlet.http.HttpServletRequest;
/**
* @version 3.5.0
* @description: 记住我,Cookie
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
public class RestTokenBasedRememberMeServices extends TokenBasedRememberMeServices {
/**
* Instantiates a new Rest token based remember me services.
*
* @param key the key
* @param userDetailsService the user details service
*/
public RestTokenBasedRememberMeServices(String key, UserDetailsService userDetailsService) {
super(key, userDetailsService);
}
@Override
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {
return (boolean) request.getAttribute(DEFAULT_PARAMETER);
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.base.SystemCode;
import com.mindskip.xzs.utility.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @version 3.5.0
* @description: The type Rest util.
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
public class RestUtil {
private static final Logger logger = LoggerFactory.getLogger(RestUtil.class);
/**
* Response.
*
* @param response the response
* @param systemCode the system code
*/
public static void response(HttpServletResponse response, SystemCode systemCode) {
response(response, systemCode.getCode(), systemCode.getMessage());
}
/**
* Response.
*
* @param response the response
* @param systemCode the system code
* @param msg the msg
*/
public static void response(HttpServletResponse response, int systemCode, String msg) {
response(response, systemCode, msg, null);
}
/**
* Response.
*
* @param response the response
* @param systemCode the system code
* @param msg the msg
* @param content the content
*/
public static void response(HttpServletResponse response, int systemCode, String msg, Object content) {
try {
RestResponse res = new RestResponse<>(systemCode, msg, content);
String resStr = JsonUtil.toJsonStr(res);
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(resStr);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
package com.mindskip.xzs.configuration.spring.security;
import com.mindskip.xzs.configuration.property.CookieConfig;
import com.mindskip.xzs.configuration.property.SystemConfig;
import com.mindskip.xzs.domain.enums.RoleEnum;
import org.springframework.beans.factory.annotation.Autowired;
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.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Collections;
import java.util.List;
/**
* @version 3.5.0
* @description: The type Security configurer.
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/12/25 9:45
*/
@Configuration
@EnableWebSecurity
public class SecurityConfigurer {
/**
* The type Form login web security configurer adapter.
*/
@Configuration
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final SystemConfig systemConfig;
private final LoginAuthenticationEntryPoint restAuthenticationEntryPoint;
private final RestAuthenticationProvider restAuthenticationProvider;
private final RestDetailsServiceImpl formDetailsService;
private final RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
private final RestAuthenticationFailureHandler restAuthenticationFailureHandler;
private final RestLogoutSuccessHandler restLogoutSuccessHandler;
private final RestAccessDeniedHandler restAccessDeniedHandler;
/**
* Instantiates a new Form login web security configurer adapter.
*
* @param systemConfig the system config
* @param restAuthenticationEntryPoint the rest authentication entry point
* @param restAuthenticationProvider the rest authentication provider
* @param formDetailsService the form details service
* @param restAuthenticationSuccessHandler the rest authentication success handler
* @param restAuthenticationFailureHandler the rest authentication failure handler
* @param restLogoutSuccessHandler the rest logout success handler
* @param restAccessDeniedHandler the rest access denied handler
*/
@Autowired
public FormLoginWebSecurityConfigurerAdapter(SystemConfig systemConfig, LoginAuthenticationEntryPoint restAuthenticationEntryPoint, RestAuthenticationProvider restAuthenticationProvider, RestDetailsServiceImpl formDetailsService, RestAuthenticationSuccessHandler restAuthenticationSuccessHandler, RestAuthenticationFailureHandler restAuthenticationFailureHandler, RestLogoutSuccessHandler restLogoutSuccessHandler, RestAccessDeniedHandler restAccessDeniedHandler) {
this.systemConfig = systemConfig;
this.restAuthenticationEntryPoint = restAuthenticationEntryPoint;
this.restAuthenticationProvider = restAuthenticationProvider;
this.formDetailsService = formDetailsService;
this.restAuthenticationSuccessHandler = restAuthenticationSuccessHandler;
this.restAuthenticationFailureHandler = restAuthenticationFailureHandler;
this.restLogoutSuccessHandler = restLogoutSuccessHandler;
this.restAccessDeniedHandler = restAccessDeniedHandler;
}
/**
* @param http http
* @throws Exception exception
* csrf is the from submit get method
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable();
List<String> securityIgnoreUrls = systemConfig.getSecurityIgnoreUrls();
String[] ignores = new String[securityIgnoreUrls.size()];
http
.addFilterAt(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint)
.and().authenticationProvider(restAuthenticationProvider)
.authorizeRequests()
.antMatchers(securityIgnoreUrls.toArray(ignores)).permitAll()
.antMatchers("/api/admin/**").hasRole(RoleEnum.ADMIN.getName())
.antMatchers("/api/student/**").hasRole(RoleEnum.STUDENT.getName())
.anyRequest().permitAll()
.and().exceptionHandling().accessDeniedHandler(restAccessDeniedHandler)
.and().formLogin().successHandler(restAuthenticationSuccessHandler).failureHandler(restAuthenticationFailureHandler)
.and().logout().logoutUrl("/api/user/logout").logoutSuccessHandler(restLogoutSuccessHandler).invalidateHttpSession(true)
.and().rememberMe().key(CookieConfig.getName()).tokenValiditySeconds(CookieConfig.getInterval()).userDetailsService(formDetailsService)
.and().csrf().disable()
.cors();
}
/**
* Cors configuration source cors configuration source.
*
* @return the cors configuration source
*/
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setMaxAge(3600L);
configuration.setAllowedOrigins(Collections.singletonList("*"));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Collections.singletonList("*"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", configuration);
return source;
}
/**
* Authentication filter rest login authentication filter.
*
* @return the rest login authentication filter
* @throws Exception the exception
*/
@Bean
public RestLoginAuthenticationFilter authenticationFilter() throws Exception {
RestLoginAuthenticationFilter authenticationFilter = new RestLoginAuthenticationFilter();
authenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
authenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
authenticationFilter.setAuthenticationManager(authenticationManagerBean());
authenticationFilter.setUserDetailsService(formDetailsService);
return authenticationFilter;
}
}
}
package com.mindskip.xzs.context;
import com.mindskip.xzs.domain.User;
import com.mindskip.xzs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
/**
* @version 3.3.0
* @description: The enum System code.
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
* @date 2021/5/25 10:45
*/
@Component
public class WebContext {
private static final String USER_ATTRIBUTES = "USER_ATTRIBUTES";
private final UserService userService;
/**
* Instantiates a new Web context.
*
* @param userService the user service
*/
@Autowired
public WebContext(UserService userService) {
this.userService = userService;
}
/**
* Sets current user.
*
* @param user the user
*/
public void setCurrentUser(User user) {
RequestContextHolder.currentRequestAttributes().setAttribute(USER_ATTRIBUTES, user, RequestAttributes.SCOPE_REQUEST);
}
/**
* Gets current user.
*
* @return the current user
*/
public User getCurrentUser() {
User user = (User) RequestContextHolder.currentRequestAttributes().getAttribute(USER_ATTRIBUTES, RequestAttributes.SCOPE_REQUEST);
if (null != user) {
return user;
} else {
org.springframework.security.core.userdetails.User springUser = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (null == springUser) {
return null;
}
user = userService.getUserByUserName(springUser.getUsername());
if (null != user) {
setCurrentUser(user);
}
return user;
}
}
}
package com.mindskip.xzs.controller;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.service.*;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.viewmodel.dashboard.IndexVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController("AdminDashboardController")
@RequestMapping(value = "/api/admin/dashboard")
public class DashboardController extends BaseApiController {
private final ExamPaperService examPaperService;
private final QuestionService questionService;
private final ExamPaperAnswerService examPaperAnswerService;
private final ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService;
private final UserEventLogService userEventLogService;
@Autowired
public DashboardController(ExamPaperService examPaperService, QuestionService questionService, ExamPaperAnswerService examPaperAnswerService, ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService, UserEventLogService userEventLogService) {
this.examPaperService = examPaperService;
this.questionService = questionService;
this.examPaperAnswerService = examPaperAnswerService;
this.examPaperQuestionCustomerAnswerService = examPaperQuestionCustomerAnswerService;
this.userEventLogService = userEventLogService;
}
@RequestMapping(value = "/index", method = RequestMethod.POST)
public RestResponse<IndexVM> Index() {
IndexVM vm = new IndexVM();
Integer examPaperCount = examPaperService.selectAllCount();
Integer questionCount = questionService.selectAllCount();
Integer doExamPaperCount = examPaperAnswerService.selectAllCount();
Integer doQuestionCount = examPaperQuestionCustomerAnswerService.selectAllCount();
vm.setExamPaperCount(examPaperCount);
vm.setQuestionCount(questionCount);
vm.setDoExamPaperCount(doExamPaperCount);
vm.setDoQuestionCount(doQuestionCount);
List<Integer> mothDayUserActionValue = userEventLogService.selectMothCount();
List<Integer> mothDayDoExamQuestionValue = examPaperQuestionCustomerAnswerService.selectMothCount();
vm.setMothDayUserActionValue(mothDayUserActionValue);
vm.setMothDayDoExamQuestionValue(mothDayDoExamQuestionValue);
vm.setMothDayText(DateTimeUtil.MothDay());
return RestResponse.ok(vm);
}
}
package com.mindskip.xzs.controller;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.domain.Subject;
import com.mindskip.xzs.service.SubjectService;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.education.SubjectEditRequestVM;
import com.mindskip.xzs.viewmodel.education.SubjectPageRequestVM;
import com.mindskip.xzs.viewmodel.education.SubjectResponseVM;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController("AdminEducationController")
@RequestMapping(value = "/api/admin/education")
public class EducationController extends BaseApiController {
private final SubjectService subjectService;
@Autowired
public EducationController(SubjectService subjectService) {
this.subjectService = subjectService;
}
@RequestMapping(value = "/subject/list", method = RequestMethod.POST)
public RestResponse<List<Subject>> list() {
List<Subject> subjects = subjectService.allSubject();
return RestResponse.ok(subjects);
}
@RequestMapping(value = "/subject/page", method = RequestMethod.POST)
public RestResponse<PageInfo<SubjectResponseVM>> pageList(@RequestBody SubjectPageRequestVM model) {
PageInfo<Subject> pageInfo = subjectService.page(model);
PageInfo<SubjectResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> modelMapper.map(e, SubjectResponseVM.class));
return RestResponse.ok(page);
}
@RequestMapping(value = "/subject/edit", method = RequestMethod.POST)
public RestResponse edit(@RequestBody @Valid SubjectEditRequestVM model) {
Subject subject = modelMapper.map(model, Subject.class);
if (model.getId() == null) {
subject.setDeleted(false);
subjectService.insertByFilter(subject);
} else {
subjectService.updateByIdFilter(subject);
}
return RestResponse.ok();
}
@RequestMapping(value = "/subject/select/{id}", method = RequestMethod.POST)
public RestResponse<SubjectEditRequestVM> select(@PathVariable Integer id) {
Subject subject = subjectService.selectById(id);
SubjectEditRequestVM vm = modelMapper.map(subject, SubjectEditRequestVM.class);
return RestResponse.ok(vm);
}
@RequestMapping(value = "/subject/delete/{id}", method = RequestMethod.POST)
public RestResponse delete(@PathVariable Integer id) {
Subject subject = subjectService.selectById(id);
subject.setDeleted(true);
subjectService.updateByIdFilter(subject);
return RestResponse.ok();
}
}
package com.mindskip.xzs.controller;
import com.mindskip.xzs.base.SystemCode;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@RestController
public class ErrorController extends BasicErrorController {
private static final String PATH = "/error";
public ErrorController() {
super(new DefaultErrorAttributes(), new ErrorProperties());
}
@RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> error = new HashMap<>(2);
error.put("code", SystemCode.InnerError.getCode());
error.put("message", SystemCode.InnerError.getMessage());
return new ResponseEntity<>(error, HttpStatus.OK);
}
@Override
public String getErrorPath() {
return PATH;
}
}
package com.mindskip.xzs.controller;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.domain.ExamPaperAnswer;
import com.mindskip.xzs.domain.Subject;
import com.mindskip.xzs.domain.User;
import com.mindskip.xzs.service.*;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.ExamUtil;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.student.exampaper.ExamPaperAnswerPageResponseVM;
import com.mindskip.xzs.viewmodel.paper.ExamPaperAnswerPageRequestVM;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController("AdminExamPaperAnswerController")
@RequestMapping(value = "/api/admin/examPaperAnswer")
public class ExamPaperAnswerController extends BaseApiController {
private final ExamPaperAnswerService examPaperAnswerService;
private final SubjectService subjectService;
private final UserService userService;
@Autowired
public ExamPaperAnswerController(ExamPaperAnswerService examPaperAnswerService, SubjectService subjectService, UserService userService) {
this.examPaperAnswerService = examPaperAnswerService;
this.subjectService = subjectService;
this.userService = userService;
}
@RequestMapping(value = "/page", method = RequestMethod.POST)
public RestResponse<PageInfo<ExamPaperAnswerPageResponseVM>> pageJudgeList(@RequestBody ExamPaperAnswerPageRequestVM model) {
PageInfo<ExamPaperAnswer> pageInfo = examPaperAnswerService.adminPage(model);
PageInfo<ExamPaperAnswerPageResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> {
ExamPaperAnswerPageResponseVM vm = modelMapper.map(e, ExamPaperAnswerPageResponseVM.class);
Subject subject = subjectService.selectById(vm.getSubjectId());
vm.setDoTime(ExamUtil.secondToVM(e.getDoTime()));
vm.setSystemScore(ExamUtil.scoreToVM(e.getSystemScore()));
vm.setUserScore(ExamUtil.scoreToVM(e.getUserScore()));
vm.setPaperScore(ExamUtil.scoreToVM(e.getPaperScore()));
vm.setSubjectName(subject.getName());
vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
User user = userService.selectById(e.getCreateUser());
vm.setUserName(user.getUserName());
return vm;
});
return RestResponse.ok(page);
}
}
Supports Markdown
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