提交 e79fb1ec authored 作者: gongwenjie's avatar gongwenjie

登录权限,根据前台修改部分代码

上级 82ff72dc
......@@ -8,8 +8,11 @@ import com.zjty.tynotes.pas.entity.*;
import com.zjty.tynotes.pas.service.IAuthorityService;
import com.zjty.tynotes.pas.service.IRoleService;
import com.zjty.tynotes.pas.service.IUserService;
import com.zjty.tynotes.pas.task.Init;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
......@@ -29,7 +32,8 @@ import java.util.Optional;
*/
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {
private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
IUserService iUserService;
......@@ -42,40 +46,58 @@ public class MyUserDetailsServiceImpl implements UserDetailsService {
@Autowired
private AuthorityDao authorityDao;
@Autowired
private Init init;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("userService验证:" + username);
User user = iUserService.findUserByUsername(username);
if(user!=null){
List<UserRole> userRoles = userRoleDao.findAllByUserId(user.getId());
List<String> roleIds = new ArrayList<>();
if(userRoles!=null){
for (UserRole userRole : userRoles) {
roleIds.add(userRole.getRoleId());
}
if(username.equals("root")){
User root = init.root;
// root.setPassword("root");
// root.setPassword(bCryptPasswordEncoder.encode("root"));
List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
List<Role> roles = root.getRoles();
Role role = roles.get(0);
List<Authority> authorities = role.getAuthorities();
SimpleGrantedAuthority s = new SimpleGrantedAuthority("管理员");
for (Authority authority : authorities) {
authorityList.add(new SimpleGrantedAuthority(authority.getName()));
}
user.setUsername(username);
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
ArrayList<SimpleGrantedAuthority> list = new ArrayList<>();
List<Role> roles = roleDao.findAllByIdIn(roleIds);
List<RoleAuthority> roleAuthorities = roleAuthorityDao.findAllByRoleIdIn(roleIds);
List<String> authorityIds = new ArrayList<>();
if(roleAuthorities!=null){
for (RoleAuthority roleAuthority : roleAuthorities) {
if(!authorityIds.contains(roleAuthority.getAuthorityId())){
authorityIds.add(roleAuthority.getAuthorityId());
root.setArrayList(authorityList);
return root;
}else{
User user = iUserService.findUserByUsername(username);
if(user!=null){
List<UserRole> userRoles = userRoleDao.findAllByUserId(user.getId());
List<String> roleIds = new ArrayList<>();
if(userRoles!=null){
for (UserRole userRole : userRoles) {
roleIds.add(userRole.getRoleId());
}
}
user.setUsername(username);
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
ArrayList<SimpleGrantedAuthority> list = new ArrayList<>();
List<Role> roles = roleDao.findAllByIdIn(roleIds);
List<RoleAuthority> roleAuthorities = roleAuthorityDao.findAllByRoleIdIn(roleIds);
List<String> authorityIds = new ArrayList<>();
if(roleAuthorities!=null){
for (RoleAuthority roleAuthority : roleAuthorities) {
if(!authorityIds.contains(roleAuthority.getAuthorityId())){
authorityIds.add(roleAuthority.getAuthorityId());
}
}
}
}
List<Authority> authorities = authorityDao.findAllByIdIn(authorityIds);
authorities.forEach(authority -> {
list.add(new SimpleGrantedAuthority(authority.getName()));
});
user.setArrayList(list);
List<Authority> authorities = authorityDao.findAllByIdIn(authorityIds);
authorities.forEach(authority -> {
list.add(new SimpleGrantedAuthority(authority.getName()));
});
user.setArrayList(list);
}
return user;
}else{
return new User();
}
}
}
......@@ -52,13 +52,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.cors().and()
.authorizeRequests()
// .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers(HttpMethod.DELETE, "/pas/user/delete/**").hasAuthority("deleteUser")
.antMatchers(HttpMethod.POST, "/pas/user").hasAuthority("addUser")
.antMatchers(HttpMethod.PUT, "/pas/user").hasAuthority("updateUser")
.antMatchers(HttpMethod.POST, "/pas/department").hasAuthority("system")
.antMatchers(HttpMethod.POST, "/pas/role").hasAuthority("system")
.antMatchers(HttpMethod.GET, "/pas/authority").hasAuthority("system")
.antMatchers(HttpMethod.POST, "/pas/group").hasAuthority("system")
.antMatchers("/pas/user").hasAnyAuthority("用户管理")
.antMatchers("/pas/authority").hasAnyAuthority("权限管理")
.antMatchers("/pas/config").hasAnyAuthority("考勤管理")
.antMatchers("/pas/role").hasAnyAuthority("角色管理")
.antMatchers("/pas/department").hasAnyAuthority("部门管理")
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
.antMatchers("/pas/count").permitAll()
.anyRequest().authenticated()
......
//package com.zjty.tynotes.pas.config.handler;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.zjty.tynotes.pas.entity.Authority;
//import com.zjty.tynotes.pas.entity.Role;
//import com.zjty.tynotes.pas.entity.User;
//import com.zjty.tynotes.pas.service.IAuthorityService;
//import com.zjty.tynotes.pas.service.IRoleService;
//import com.zjty.tynotes.pas.service.IUserService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.core.ValueOperations;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.context.SecurityContext;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.session.SessionInformation;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
//import org.springframework.security.web.authentication.session.SessionAuthenticationException;
//import org.springframework.security.web.session.ConcurrentSessionFilter;
//import org.springframework.stereotype.Component;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.Cookie;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.util.List;
//
///**
// * @author mcj
// */
//@Component
//@Slf4j
//public class MySuccessHandler implements AuthenticationSuccessHandler {
// @Autowired
// private SessionRegistry sessionRegistry;
//
// @Autowired
// private IAuthorityService iAuthorityService;
//
// @Autowired
// IRoleService iRoleService;
//
// private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//
// @Autowired
// IUserService iUserService;
//
// @Autowired
// RedisTemplate redisTemplate;
//
// @Override
// public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
// Cookie[] cookies = httpServletRequest.getCookies();
// if(cookies==null){
// return;
// }
// String value = cookies[0].getValue();
// List<Object> o = sessionRegistry.getAllPrincipals();
// User user = (User) authentication.getPrincipal();
// for (Object principal : o) {
// User cacheUser = (User) principal;
// if (cacheUser.getUsername().equals(user.getUsername())) {
// log.info("当前用户已经在线上.现顶替:{}",user.getUsername());
// List<SessionInformation> sessions = sessionRegistry.getAllSessions(cacheUser, false);
// for (SessionInformation sessionInformation : sessions) {
// String sessionId = sessionInformation.getSessionId();
//
// sessionInformation.expireNow();
// }
// }
// }
//
// redisTemplate.opsForValue().set(user.getUsername(),0);
//
// UserVo userVo = new UserVo().user2userVo(user);
// User username = iUserService.findUserByUsername(userVo.getUsername());
// Role role = iRoleService.findRoleById(user.getRoleId());
// RoleVo roleVo = new RoleVo();
// User user1 = iUserService.findUserByUsername(userVo.getUsername());
// userVo.setPassword(user1.getPassword());
// roleVo.setRoleId(user.getRoleId());
// List<Menu> allByMenuId = iMenuSerivce.findAllByMenuId(role.getMenuIds());
// roleVo.setMenus(allByMenuId);
// roleVo.setRoleName(role.getName());
// userVo.setRole(roleVo);
// List<Authority> authorityByIds = iAuthorityService.findAuthorityByIds(role.getAuthorityIds());
// roleVo.setAuthorities(authorityByIds);
//
// sessionRegistry.registerNewSession(value, authentication.getPrincipal());
// httpServletResponse.setStatus(200);
// httpServletResponse.setContentType("application/json; charset=utf-8");
// httpServletResponse.getWriter().println(new ObjectMapper().writeValueAsString(userVo));
//
//
// }
//}
package com.zjty.tynotes.pas.config.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjty.tynotes.pas.entity.Authority;
import com.zjty.tynotes.pas.entity.Role;
import com.zjty.tynotes.pas.entity.User;
import com.zjty.tynotes.pas.service.IAuthorityService;
import com.zjty.tynotes.pas.service.IRoleService;
import com.zjty.tynotes.pas.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.session.ConcurrentSessionFilter;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* @author mcj
*/
@Component
@Slf4j
public class MySuccessHandler implements AuthenticationSuccessHandler {
@Autowired
private SessionRegistry sessionRegistry;
@Autowired
private IAuthorityService iAuthorityService;
@Autowired
IRoleService iRoleService;
private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
@Autowired
IUserService iUserService;
@Autowired
RedisTemplate redisTemplate;
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
Cookie[] cookies = httpServletRequest.getCookies();
if(cookies==null){
return;
}
String value = cookies[0].getValue();
List<Object> o = sessionRegistry.getAllPrincipals();
User user = (User) authentication.getPrincipal();
for (Object principal : o) {
User cacheUser = (User) principal;
if (cacheUser.getUsername().equals(user.getUsername())) {
log.info("当前用户已经在线上.现顶替:{}",user.getUsername());
List<SessionInformation> sessions = sessionRegistry.getAllSessions(cacheUser, false);
for (SessionInformation sessionInformation : sessions) {
String sessionId = sessionInformation.getSessionId();
sessionInformation.expireNow();
}
}
}
redisTemplate.opsForValue().set(user.getUsername(),0);
sessionRegistry.registerNewSession(value, authentication.getPrincipal());
httpServletResponse.setStatus(200);
httpServletResponse.setContentType("application/json; charset=utf-8");
httpServletResponse.getWriter().println(new ObjectMapper().writeValueAsString("登陆成功"));
}
}
......@@ -28,7 +28,7 @@ public class AuthorityController {
@ApiOperation("新增权限")
@PostMapping("/addAuthority")
public ResponseEntity addAuthority(Authority authority){
public ResponseEntity addAuthority(@RequestBody Authority authority){
return ok(iAuthorityService.addAuthority(authority));
}
......@@ -66,4 +66,6 @@ public class AuthorityController {
return ok(iAuthorityService.findAuthority());
}
}
......@@ -36,6 +36,8 @@ public class ConfigController {
return ok(configService.save(configs));
}
@ApiOperation("获取节假日集合")
@GetMapping("/getHoliday")
public ResponseEntity getHoliday(@RequestBody HolidayRequest holidayRequest){
......
......@@ -73,7 +73,12 @@ public class RoleController {
return "修改角色失败";
}
@ApiOperation(value = "根据部门查询角色",response = Role.class)
@GetMapping("/findRoleByDepartId/{id}")
public ResponseEntity updateRole(@PathVariable("id") String id){
return ResponseEntity.ok(iRoleService.findRoleByDepartId(id));
}
......
......@@ -17,10 +17,9 @@ public interface PasUserDao extends MongoRepository<User, String> {
/**
* 根据用户名查询用户对象
* @param username 用户名
* @param status 状态
* @return User
*/
User findAllByUsernameEqualsAndStatusEquals(String username,Integer status);
User findByUsername(String username);
/**
* 根据id列表查询
......
......@@ -14,4 +14,6 @@ public interface RoleDao extends MongoRepository<Role, String> {
List<Role> findAllByIdIn(List<String> ids);
List<Role> findAllByDepartmentIdAndIsLeader(String departmentIds,String isLeader);
List<Role> findAllByDepartmentId(String departmentId);
}
......@@ -24,14 +24,62 @@ public class Config {
@ApiModelProperty(value = "id",example = "1")
private String id;
@NotEmpty(message = "参数名称不可为空")
@ApiModelProperty(value = "参数名称",example = "上班时间")
private String name;
@ApiModelProperty(value = "权限描述",example = "。。。。")
private String description;
@NotEmpty(message = "上班时间")
@ApiModelProperty(value = "上班时间",example = "2019/2/2")
private String workTime;
@NotEmpty(message = "下班时间")
@ApiModelProperty(value = "下班时间",example = "2019/2/2")
private String afterWorkTime;
@NotEmpty(message = "每日考勤基础分")
@ApiModelProperty(value = "每日考勤基础分",example = "2")
private String score;
@NotEmpty(message = "迟到次数")
@ApiModelProperty(value = "迟到次数",example = "3")
private String lateNum;
@NotEmpty(message = "迟到15分钟以上扣分")
@ApiModelProperty(value = "迟到15分钟以上扣分",example = "2")
private String latePointsFifteen;
@NotEmpty(message = "迟到半天扣分")
@ApiModelProperty(value = "迟到半天扣分",example = "4")
private String latePointsHalfOfDay;
@NotEmpty(message = "事假半天扣分")
@ApiModelProperty(value = "事假半天",example = "2")
private String thingHalfOfDay;
@NotEmpty(message = "病假次数")
@ApiModelProperty(value = "病假次数",example = "8")
private String sickNum;
@NotEmpty(message = "调休半天扣分")
@ApiModelProperty(value = "调休半天扣分",example = "2")
private String paidHalfOfDayLeave;
@NotEmpty(message = "调休一天扣分")
@ApiModelProperty(value = "调休一天扣分",example = "2")
private String paidDayLeave;
@NotEmpty(message = "月补卡数")
@ApiModelProperty(value = "月补卡数",example = "5")
private String addCardNum;
@NotEmpty(message = "加班一小时加分")
@ApiModelProperty(value = "加班一小时加分",example = "0.25")
private String workOverScore;
@NotEmpty(message = "全天旷工扣分")
@ApiModelProperty(value = "全天旷工扣分",example = "6")
private String absenteeism;
@NotEmpty(message = "事假一天扣分")
@ApiModelProperty(value = "事假一天扣分",example = "4")
private String thingDay;
@ApiModelProperty(value = "参数值",example = "2020/2/10")
private String value;
}
......@@ -33,7 +33,6 @@ public class Department {
String level;
@ApiModelProperty(value = "上级部门id",example = "1")
@NotNull(message = "上级部门id不可为空")
String parentId;
@Transient
......
......@@ -9,6 +9,7 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
......
......@@ -47,4 +47,6 @@ public interface IRoleService {
* @return
*/
boolean deleteRole(String id);
List<Role> findRoleByDepartId(String id);
}
......@@ -55,6 +55,7 @@ public class AuthorityServiceImpl implements IAuthorityService {
Authority authority1 = byId.get();
authority1.setName(authority.getName());
authority1.setDescription(authority.getDescription());
authorityDao.save(authority1);
return authority1;
}
return null;
......
......@@ -67,22 +67,50 @@ public class ConfigServiceImpl implements ConfigService {
@Override
public List<Day> findHolidaysByMonth(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = sdf.parse(date);
int year = date1.getYear();
int month = date1.getMonth();
int year = date1.getYear()+1900;
int month = date1.getMonth()+1;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,1);
calendar.set(Calendar.MONTH,month-1);
calendar.set(Calendar.DAY_OF_MONTH,2);
Date firstDate = calendar.getTime();
calendar.set(Calendar.DAY_OF_MONTH,-1);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,0);
Date lastDate = calendar.getTime();
List<Day> days = dayDao.findAllByDateBetween(firstDate, lastDate);
if(days==null || days.size()==0){
calendar.set(Calendar.DAY_OF_MONTH,2);
List<String> fullDayList = new ArrayList<>(32);
int count = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int j = 1; j <= count ; j++) {
fullDayList.add(sdf.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH,1);
}
List<Day> days1 = new ArrayList<>();
for (String string : fullDayList) {
Day day = new Day();
day.setStatus("0");
day.setDate(sdf.parse(string));
days1.add(day);
}
return dayDao.saveAll(days1);
}
calendar.set(Calendar.MONTH,month-1);
calendar.set(Calendar.DAY_OF_MONTH,1);
firstDate = calendar.getTime();
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,1);
lastDate = calendar.getTime();
return dayDao.findAllByDateBetween(firstDate,lastDate);
} catch (ParseException e) {
}
return null;
}
}
......@@ -81,6 +81,11 @@ public class RoleServiceImpl implements IRoleService {
return false;
}
@Override
public List<Role> findRoleByDepartId(String id) {
return roleDao.findAllByDepartmentId(id);
}
@Override
public Boolean updateRole(Role role) {
List<Authority> authorities = role.getAuthorities();
......
......@@ -104,7 +104,7 @@ public class UserServiceImpl implements IUserService {
@Override
public User findUserByUsername(String username) {
return pasUserDao.findAllByUsernameEqualsAndStatusEquals(username,0);
return pasUserDao.findByUsername(username);
}
@Override
......
......@@ -9,6 +9,8 @@ import com.zjty.tynotes.pas.service.IDepartmentService;
import com.zjty.tynotes.pas.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
......@@ -31,32 +33,37 @@ public class Init implements CommandLineRunner {
@Autowired
private IRoleService iRoleService;
public User root;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public void run(String... args) throws Exception {
// iRoleService.deleteAll();
root = new User();
Role role = new Role(null,"管理员","管理系统的人员",null,null,null);
List<Authority> authorities = new ArrayList<>();
Authority authority2 = new Authority(null,"用户管理","无");
Authority authority1 = new Authority(null,"权限管理","无");
Authority authority3 = new Authority(null,"角色管理","无");
Authority authority4 = new Authority(null,"考勤管理","无");
Authority authority5 = new Authority(null,"部门管理","无");
authorities.add(authority2);
authorities.add(authority1);
authorities.add(authority3);
authorities.add(authority4);
authorities.add(authority5);
role.setAuthorities(authorities);
List<Authority> all = iAuthorityService.findAuthority();
List<String> list = all.stream().map(Authority::getId).collect(Collectors.toList());
Role role = new Role();
role.setName("管理员");
root.createUser();
root.setUsername("root");
Role role1 = null;
if (iRoleService.findAll().size() == 0) {
role1 = iRoleService.addRole(role);
}
if (pasUserDao.findAllByUsername("root") == null) {
User user = new User();
user.createUser();
user.setUsername("root");
user.setPassword("root");
if (role1 != null) {
List<Role> roles = new ArrayList<>();
roles.add(role1);
user.setRoles(roles);
}
user.setDepartmentId("1");
pasUserDao.save(user);
}
root.setPassword(bCryptPasswordEncoder.encode("root"));
List<Role> roles = new ArrayList<>();
roles.add(role);
root.setRoles(roles);
// User user1 = new User();
......
spring.application.name=workbook
# https端口号.
server.port=8082
## 证书的路径.
......@@ -13,7 +14,7 @@ server.port=8082
#server.ssl.keyAlias= alias
#mongodb configuration
spring.data.mongodb.uri=mongodb://192.168.1.248:27017/note
spring.data.mongodb.uri=mongodb://localhost:27017/note
# servlet configuration
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论