浏览代码

增加地址查询

hym 4 年之前
父节点
当前提交
1c35633ca2

+ 58 - 0
smart-city-platform/src/main/java/com/bz/smart_city/commom/security/platform/PlatformAuthenticationProvider.java

@@ -0,0 +1,58 @@
+package com.bz.smart_city.commom.security.platform;
+
+import com.bz.smart_city.commom.security.mobile.MobileLoginAuthenticationToken;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.authentication.InternalAuthenticationServiceException;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.util.Assert;
+
+@Slf4j
+public class PlatformAuthenticationProvider implements AuthenticationProvider {
+
+    private UserDetailsService userDetailsService;
+
+    private PasswordEncoder passwordEncoder;
+
+    @Override
+    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+        MobileLoginAuthenticationToken authenticationToken = (MobileLoginAuthenticationToken)authentication;
+        UserDetails userDetails = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
+        if (userDetails == null) {
+            throw new InternalAuthenticationServiceException("无法获取用户信息");
+        }
+        String presentedPassword = authenticationToken.getCredentials().toString();
+
+        MobileLoginAuthenticationToken authenticationTokenReslut = new MobileLoginAuthenticationToken(userDetails,authenticationToken.getCredentials(),userDetails.getAuthorities());
+
+        authenticationTokenReslut.setDetails(authenticationToken.getDetails());
+
+        return authenticationTokenReslut;
+    }
+
+    @Override
+    public boolean supports(Class<?> authentication) {
+        return MobileLoginAuthenticationToken.class.isAssignableFrom(authentication);
+    }
+
+    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
+        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
+        this.passwordEncoder = passwordEncoder;
+    }
+
+    protected PasswordEncoder getPasswordEncoder() {
+        return passwordEncoder;
+    }
+
+    public UserDetailsService getUserDetailsService() {
+        return userDetailsService;
+    }
+
+    public void setUserDetailsService(UserDetailsService userDetailsService) {
+        this.userDetailsService = userDetailsService;
+    }
+}

+ 54 - 0
smart-city-platform/src/main/java/com/bz/smart_city/commom/security/platform/PlatformCheckUserFilter.java

@@ -0,0 +1,54 @@
+package com.bz.smart_city.commom.security.platform;
+
+import com.bz.smart_city.commom.util.ByteArrayUtils;
+import com.bz.smart_city.commom.util.RedisUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.ServletWebRequest;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+
+/**
+ * 验证码验证
+ */
+@Component
+public class PlatformCheckUserFilter extends OncePerRequestFilter {
+
+    @Autowired
+    @Qualifier("userAuthenticationFailureHandler")
+    private AuthenticationFailureHandler userAuthenticationFailureHandler;
+    @Value("${server.servlet.context-path}")
+    private String contextPath;
+    @Autowired
+    RedisUtil redisUtil;
+    @Value("${spring.profiles.active}")
+    private String active;
+
+    @Override
+    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
+        if (StringUtils.equals(contextPath+"/user/platformLogin", request.getRequestURI()) && StringUtils.equalsIgnoreCase(request.getMethod(), "post")) {
+            try {
+                validate(new ServletWebRequest(request));
+            } catch (SmsCodeException e) {
+                userAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
+                return;
+            }
+        }
+        filterChain.doFilter(request, response);
+    }
+
+    private void validate(ServletWebRequest servletWebRequest) {
+
+        String mobile = servletWebRequest.getParameter("code");
+    }
+}

+ 94 - 0
smart-city-platform/src/main/java/com/bz/smart_city/commom/security/platform/PlatformLoginAuthenticationFilter.java

@@ -0,0 +1,94 @@
+package com.bz.smart_city.commom.security.platform;
+
+import com.bz.smart_city.commom.security.mobile.MobileLoginAuthenticationToken;
+import org.springframework.security.authentication.AuthenticationServiceException;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
+import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
+import org.springframework.util.Assert;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class PlatformLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+    // ~ Static fields/initializers
+    // =====================================================================================
+
+    public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "code";
+    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
+
+    private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY;
+    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
+    private boolean postOnly = true;
+
+    // ~ Constructors
+    // ===================================================================================================
+
+    public PlatformLoginAuthenticationFilter() {
+        super(new AntPathRequestMatcher("/user/platformLogin", "POST"));
+    }
+
+    // ~ Methods
+    // ========================================================================================================
+
+    @Override
+    public Authentication attemptAuthentication(HttpServletRequest request,
+                                                HttpServletResponse response) throws AuthenticationException {
+        if (postOnly && !request.getMethod().equals("POST")) {
+            throw new AuthenticationServiceException(
+                    "Authentication method not supported: " + request.getMethod());
+        }
+
+        String mobile = obtainMobile(request);
+
+
+
+        mobile = mobile.trim();
+
+        MobileLoginAuthenticationToken authRequest = new MobileLoginAuthenticationToken(mobile, "");
+
+        // Allow subclasses to set the "details" property
+        setDetails(request, authRequest);
+
+        return this.getAuthenticationManager().authenticate(authRequest);
+    }
+
+    private String obtainMobile(HttpServletRequest request) {
+        return request.getParameter(mobileParameter);
+    }
+
+
+    protected String obtainPassword(HttpServletRequest request) {
+        return request.getParameter(passwordParameter);
+    }
+
+
+    protected void setDetails(HttpServletRequest request, MobileLoginAuthenticationToken authRequest) {
+        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
+    }
+
+
+    public void setMobileParameter(String mobileParameter) {
+        Assert.hasText(mobileParameter, "Username parameter must not be empty or null");
+        this.mobileParameter = mobileParameter;
+    }
+
+
+    public void setPasswordParameter(String passwordParameter) {
+        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
+        this.passwordParameter = passwordParameter;
+    }
+
+    public void setPostOnly(boolean postOnly) {
+        this.postOnly = postOnly;
+    }
+
+    public final String getmobileParameter() {
+        return mobileParameter;
+    }
+
+    public final String getPasswordParameter() {
+        return passwordParameter;
+    }
+}

+ 207 - 0
smart-city-platform/src/main/java/com/bz/smart_city/commom/security/platform/PlatformLoginUserDetailService.java

@@ -0,0 +1,207 @@
+package com.bz.smart_city.commom.security.platform;
+
+import com.alibaba.fastjson.JSONObject;
+import com.bz.smart_city.commom.security.validate.ValidateCodeException;
+import com.bz.smart_city.commom.util.ByteArrayUtils;
+import com.bz.smart_city.commom.util.RedisUtil;
+import com.bz.smart_city.dao.*;
+import com.bz.smart_city.dto.LoginUser;
+import com.bz.smart_city.dto.SiteUserDto;
+import com.bz.smart_city.entity.*;
+import com.bz.smart_city.service.PermissionService;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.authentication.DisabledException;
+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 org.springframework.web.client.RestTemplate;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static com.google.common.collect.Lists.newArrayList;
+
+@Component
+public class PlatformLoginUserDetailService implements UserDetailsService {
+    @Resource
+    private UserMapper userMapper;
+    @Resource
+    private PermissionService permissionService;
+    @Resource
+    private SiteUserMapper siteUserMapper;
+    @Resource
+    private SiteMapper siteMapper;
+    @Resource
+    private ProgramMapper programMapper;
+    @Resource
+    private ProgramItemMapper programItemMapper;
+    @Resource
+    private CustomerMapper customerMapper;
+    @Autowired
+    private RedisUtil redisUtil;
+
+
+    private String appId="1001";
+
+
+    private String appSecret="123456";
+     private String url="http://192.168.0.113:8081/user-auth/user/getUniqId?appId={appId}&appSecret={appSecret}&code={code}";
+
+    private String sendApiReQuest(String path ,  Map<String, Object> map){
+
+        RestTemplate restTemplate=new RestTemplate();
+        ResponseEntity<String> res = restTemplate.getForEntity(path,String.class,map);
+        String body = res.getBody();
+        JSONObject info = JSONObject.parseObject(body);
+        String result=null;
+        if(info.getInteger("status")==0){
+            result=info.getString("data");
+        }
+        return result;
+    }
+    @Override
+    public UserDetails loadUserByUsername(String code) throws UsernameNotFoundException {
+        JSONObject jsonObject=new JSONObject();
+        jsonObject.put("appId",appId);
+        jsonObject.put("appSecret",appSecret);
+        jsonObject.put("code",code);
+        String uniqId = sendApiReQuest(url, jsonObject);
+
+        User user =null;// userMapper.findUserByUniqId(uniqId);
+        if (user == null) {
+            throw new UsernameNotFoundException("该用户不存在");
+        }
+
+        //判断是否禁用
+        if (user.getStatus() == 2) {
+            throw new DisabledException("账号已被禁用");
+        }
+        LoginUser loginUser = new LoginUser();
+        BeanUtils.copyProperties(user, loginUser);
+
+        Map<Integer, List<Permission>> permissionMap = new HashMap<>();
+        Map<Integer, List<ProgramItem>> datePermissionMap = new HashMap<>();
+        if (user.getIsSuperAdmin() == 1) {
+            //超级管理员的权限
+            List<Permission> permissions = permissionService.getPermissionBySuperAdmin();
+            permissionMap.put(0, permissions);
+            loginUser.setCurrentSiteId(0);
+            loginUser.setType(1);
+        } else  {
+            //站点管理员(多站点)
+            Integer siteId = null;
+            List<Site> siteList = siteUserMapper.getSiteByUserId(user.getId());
+            List<SiteUserDto> siteV2List = siteUserMapper.getSiteByUserIdV2(user.getId());
+            if (siteList == null || siteList.size() == 0) {
+                throw new ValidateCodeException("该用户未关联站点");
+            }
+
+            siteV2List.forEach(site -> {
+                if(site.getUserType() == 2){
+                    List<Permission> permissions = permissionService.getPermissionBySiteAdminV2(site.getId(),site.getType());;
+                    permissionMap.put(site.getId(), permissions);
+                }else {
+                    permissionMap.put(site.getId(), permissionService.getPermissionByUserId(user.getId(), site.getId()));
+                }
+
+
+                List<ProgramItem> programItemList = programItemMapper.getBySiteIdAndUserId(site.getId(), user.getId());
+                if (programItemList != null && programItemList.size() > 0) {
+                    datePermissionMap.put(site.getId(), programItemList);
+                }
+            });
+            permissionMap.put(0, newArrayList());
+
+
+            String key = "useSelectSiteId:" + user.getId();
+            byte[] useSelectSiteIdByte = redisUtil.get(key.getBytes());
+            if (useSelectSiteIdByte != null) {
+                Integer useSelectSiteId = (Integer) ByteArrayUtils.bytesToObject(useSelectSiteIdByte).get();
+                if (!checkSite(siteList, useSelectSiteId)) {
+                    siteId = siteList.size()>0?siteList.get(0).getId():0;
+                    //保存redis
+                    redisUtil.setExpire(key.getBytes(), ByteArrayUtils.objectToBytes(siteId).get());
+                }else {
+                    siteId = useSelectSiteId;
+                }
+            }else {
+                siteId = siteList.size()>0?siteList.get(0).getId():0;
+                //保存redis
+                redisUtil.setExpire(key.getBytes(), ByteArrayUtils.objectToBytes(siteId).get());
+            }
+
+
+            SiteUser siteUser = siteUserMapper.findBySiteIdAndUserId(siteId,user.getId());
+
+            loginUser.setType(siteUser.getType());
+            loginUser.setOrgId(siteUser.getOrganId());
+            loginUser.setSiteId(siteId);
+            loginUser.setCurrentSiteId(siteId);
+            loginUser.setSiteList(siteList);
+            loginUser.setIsSiteAdmin(siteUser.getIsAdmin());//站点管理员
+            loginUser.setSiteType(checkSiteType(siteList,siteId));
+
+            Site site = siteMapper.findById(siteId);
+            loginUser.setCustomerId(site.getCustomerId());
+            loginUser.setCustomerName(site.getCustomerName());
+            loginUser.setOrgId(siteUser.getOrganId());
+
+            //查询数据权限
+
+        }
+
+        /*else {
+            //查询平台用户的站点
+            Site site = siteUserMapper.findSiteByUserId(user.getId());
+            if (site != null) {
+                List<Site> siteList = newArrayList();
+                siteList.add(site);
+                loginUser.setSiteId(site.getId());
+                loginUser.setCurrentSiteId(site.getId());
+                loginUser.setSiteList(siteList);
+
+                //查询功能权限
+                permissionMap.put(site.getId(), permissionService.getPermissionByUserId(user.getId(), null));
+                //查询数据权限
+                datePermissionMap.put(site.getId(), programItemMapper.getBySiteIdAndUserId(site.getId(), user.getId()));
+            }
+        }*/
+
+
+        /*Customer customer = null;
+        if(loginUser.getOrgId()!=null) {
+            customer = customerMapper.findByOrgId(loginUser.getOrgId());
+            //loginUser.setOrgId(user.getOrganId());
+        }
+        if(customer!=null)
+          loginUser.setCustomerId(customer.getId());*/
+        loginUser.setPermissionMap(permissionMap);
+        loginUser.setDataPermissionMap(datePermissionMap);
+        return loginUser;
+    }
+
+    //判断siteList中是否包含siteId
+    private boolean checkSite(List<Site> siteList, Integer siteId) {
+        return siteList.parallelStream().anyMatch(site -> site.getId().equals(siteId));
+    }
+
+    private Integer checkSiteType(List<Site> siteList, Integer siteId) {
+        Integer siteType = null;
+        for (Site site : siteList) {
+            if(site.getId().equals(siteId)){
+                siteType =  site.getType();
+                break;
+            }
+        }
+        return siteType;
+    }
+}

+ 50 - 0
smart-city-platform/src/main/java/com/bz/smart_city/commom/security/platform/PlatformSecurityConfig.java

@@ -0,0 +1,50 @@
+package com.bz.smart_city.commom.security.platform;
+
+import com.bz.smart_city.commom.security.mobile.MobileLoginUserDetailService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.context.annotation.Bean;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.web.DefaultSecurityFilterChain;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.stereotype.Component;
+
+@Component
+public class PlatformSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
+    @Autowired
+    @Qualifier("userAuthenticationSuccessHandler")
+    private AuthenticationSuccessHandler authenticationSuccessHandler;
+    @Autowired
+    @Qualifier("userAuthenticationFailureHandler")
+    private AuthenticationFailureHandler authenticationFailureHandler;
+    @Autowired
+    private PlatformLoginUserDetailService userDetailsService;
+    @Autowired
+    private PlatformCheckUserFilter smsCodeCheckUserFilter;
+    @Bean
+    public PasswordEncoder passwordEncoder() {
+        return new BCryptPasswordEncoder();
+    }
+
+
+
+    @Override
+    public void configure(HttpSecurity http) throws Exception {
+        PlatformLoginAuthenticationFilter smsCodeLoginAuthenticationFilter = new PlatformLoginAuthenticationFilter();
+        smsCodeLoginAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
+        smsCodeLoginAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
+        smsCodeLoginAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
+
+        PlatformAuthenticationProvider smsCodeLoginAuthenticationProvider = new PlatformAuthenticationProvider();
+        smsCodeLoginAuthenticationProvider.setUserDetailsService(userDetailsService);
+        http.authenticationProvider(smsCodeLoginAuthenticationProvider)
+                .addFilterAfter(smsCodeCheckUserFilter, UsernamePasswordAuthenticationFilter.class)
+                .addFilterAfter(smsCodeLoginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
+    }
+}

+ 9 - 0
smart-city-platform/src/main/java/com/bz/smart_city/commom/security/platform/SmsCodeException.java

@@ -0,0 +1,9 @@
+package com.bz.smart_city.commom.security.platform;
+
+import org.springframework.security.core.AuthenticationException;
+
+public class SmsCodeException extends AuthenticationException {
+    public SmsCodeException(String msg) {
+        super(msg);
+    }
+}

+ 1 - 1
smart-city-platform/src/main/java/com/bz/smart_city/dao/GridManagementMapper.java

@@ -92,7 +92,7 @@ public interface GridManagementMapper {
     List<Building> getBuildingByCommutity(@Param("commutityId") Integer commutityId);
 
     List<Device> getDevices(@Param("buildingId") Integer buildingId,
-                            @Param("userId") Integer userId);
+                            @Param("userId") Integer userId,@Param("address") String address);
 
     GridManagement getByDeviceId(@Param("deviceId") Long deviceId);
 }

+ 2 - 2
smart-city-platform/src/main/java/com/bz/smart_city/grid/GridManagementController.java

@@ -161,9 +161,9 @@ public class GridManagementController {
      */
     @RequestMapping(value = "getDevices", method = RequestMethod.POST)
     @ApiOperation(value = "查询建筑信息")
-    public AjaxMessage<List<Device>> getDevices(Integer buildingId,Integer userId) {
+    public AjaxMessage<List<Device>> getDevices(Integer buildingId,Integer userId,String address) {
 
-        List<Device>devices=gridManagementService.getDevices(buildingId,userId);
+        List<Device>devices=gridManagementService.getDevices(buildingId,userId,address);
 
         return new AjaxMessage<>(ResultStatus.OK, devices);
     }

+ 1 - 1
smart-city-platform/src/main/java/com/bz/smart_city/grid/GridManagementService.java

@@ -85,5 +85,5 @@ public interface GridManagementService {
 
     List<Building> getBuildingByCommutity(Integer commutityId);
 
-    List<Device> getDevices(Integer buildingId,Integer userId);
+    List<Device> getDevices(Integer buildingId, Integer userId, String address);
 }

+ 2 - 2
smart-city-platform/src/main/java/com/bz/smart_city/grid/GridManagementServiceImpl.java

@@ -145,8 +145,8 @@ public class GridManagementServiceImpl implements GridManagementService {
     }
 
     @Override
-    public List<Device> getDevices(Integer buildingId,Integer userId) {
-        List<Device> devices=gridManagementMapper.getDevices(buildingId,userId);
+    public List<Device> getDevices(Integer buildingId, Integer userId, String address) {
+        List<Device> devices=gridManagementMapper.getDevices(buildingId,userId,address);
         return devices;
     }
 

+ 3 - 0
smart-city-platform/src/main/resources/mapper/GridManagementMapper.xml

@@ -178,6 +178,9 @@
     <select id="getDevices" resultType="com.bz.smart_city.entity.Device">
         select * from sc_device where building_id=#{buildingId} and
          id not in (select distinct device_id from sc_grid_management) and status=1
+        <if test="address != null  ">
+            and loc_desc LIKE concat('%',#{address},'%')
+        </if>
     </select>
 
     <select id="getByDeviceId" resultMap="GridManagementMap">