1
0
mirror of https://github.com/chatopera/cosin.git synced 2025-08-01 16:38:02 +08:00

Fix UserRoleRepository related class

This commit is contained in:
dengchao@xgtl 2020-04-17 09:46:39 +08:00
parent 04cab0db80
commit ad6946e859
4 changed files with 536 additions and 580 deletions

View File

@ -1,402 +1,368 @@
/* /*
* Copyright (C) 2017 优客服-多渠道客服系统 * Copyright (C) 2017 优客服-多渠道客服系统
* Modifications copyright (C) 2018-2019 Chatopera Inc, <https://www.chatopera.com> * Modifications copyright (C) 2018-2019 Chatopera Inc, <https://www.chatopera.com>
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.chatopera.cc.controller; package com.chatopera.cc.controller;
import com.chatopera.cc.acd.ACDWorkMonitor; import com.chatopera.cc.acd.ACDWorkMonitor;
import com.chatopera.cc.basic.Constants; import com.chatopera.cc.basic.Constants;
import com.chatopera.cc.basic.MainContext; import com.chatopera.cc.basic.MainContext;
import com.chatopera.cc.basic.MainUtils; import com.chatopera.cc.basic.MainUtils;
import com.chatopera.cc.basic.auth.AuthToken; import com.chatopera.cc.basic.auth.AuthToken;
import com.chatopera.cc.cache.Cache; import com.chatopera.cc.model.AgentStatus;
import com.chatopera.cc.model.AgentStatus; import com.chatopera.cc.model.SystemConfig;
import com.chatopera.cc.model.SystemConfig; import com.chatopera.cc.model.User;
import com.chatopera.cc.model.User; import com.chatopera.cc.model.UserRole;
import com.chatopera.cc.model.UserRole; import com.chatopera.cc.persistence.repository.UserRepository;
import com.chatopera.cc.persistence.repository.AgentStatusRepository; import com.chatopera.cc.persistence.repository.UserRoleRepository;
import com.chatopera.cc.persistence.repository.UserRepository; import com.chatopera.cc.proxy.AgentProxy;
import com.chatopera.cc.persistence.repository.UserRoleRepository; import com.chatopera.cc.proxy.AgentSessionProxy;
import com.chatopera.cc.proxy.AgentProxy; import com.chatopera.cc.proxy.OnlineUserProxy;
import com.chatopera.cc.proxy.AgentSessionProxy; import com.chatopera.cc.proxy.UserProxy;
import com.chatopera.cc.proxy.OnlineUserProxy; import com.chatopera.cc.util.Menu;
import com.chatopera.cc.proxy.UserProxy; import lombok.RequiredArgsConstructor;
import com.chatopera.cc.util.Menu; import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.StringUtils; import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException; import org.slf4j.Logger;
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import org.slf4j.LoggerFactory; import org.springframework.lang.NonNull;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.Cookie;
import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponse; import javax.validation.Valid;
import javax.validation.Valid; import java.util.Date;
import java.io.UnsupportedEncodingException; import java.util.List;
import java.security.NoSuchAlgorithmException; import java.util.Optional;
import java.util.Date;
import java.util.List; /**
* @author CSKefu
/** * @version 1.0.1
* @author CSKefu */
* @version 1.0.1 @Controller
*/ @RequiredArgsConstructor
@Controller public class LoginController extends Handler {
public class LoginController extends Handler { private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
@NonNull
@Autowired private final UserRepository userRepository;
private UserRepository userRepository;
@NonNull
@Autowired private final UserRoleRepository userRoleRes;
private UserRoleRepository userRoleRes;
@NonNull
@Autowired private final AuthToken authToken;
private AuthToken authToken;
@NonNull
@Autowired private final AgentProxy agentProxy;
private AgentStatusRepository agentStatusRes;
@NonNull
@Autowired private final AgentSessionProxy agentSessionProxy;
private Cache cache;
@NonNull
@Autowired private final UserProxy userProxy;
private AgentProxy agentProxy;
@NonNull
@Autowired private final ACDWorkMonitor acdWorkMonitor;
private AgentSessionProxy agentSessionProxy;
/**
@Autowired * 登录页面
private UserProxy userProxy; */
@RequestMapping(value = "/login", method = RequestMethod.GET)
@Autowired @Menu(type = "apps", subtype = "user", access = true)
private ACDWorkMonitor acdWorkMonitor; public ModelAndView login(HttpServletRequest request, @RequestHeader(value = "referer", required = false) String referer, @Valid String msg) {
ModelAndView view = new ModelAndView("redirect:/");
/** if (request.getSession(true).getAttribute(Constants.USER_SESSION_NAME) == null) {
* 登录页面 view = new ModelAndView("/login");
* if (StringUtils.isNotBlank(request.getParameter("referer"))) {
* @param request referer = request.getParameter("referer");
* @param response }
* @param referer if (StringUtils.isNotBlank(referer)) {
* @param msg view.addObject("referer", referer);
* @return }
* @throws NoSuchAlgorithmException Cookie[] cookies = request.getCookies(); // 这样便可以获取一个cookie数组
*/ if (cookies != null) {
@RequestMapping(value = "/login", method = RequestMethod.GET) for (Cookie cookie : cookies) {
@Menu(type = "apps", subtype = "user", access = true) if (cookie != null && StringUtils.isNotBlank(cookie.getName()) && StringUtils.isNotBlank(
public ModelAndView login(HttpServletRequest request, HttpServletResponse response, @RequestHeader(value = "referer", required = false) String referer, @Valid String msg) { cookie.getValue())) {
ModelAndView view = new ModelAndView("redirect:/"); if (cookie.getName().equals(Constants.CSKEFU_SYSTEM_COOKIES_FLAG)) {
if (request.getSession(true).getAttribute(Constants.USER_SESSION_NAME) == null) { String flagid;
view = new ModelAndView("/login"); try {
if (StringUtils.isNotBlank(request.getParameter("referer"))) { flagid = MainUtils.decryption(cookie.getValue());
referer = request.getParameter("referer"); if (StringUtils.isNotBlank(flagid)) {
} Optional<User> optional = userRepository.findById(flagid);
if (StringUtils.isNotBlank(referer)) { if (optional.isPresent()) {
view.addObject("referer", referer); view = this.processLogin(request, optional.get(), referer);
} }
Cookie[] cookies = request.getCookies(); // 这样便可以获取一个cookie数组 }
if (cookies != null) { } catch (EncryptionOperationNotPossibleException e) {
for (Cookie cookie : cookies) { logger.error("[login] error:", e);
if (cookie != null && StringUtils.isNotBlank(cookie.getName()) && StringUtils.isNotBlank( view = request(super.createRequestPageTempletResponse("/public/clearcookie"));
cookie.getValue())) { return view;
if (cookie.getName().equals(Constants.CSKEFU_SYSTEM_COOKIES_FLAG)) { }
String flagid; }
try { }
flagid = MainUtils.decryption(cookie.getValue()); }
if (StringUtils.isNotBlank(flagid)) { }
User user = userRepository.findById(flagid); }
if (user != null) { if (StringUtils.isNotBlank(msg)) {
view = this.processLogin(request, user, referer); view.addObject("msg", msg);
} }
} SystemConfig systemConfig = MainUtils.getSystemConfig();
} catch (EncryptionOperationNotPossibleException e) { if (systemConfig != null && systemConfig.isEnableregorgi()) {
logger.error("[login] error:", e); view.addObject("show", true);
view = request(super.createRequestPageTempletResponse("/public/clearcookie")); }
return view; if (systemConfig != null) {
} catch (NoSuchAlgorithmException e) { view.addObject("systemConfig", systemConfig);
logger.error("[login] error:", e); }
} return view;
} }
}
} /**
} * 提交登录表单
} */
if (StringUtils.isNotBlank(msg)) { @RequestMapping(value = "/login", method = RequestMethod.POST)
view.addObject("msg", msg); @Menu(type = "apps", subtype = "user", access = true)
} public ModelAndView login(
SystemConfig systemConfig = MainUtils.getSystemConfig(); final HttpServletRequest request,
if (systemConfig != null && systemConfig.isEnableregorgi()) { final HttpServletResponse response,
view.addObject("show", true); @Valid User user,
} @Valid String referer,
if (systemConfig != null) { @Valid String sla) {
view.addObject("systemConfig", systemConfig); ModelAndView view = new ModelAndView("redirect:/");
} if (request.getSession(true).getAttribute(Constants.USER_SESSION_NAME) == null) {
return view; if (user != null && user.getUsername() != null) {
} final User loginUser = userRepository.findByUsernameAndPasswordAndDatastatus(
user.getUsername(), MainUtils.md5(user.getPassword()), false);
/** if (loginUser != null && StringUtils.isNotBlank(loginUser.getId())) {
* 提交登录表单 view = this.processLogin(request, loginUser, referer);
*
* @param request // 自动登录
* @param response if (StringUtils.equals("1", sla)) {
* @param user Cookie flagid = new Cookie(
* @param referer Constants.CSKEFU_SYSTEM_COOKIES_FLAG, MainUtils.encryption(loginUser.getId()));
* @param sla flagid.setMaxAge(7 * 24 * 60 * 60);
* @return response.addCookie(flagid);
* @throws NoSuchAlgorithmException }
*/
@RequestMapping(value = "/login", method = RequestMethod.POST) // add authorization code for rest api
@Menu(type = "apps", subtype = "user", access = true) final String orgi = loginUser.getOrgi();
public ModelAndView login( String auth = MainUtils.getUUID();
final HttpServletRequest request, authToken.putUserByAuth(auth, loginUser);
final HttpServletResponse response, userRepository.save(loginUser); // 更新登录状态到数据库
@Valid User user, response.addCookie((new Cookie("authorization", auth)));
@Valid String referer,
@Valid String sla) throws NoSuchAlgorithmException { // 该登录用户是坐席并且具有坐席对话的角色
ModelAndView view = new ModelAndView("redirect:/"); if ((loginUser.isAgent() &&
if (request.getSession(true).getAttribute(Constants.USER_SESSION_NAME) == null) { loginUser.getRoleAuthMap().containsKey("A01") &&
if (user != null && user.getUsername() != null) { ((boolean) loginUser.getRoleAuthMap().get("A01")))
final User loginUser = userRepository.findByUsernameAndPasswordAndDatastatus( || loginUser.isAdmin()) {
user.getUsername(), MainUtils.md5(user.getPassword()), false); try {
if (loginUser != null && StringUtils.isNotBlank(loginUser.getId())) { //****************************************
view = this.processLogin(request, loginUser, referer); //* 登录成功设置该坐席为就绪状态默认
//****************************************
// 自动登录 // https://gitlab.chatopera.com/chatopera/cosinee.w4l/issues/306
if (StringUtils.equals("1", sla)) { final AgentStatus agentStatus = agentProxy.resolveAgentStatusByAgentnoAndOrgi(
Cookie flagid = new Cookie( loginUser.getId(), orgi, loginUser.getSkills());
Constants.CSKEFU_SYSTEM_COOKIES_FLAG, MainUtils.encryption(loginUser.getId())); agentStatus.setBusy(false);
flagid.setMaxAge(7 * 24 * 60 * 60); agentProxy.ready(loginUser, agentStatus, false);
response.addCookie(flagid);
} // 工作状态记录
acdWorkMonitor.recordAgentStatus(agentStatus.getAgentno(),
// add authorization code for rest api agentStatus.getUsername(),
final String orgi = loginUser.getOrgi(); agentStatus.getAgentno(),
String auth = MainUtils.getUUID(); user.isAdmin(), // 0代表admin
authToken.putUserByAuth(auth, loginUser); agentStatus.getAgentno(),
userRepository.save(loginUser); // 更新登录状态到数据库 MainContext.AgentStatusEnum.OFFLINE.toString(),
response.addCookie((new Cookie("authorization", auth))); MainContext.AgentStatusEnum.READY.toString(),
MainContext.AgentWorkType.MEIDIACHAT.toString(),
// 该登录用户是坐席并且具有坐席对话的角色 orgi, null);
if ((loginUser.isAgent() &&
loginUser.getRoleAuthMap().containsKey("A01") && } catch (Exception e) {
((boolean) loginUser.getRoleAuthMap().get("A01") == true)) logger.error("[login] set agent status", e);
|| loginUser.isAdmin()) { }
try { }
/**************************************** } else {
* 登录成功设置该坐席为就绪状态默认 view = request(super.createRequestPageTempletResponse("/login"));
****************************************/ if (StringUtils.isNotBlank(referer)) {
// https://gitlab.chatopera.com/chatopera/cosinee.w4l/issues/306 view.addObject("referer", referer);
final AgentStatus agentStatus = agentProxy.resolveAgentStatusByAgentnoAndOrgi( }
loginUser.getId(), orgi, loginUser.getSkills()); view.addObject("msg", "0");
agentStatus.setBusy(false); }
agentProxy.ready(loginUser, agentStatus, false); }
}
// 工作状态记录 SystemConfig systemConfig = MainUtils.getSystemConfig();
acdWorkMonitor.recordAgentStatus(agentStatus.getAgentno(), if (systemConfig != null && systemConfig.isEnableregorgi()) {
agentStatus.getUsername(), view.addObject("show", true);
agentStatus.getAgentno(), }
user.isAdmin(), // 0代表admin if (systemConfig != null) {
agentStatus.getAgentno(), view.addObject("systemConfig", systemConfig);
MainContext.AgentStatusEnum.OFFLINE.toString(), }
MainContext.AgentStatusEnum.READY.toString(),
MainContext.AgentWorkType.MEIDIACHAT.toString(), return view;
orgi, null); }
} catch (Exception e) { /**
logger.error("[login] set agent status", e); * 处理登录事件
} */
} private ModelAndView processLogin(final HttpServletRequest request, final User loginUser, String referer) {
} else { ModelAndView view = new ModelAndView();
view = request(super.createRequestPageTempletResponse("/login")); if (loginUser != null) {
if (StringUtils.isNotBlank(referer)) { // 设置登录用户的状态
view.addObject("referer", referer); loginUser.setLogin(true);
} // 更新redis session信息用以支持sso
view.addObject("msg", "0"); agentSessionProxy.updateUserSession(
} loginUser.getId(), MainUtils.getContextID(request.getSession().getId()), loginUser.getOrgi());
} loginUser.setSessionid(MainUtils.getContextID(request.getSession().getId()));
}
SystemConfig systemConfig = MainUtils.getSystemConfig();
if (systemConfig != null && systemConfig.isEnableregorgi()) { if (StringUtils.isNotBlank(referer)) {
view.addObject("show", true); view = new ModelAndView("redirect:" + referer);
} } else {
if (systemConfig != null) { view = new ModelAndView("redirect:/");
view.addObject("systemConfig", systemConfig); }
}
// 登录成功 判断是否进入多租户页面
return view; SystemConfig systemConfig = MainUtils.getSystemConfig();
} if (systemConfig != null && systemConfig.isEnabletneant() && systemConfig.isTenantconsole() && !loginUser.isAdmin()) {
view = new ModelAndView("redirect:/apps/tenant/index");
/** }
* 处理登录事件 List<UserRole> userRoleList = userRoleRes.findByOrgiAndUser(loginUser.getOrgi(), loginUser);
* if (userRoleList != null && userRoleList.size() > 0) {
* @param request for (UserRole userRole : userRoleList) {
* @param loginUser loginUser.getRoleList().add(userRole.getRole());
* @param referer }
* @return }
*/
private ModelAndView processLogin(final HttpServletRequest request, final User loginUser, String referer) { // 获取用户部门以及下级部门
ModelAndView view = new ModelAndView(); userProxy.attachOrgansPropertiesForUser(loginUser);
if (loginUser != null) {
// 设置登录用户的状态 // 添加角色信息
loginUser.setLogin(true); userProxy.attachRolesMap(loginUser);
// 更新redis session信息用以支持sso
agentSessionProxy.updateUserSession( loginUser.setLastlogintime(new Date());
loginUser.getId(), MainUtils.getContextID(request.getSession().getId()), loginUser.getOrgi()); if (StringUtils.isNotBlank(loginUser.getId())) {
loginUser.setSessionid(MainUtils.getContextID(request.getSession().getId())); userRepository.save(loginUser);
}
if (StringUtils.isNotBlank(referer)) { super.setUser(request, loginUser);
view = new ModelAndView("redirect:" + referer); // 当前用户 企业id为空 调到创建企业页面
} else { if (StringUtils.isBlank(loginUser.getOrgid())) {
view = new ModelAndView("redirect:/"); view = new ModelAndView("redirect:/apps/organization/add.html");
} }
}
// 登录成功 判断是否进入多租户页面 return view;
SystemConfig systemConfig = MainUtils.getSystemConfig(); }
if (systemConfig != null && systemConfig.isEnabletneant() && systemConfig.isTenantconsole() && !loginUser.isAdmin()) {
view = new ModelAndView("redirect:/apps/tenant/index");
} /**
List<UserRole> userRoleList = userRoleRes.findByOrgiAndUser(loginUser.getOrgi(), loginUser); * 登出用户
if (userRoleList != null && userRoleList.size() > 0) { * code代表登出的原因
for (UserRole userRole : userRoleList) { *
loginUser.getRoleList().add(userRole.getRole()); * @param code 登出的代码
} */
} @RequestMapping("/logout")
public String logout(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "code", required = false) String code) {
// 获取用户部门以及下级部门 request.getSession().removeAttribute(Constants.USER_SESSION_NAME);
userProxy.attachOrgansPropertiesForUser(loginUser); request.getSession().invalidate();
Cookie[] cookies = request.getCookies();
// 添加角色信息 if (cookies != null) {
userProxy.attachRolesMap(loginUser); for (Cookie cookie : cookies) {
if (cookie != null && StringUtils.isNotBlank(cookie.getName()) && StringUtils.isNotBlank(
loginUser.setLastlogintime(new Date()); cookie.getValue())) {
if (StringUtils.isNotBlank(loginUser.getId())) { if (cookie.getName().equals(Constants.CSKEFU_SYSTEM_COOKIES_FLAG)) {
userRepository.save(loginUser); cookie.setMaxAge(0);
} response.addCookie(cookie);
}
super.setUser(request, loginUser); }
// 当前用户 企业id为空 调到创建企业页面 }
if (StringUtils.isBlank(loginUser.getOrgid())) { }
view = new ModelAndView("redirect:/apps/organization/add.html");
} if (StringUtils.isNotBlank(code)) {
} return "redirect:/?msg=" + code;
return view; }
}
return "redirect:/";
}
/**
* 登出用户 @RequestMapping(value = "/register")
* code代表登出的原因 @Menu(type = "apps", subtype = "user", access = true)
* public ModelAndView register(HttpServletRequest request, @Valid String msg) {
* @param request ModelAndView view = request(super.createRequestPageTempletResponse("redirect:/"));
* @param response if (request.getSession(true).getAttribute(Constants.USER_SESSION_NAME) == null) {
* @param code 登出的代码 view = request(super.createRequestPageTempletResponse("/register"));
* @return }
*/ if (StringUtils.isNotBlank(msg)) {
@RequestMapping("/logout") view.addObject("msg", msg);
public String logout(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "code", required = false) String code) throws UnsupportedEncodingException { }
final User user = super.getUser(request); return view;
request.getSession().removeAttribute(Constants.USER_SESSION_NAME); }
request.getSession().invalidate();
Cookie[] cookies = request.getCookies(); @RequestMapping("/addAdmin")
if (cookies != null) { @Menu(type = "apps", subtype = "user", access = true)
for (Cookie cookie : cookies) { public ModelAndView addAdmin(HttpServletRequest request, @Valid User user) {
if (cookie != null && StringUtils.isNotBlank(cookie.getName()) && StringUtils.isNotBlank( String msg = validUser(user);
cookie.getValue())) { if (StringUtils.isNotBlank(msg)) {
if (cookie.getName().equals(Constants.CSKEFU_SYSTEM_COOKIES_FLAG)) { return request(super.createRequestPageTempletResponse("redirect:/register.html?msg=" + msg));
cookie.setMaxAge(0); } else {
response.addCookie(cookie); user.setUname(user.getUsername());
} user.setAdmin(true);
} if (StringUtils.isNotBlank(user.getPassword())) {
} user.setPassword(MainUtils.md5(user.getPassword()));
} }
user.setOrgi(super.getOrgiByTenantshare(request));
if (StringUtils.isNotBlank(code)) { /*if(StringUtils.isNotBlank(super.getUser(request).getOrgid())) {
return "redirect:/?msg=" + code; user.setOrgid(super.getUser(request).getOrgid());
} }else {
user.setOrgid(MainContext.SYSTEM_ORGI);
return "redirect:/"; }*/
} userRepository.save(user);
OnlineUserProxy.clean(super.getOrgi(request));
@RequestMapping(value = "/register")
@Menu(type = "apps", subtype = "user", access = true) }
public ModelAndView register(HttpServletRequest request, HttpServletResponse response, @Valid String msg) { ModelAndView view = this.processLogin(request, user, "");
ModelAndView view = request(super.createRequestPageTempletResponse("redirect:/")); //当前用户 企业id为空 调到创建企业页面
if (request.getSession(true).getAttribute(Constants.USER_SESSION_NAME) == null) { if (StringUtils.isBlank(user.getOrgid())) {
view = request(super.createRequestPageTempletResponse("/register")); view = request(super.createRequestPageTempletResponse("redirect:/apps/organization/add.html"));
} }
if (StringUtils.isNotBlank(msg)) { return view;
view.addObject("msg", msg); }
}
return view; private String validUser(User user) {
} String msg = "";
User tempUser = userRepository.findByUsernameAndDatastatus(user.getUsername(), false);
@RequestMapping("/addAdmin") if (tempUser != null) {
@Menu(type = "apps", subtype = "user", access = true) msg = "username_exist";
public ModelAndView addAdmin(HttpServletRequest request, HttpServletResponse response, @Valid User user) { return msg;
String msg = ""; }
msg = validUser(user); tempUser = userRepository.findByEmailAndDatastatus(user.getEmail(), false);
if (StringUtils.isNotBlank(msg)) { if (tempUser != null) {
return request(super.createRequestPageTempletResponse("redirect:/register.html?msg=" + msg)); msg = "email_exist";
} else { return msg;
user.setUname(user.getUsername()); }
user.setAdmin(true); tempUser = userRepository.findByMobileAndDatastatus(user.getMobile(), false);
if (StringUtils.isNotBlank(user.getPassword())) { if (tempUser != null) {
user.setPassword(MainUtils.md5(user.getPassword())); msg = "mobile_exist";
} return msg;
user.setOrgi(super.getOrgiByTenantshare(request)); }
/*if(StringUtils.isNotBlank(super.getUser(request).getOrgid())) { return msg;
user.setOrgid(super.getUser(request).getOrgid()); }
}else { }
user.setOrgid(MainContext.SYSTEM_ORGI);
}*/
userRepository.save(user);
OnlineUserProxy.clean(super.getOrgi(request));
}
ModelAndView view = this.processLogin(request, user, "");
//当前用户 企业id为空 调到创建企业页面
if (StringUtils.isBlank(user.getOrgid())) {
view = request(super.createRequestPageTempletResponse("redirect:/apps/organization/add.html"));
}
return view;
}
private String validUser(User user) {
String msg = "";
User tempUser = userRepository.findByUsernameAndDatastatus(user.getUsername(), false);
if (tempUser != null) {
msg = "username_exist";
return msg;
}
tempUser = userRepository.findByEmailAndDatastatus(user.getEmail(), false);
if (tempUser != null) {
msg = "email_exist";
return msg;
}
tempUser = userRepository.findByMobileAndDatastatus(user.getMobile(), false);
if (tempUser != null) {
msg = "mobile_exist";
return msg;
}
return msg;
}
}

View File

@ -23,11 +23,11 @@ import com.chatopera.cc.persistence.repository.UserRepository;
import com.chatopera.cc.persistence.repository.UserRoleRepository; import com.chatopera.cc.persistence.repository.UserRoleRepository;
import com.chatopera.cc.proxy.OnlineUserProxy; import com.chatopera.cc.proxy.OnlineUserProxy;
import com.chatopera.cc.util.Menu; import com.chatopera.cc.util.Menu;
import org.slf4j.Logger; import lombok.RequiredArgsConstructor;
import org.slf4j.LoggerFactory; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@ -35,28 +35,27 @@ import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid; import javax.validation.Valid;
import java.io.IOException;
import java.util.List; import java.util.List;
/** /**
* @author 程序猿DD * @author <a href="http://blog.didispace.com>程序猿DD</a>
* @version 1.0.0 * @version 1.0.0
* @blog http://blog.didispace.com
*/ */
@Slf4j
@Controller @Controller
@RequestMapping("/admin/user") @RequestMapping("/admin/user")
@RequiredArgsConstructor
public class UsersController extends Handler { public class UsersController extends Handler {
private final static Logger logger = LoggerFactory.getLogger(UsersController.class);
@Autowired @NonNull
private UserRepository userRepository; private final UserRepository userRepository;
@Autowired @NonNull
private UserRoleRepository userRoleRes; private final UserRoleRepository userRoleRes;
@RequestMapping("/index") @RequestMapping("/index")
@Menu(type = "admin", subtype = "user") @Menu(type = "admin", subtype = "user")
public ModelAndView index(ModelMap map, HttpServletRequest request) throws IOException { public ModelAndView index(ModelMap map, HttpServletRequest request) {
map.addAttribute( map.addAttribute(
"userList", "userList",
userRepository.findByDatastatusAndOrgiAndOrgidAndSuperadminNot( userRepository.findByDatastatusAndOrgiAndOrgidAndSuperadminNot(
@ -70,20 +69,20 @@ public class UsersController extends Handler {
Sort.Direction.ASC, Sort.Direction.ASC,
"createtime" "createtime"
) )
) )
); );
return request(super.createAdminTempletResponse("/admin/user/index")); return request(super.createAdminTempletResponse("/admin/user/index"));
} }
@RequestMapping("/add") @RequestMapping("/add")
@Menu(type = "admin", subtype = "user") @Menu(type = "admin", subtype = "user")
public ModelAndView add(ModelMap map, HttpServletRequest request) { public ModelAndView add() {
return request(super.createRequestPageTempletResponse("/admin/user/add")); return request(super.createRequestPageTempletResponse("/admin/user/add"));
} }
@RequestMapping("/edit") @RequestMapping("/edit")
@Menu(type = "admin", subtype = "user") @Menu(type = "admin", subtype = "user")
public ModelAndView edit(ModelMap map, HttpServletRequest request, @Valid String id) { public ModelAndView edit(HttpServletRequest request, @Valid String id) {
ModelAndView view = request(super.createRequestPageTempletResponse("/admin/user/edit")); ModelAndView view = request(super.createRequestPageTempletResponse("/admin/user/edit"));
view.addObject("userData", userRepository.findByIdAndOrgi(id, super.getOrgiByTenantshare(request))); view.addObject("userData", userRepository.findByIdAndOrgi(id, super.getOrgiByTenantshare(request)));
return view; return view;
@ -95,7 +94,7 @@ public class UsersController extends Handler {
String msg = "admin_user_delete"; String msg = "admin_user_delete";
if (user != null) { if (user != null) {
List<UserRole> userRole = userRoleRes.findByOrgiAndUser(super.getOrgiByTenantshare(request), user); List<UserRole> userRole = userRoleRes.findByOrgiAndUser(super.getOrgiByTenantshare(request), user);
userRoleRes.delete(userRole); //删除用户的时候同时删除用户对应的 userRoleRes.deleteAll(userRole); //删除用户的时候同时删除用户对应的
user = userRepository.getOne(user.getId()); user = userRepository.getOne(user.getId());
user.setDatastatus(true); user.setDatastatus(true);
userRepository.save(user); userRepository.save(user);

View File

@ -1,119 +1,110 @@
/* /*
* Copyright (C) 2017 优客服-多渠道客服系统 * Copyright (C) 2017 优客服-多渠道客服系统
* Modifications copyright (C) 2018-2019 Chatopera Inc, <https://www.chatopera.com> * Modifications copyright (C) 2018-2019 Chatopera Inc, <https://www.chatopera.com>
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.chatopera.cc.controller.api.auth; package com.chatopera.cc.controller.api.auth;
import com.chatopera.cc.basic.MainUtils; import com.chatopera.cc.basic.MainUtils;
import com.chatopera.cc.basic.auth.AuthToken; import com.chatopera.cc.basic.auth.AuthToken;
import com.chatopera.cc.cache.Cache; import com.chatopera.cc.controller.Handler;
import com.chatopera.cc.controller.Handler; import com.chatopera.cc.model.User;
import com.chatopera.cc.model.User; import com.chatopera.cc.model.UserRole;
import com.chatopera.cc.model.UserRole; import com.chatopera.cc.persistence.repository.UserRepository;
import com.chatopera.cc.persistence.repository.UserRepository; import com.chatopera.cc.persistence.repository.UserRoleRepository;
import com.chatopera.cc.persistence.repository.UserRoleRepository; import com.chatopera.cc.util.Menu;
import com.chatopera.cc.util.Menu; import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils; import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger; import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus; import org.springframework.lang.NonNull;
import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponse; import javax.validation.Valid;
import javax.validation.Valid; import java.util.Date;
import java.util.Date; import java.util.List;
import java.util.List;
/**
/** * 账号密码登录
* 账号密码登录 */
*/ @Slf4j
@RestController @RestController
@RequestMapping("/tokens") @RequestMapping("/tokens")
public class ApiLoginController extends Handler { @RequiredArgsConstructor
private final static Logger logger = LoggerFactory.getLogger(ApiLoginController.class); public class ApiLoginController extends Handler {
@Autowired @NonNull
private UserRepository userRepository; private final UserRepository userRepository;
@Autowired @NonNull
private UserRoleRepository userRoleRes; private final UserRoleRepository userRoleRes;
@Autowired @NonNull
private Cache cache; private final AuthToken authToken;
@Autowired /**
private AuthToken authToken; * 登录服务传入登录账号和密码
*/
/** @SuppressWarnings("rawtypes")
* 登录服务传入登录账号和密码 @RequestMapping(method = RequestMethod.POST)
* @Menu(type = "apps", subtype = "token", access = true)
* @param request public ResponseEntity login(HttpServletResponse response, @Valid String username, @Valid String password) {
* @param response User loginUser = userRepository.findByUsernameAndPassword(username, MainUtils.md5(password));
* @param username ResponseEntity entity;
* @param password if (loginUser != null && !StringUtils.isBlank(loginUser.getId())) {
* @return loginUser.setLogin(true);
*/ List<UserRole> userRoleList = userRoleRes.findByOrgiAndUser(loginUser.getOrgi(), loginUser);
@SuppressWarnings("rawtypes") if (userRoleList != null && userRoleList.size() > 0) {
@RequestMapping(method = RequestMethod.POST) for (UserRole userRole : userRoleList) {
@Menu(type = "apps", subtype = "token", access = true) loginUser.getRoleList().add(userRole.getRole());
public ResponseEntity login(HttpServletRequest request, HttpServletResponse response, @Valid String username, @Valid String password) { }
User loginUser = userRepository.findByUsernameAndPassword(username, MainUtils.md5(password)); }
ResponseEntity entity = null; loginUser.setLastlogintime(new Date());
if (loginUser != null && !StringUtils.isBlank(loginUser.getId())) { if (!StringUtils.isBlank(loginUser.getId())) {
loginUser.setLogin(true); userRepository.save(loginUser);
List<UserRole> userRoleList = userRoleRes.findByOrgiAndUser(loginUser.getOrgi(), loginUser); }
if (userRoleList != null && userRoleList.size() > 0) { String auth = MainUtils.getUUID();
for (UserRole userRole : userRoleList) { authToken.putUserByAuth(auth, loginUser);
loginUser.getRoleList().add(userRole.getRole());
} entity = new ResponseEntity<>(auth, HttpStatus.OK);
} response.addCookie(new Cookie("authorization", auth));
loginUser.setLastlogintime(new Date()); } else {
if (!StringUtils.isBlank(loginUser.getId())) { entity = new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
userRepository.save(loginUser); }
} return entity;
String auth = MainUtils.getUUID(); }
authToken.putUserByAuth(auth, loginUser);
@SuppressWarnings("rawtypes")
entity = new ResponseEntity<>(auth, HttpStatus.OK); @RequestMapping(method = RequestMethod.GET)
response.addCookie(new Cookie("authorization", auth)); @Menu(type = "apps", subtype = "token", access = true)
} else { public ResponseEntity error(HttpServletRequest request) {
entity = new ResponseEntity<>(HttpStatus.UNAUTHORIZED); User data = super.getUser(request);
} return new ResponseEntity<>(data, data != null ? HttpStatus.OK : HttpStatus.UNAUTHORIZED);
return entity; }
}
@SuppressWarnings("rawtypes")
@SuppressWarnings("rawtypes") @RequestMapping(method = RequestMethod.DELETE)
@RequestMapping(method = RequestMethod.GET) public ResponseEntity logout(@RequestHeader(value = "authorization") String authorization) {
@Menu(type = "apps", subtype = "token", access = true) authToken.deleteUserByAuth(authorization);
public ResponseEntity error(HttpServletRequest request) { return new ResponseEntity<>(HttpStatus.OK);
User data = super.getUser(request); }
return new ResponseEntity<>(data, data != null ? HttpStatus.OK : HttpStatus.UNAUTHORIZED);
} }
@SuppressWarnings("rawtypes")
@RequestMapping(method = RequestMethod.DELETE)
public ResponseEntity logout(HttpServletRequest request, @RequestHeader(value = "authorization") String authorization) {
authToken.deleteUserByAuth(authorization);
return new ResponseEntity<>(HttpStatus.OK);
}
}

View File

@ -1,42 +1,42 @@
/* /*
* Copyright (C) 2017 优客服-多渠道客服系统 * Copyright (C) 2017 优客服-多渠道客服系统
* Modifications copyright (C) 2018-2019 Chatopera Inc, <https://www.chatopera.com> * Modifications copyright (C) 2018-2019 Chatopera Inc, <https://www.chatopera.com>
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.chatopera.cc.persistence.repository; package com.chatopera.cc.persistence.repository;
import com.chatopera.cc.model.Role; import com.chatopera.cc.model.Role;
import com.chatopera.cc.model.User; import com.chatopera.cc.model.User;
import com.chatopera.cc.model.UserRole; import com.chatopera.cc.model.UserRole;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import java.util.List; import java.util.List;
public interface UserRoleRepository extends JpaRepository<UserRole, String> public interface UserRoleRepository extends JpaRepository<UserRole, String> {
{
Page<UserRole> findByOrgiAndRole(String orgi, Role role, Pageable paramPageable);
Page<UserRole> findByOrgiAndRole(String orgi, Role role, Pageable paramPageable);
List<UserRole> findByOrgiAndRole(String orgi, Role role);
List<UserRole> findByOrgiAndRole(String orgi, Role role);
List<UserRole> findByOrgiAndUser(String orgi, User user);
List<UserRole> findByOrgiAndUser(String orgi, User user);
@SuppressWarnings("SpringDataRepositoryMethodReturnTypeInspection")
@Query(value = "SELECT u.user_id FROM uk_userrole u WHERE u.orgi = ?1 AND u.role_id = ?2", nativeQuery = true) @Query(value = "SELECT u.user_id FROM uk_userrole u WHERE u.orgi = ?1 AND u.role_id = ?2", nativeQuery = true)
List<String> findByOrgiAndRoleId(final String orgi, final String roleid); List<String> findByOrgiAndRoleId(final String orgi, final String roleid);
} }