1
0
suochencheng 7 лет назад
Родитель
Сommit
9e6549e428

+ 2 - 0
src/main/java/com/izouma/awesomeadmin/service/UserInfoService.java

@@ -36,5 +36,7 @@ public interface UserInfoService {
 
     List<String> findUserByRoleName(String roleName);
 
+    UserInfo loginWeiXin(String openId, String nickname, String sex, String headimgurl);
+
 }
 

+ 70 - 0
src/main/java/com/izouma/awesomeadmin/service/impl/UserInfoServiceImpl.java

@@ -1,5 +1,9 @@
 package com.izouma.awesomeadmin.service.impl;
 
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.text.SimpleDateFormat;
 import java.util.*;
 
 import com.izouma.awesomeadmin.constant.AppConstant;
@@ -7,6 +11,7 @@ import com.izouma.awesomeadmin.dao.DepartInfoMapper;
 import com.izouma.awesomeadmin.dao.SysAppTokenMapper;
 import com.izouma.awesomeadmin.dao.SysRoleMapper;
 import com.izouma.awesomeadmin.dto.Page;
+import com.izouma.awesomeadmin.service.OSSFileService;
 import com.izouma.awesomeadmin.shiro.AppToken;
 import com.izouma.awesomeadmin.util.MD5Util;
 import com.izouma.awesomeadmin.util.PropertiesFileLoader;
@@ -47,6 +52,9 @@ public class UserInfoServiceImpl implements UserInfoService {
     @Autowired
     private SysAppTokenMapper sysAppTokenMapper;
 
+    @Autowired
+    private OSSFileService ossFileService;
+
     @Override
     public List<UserInfo> getUserInfoList(UserInfo record) {
 
@@ -275,5 +283,67 @@ public class UserInfoServiceImpl implements UserInfoService {
             super(message);
         }
     }
+
+    @Override
+    public UserInfo loginWeiXin(String openId, String nickname, String sex, String headimgurl) {
+        logger.info("loginWeiXin");
+        try {
+            UserInfo userInfo = new UserInfo();
+            userInfo.setOpenId(openId);
+            userInfo = getUserInfo(userInfo);
+
+            if (userInfo == null) {
+                userInfo = new UserInfo();
+                userInfo.setUsername(nickname);
+                userInfo.setNickname(nickname);
+                userInfo.setSex(sex);
+                userInfo.setOpenId(openId);
+                if (StringUtils.isNotEmpty(headimgurl)) {
+                    HttpURLConnection httpUrl = null;
+                    URL iconUrl = null;
+                    try {
+                        iconUrl = new URL(headimgurl);
+                        httpUrl = (HttpURLConnection) iconUrl.openConnection();
+                        httpUrl.connect();
+                        // 图片生成名称
+                        String fileName = "";
+                        Date nowDate = new Date();
+                        // 格式化时间对象返回字符串
+                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
+                        fileName += sdf.format(nowDate);
+                        Random random = new Random();
+                        String randomCode = "";
+                        for (int i = 0; i < 8; i++) {
+                            randomCode += Integer.toString(random.nextInt(36), 36);
+                        }
+                        fileName += randomCode;
+                        String virtualPath = "awesomeAdmin/application/" + fileName + ".jpg";
+                        // item.write(new File(uploadPath + fileName));
+                        String result = ossFileService.upload(httpUrl.getInputStream(), virtualPath);
+                        System.out.println("存入照片:" + result);
+                        userInfo.setIcon(result);
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    } finally {
+                        if (httpUrl != null) {
+                            httpUrl.disconnect();
+                        }
+                    }
+                } else {
+
+                    userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
+                }
+                if (!createUserInfo(userInfo)) {
+                    return null;
+                }
+            }
+
+            return userInfo;
+
+        } catch (Exception e) {
+            logger.error("loginWeiXin", e);
+        }
+        return null;
+    }
 }
 

+ 24 - 0
src/main/java/com/izouma/awesomeadmin/shiro/WeiXinCodeRealm.java

@@ -0,0 +1,24 @@
+package com.izouma.awesomeadmin.shiro;
+
+import com.izouma.awesomeadmin.model.UserInfo;
+import org.apache.shiro.authc.AuthenticationException;
+import org.apache.shiro.authc.AuthenticationInfo;
+import org.apache.shiro.authc.AuthenticationToken;
+import org.apache.shiro.authc.SimpleAuthenticationInfo;
+
+public class WeiXinCodeRealm extends BaseRealm {
+
+    @Override
+    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
+        UserInfo userInfo = null;
+        WeiXinCodeToken weiXinCodeToken = (WeiXinCodeToken) token;
+
+        userInfo = userInfoService.loginWeiXin(weiXinCodeToken.getOpenId(), weiXinCodeToken.getNickname(), weiXinCodeToken.getSex(), weiXinCodeToken.getHeadimgurl());
+        if (userInfo == null) {
+            throw new AuthenticationException("登录失败");
+        }
+        return new SimpleAuthenticationInfo(userInfo, token.getCredentials(), this.getName());
+
+
+    }
+}

+ 93 - 0
src/main/java/com/izouma/awesomeadmin/shiro/WeiXinCodeToken.java

@@ -0,0 +1,93 @@
+package com.izouma.awesomeadmin.shiro;
+
+import org.apache.shiro.authc.HostAuthenticationToken;
+import org.apache.shiro.authc.RememberMeAuthenticationToken;
+
+public class WeiXinCodeToken implements HostAuthenticationToken, RememberMeAuthenticationToken {
+
+    private boolean rememberMe;
+    private String host;
+    private String code;
+    private String openId;
+    private String nickname;
+    private String sex;
+
+    private String headimgurl;
+
+    public WeiXinCodeToken(String code, String openId, String nickname, String sex, String headimgurl) {
+        this.code = code;
+        this.openId = openId;
+        this.nickname = nickname;
+        this.sex = sex;
+        this.headimgurl = headimgurl;
+    }
+
+    public void setRememberMe(boolean rememberMe) {
+        this.rememberMe = rememberMe;
+    }
+
+    public void setHost(String host) {
+        this.host = host;
+    }
+
+
+    public String getCode() {
+        return code;
+    }
+
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    public String getOpenId() {
+        return openId;
+    }
+
+    public void setOpenId(String openId) {
+        this.openId = openId;
+    }
+
+    @Override
+    public String getHost() {
+        return host;
+    }
+
+    @Override
+    public boolean isRememberMe() {
+        return rememberMe;
+    }
+
+    @Override
+    public Object getPrincipal() {
+        return openId;
+    }
+
+    @Override
+    public Object getCredentials() {
+        return code;
+    }
+
+    public String getSex() {
+        return sex;
+    }
+
+    public void setSex(String sex) {
+        this.sex = sex;
+    }
+
+    public String getHeadimgurl() {
+        return headimgurl;
+    }
+
+    public void setHeadimgurl(String headimgurl) {
+        this.headimgurl = headimgurl;
+    }
+
+    public String getNickname() {
+        return nickname;
+    }
+
+    public void setNickname(String nickname) {
+        this.nickname = nickname;
+    }
+}

+ 244 - 0
src/main/java/com/izouma/awesomeadmin/web/WeiXinController.java

@@ -0,0 +1,244 @@
+package com.izouma.awesomeadmin.web;
+
+import com.izouma.awesomeadmin.dto.Result;
+import com.izouma.awesomeadmin.model.UserInfo;
+import com.izouma.awesomeadmin.service.UserInfoService;
+import com.izouma.awesomeadmin.service.WeiXinService;
+import com.izouma.awesomeadmin.shiro.WeiXinCodeToken;
+import com.izouma.awesomeadmin.util.CookieUtil;
+import com.izouma.awesomeadmin.util.PropertiesFileLoader;
+import com.izouma.awesomeadmin.util.WeixinUtil;
+import org.activiti.engine.IdentityService;
+import org.apache.log4j.Logger;
+import org.apache.shiro.SecurityUtils;
+import org.apache.shiro.authc.AuthenticationException;
+import org.apache.shiro.subject.Subject;
+import org.json.JSONObject;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Map;
+
+@Controller
+@RequestMapping("/wx")
+public class WeiXinController {
+
+    private static Logger logger = Logger.getLogger(WeiXinController.class);
+
+    @Autowired
+    private WeiXinService weiXinService;
+
+    @Autowired
+    private UserInfoService userInfoService;
+
+    @Autowired
+    private IdentityService identityService;
+
+
+    @RequestMapping(value = "/getSignature", method = RequestMethod.GET)
+    @ResponseBody
+    public Map<String, String> getSignature(HttpServletRequest request) {
+
+        String shareUrl = request.getParameter("shareUrl");
+        return weiXinService.getSignature(shareUrl);
+
+    }
+
+
+    @RequestMapping(value = "/auth", method = RequestMethod.GET)
+    @ResponseBody
+    public ModelAndView auth(@RequestParam("redirectUri") String redirectUri) {
+
+        return new ModelAndView("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + PropertiesFileLoader.getProperties("weixinappid")
+                + "&redirect_uri=" + "http://xjw.izouma.com/wx/redirectLogin?redirectUri=" + redirectUri
+                + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
+    }
+
+
+    @RequestMapping(value = "/redirectLogin", method = RequestMethod.GET)
+    @ResponseBody
+    public ModelAndView redirectLogin(HttpServletRequest request, HttpServletResponse response,
+                                      @RequestParam(required = true, value = "code") String code, @RequestParam(required = false, value = "redirectUri") String redirectUri) {
+
+        ModelAndView mav = new ModelAndView("redirect:http://xjw.izouma.com/#/" + redirectUri);
+        final String APP_ID = PropertiesFileLoader.getProperties("weixinappid");
+        final String APP_SECRET = PropertiesFileLoader.getProperties("weixinsecret");
+        try {
+
+            // System.out.println("code : " + code);
+            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code
+                    + "&grant_type=authorization_code";
+            JSONObject data = WeixinUtil.loadJSON(url);
+            // System.out.println("data : " + data);
+
+            // System.out.println(json.toString());
+
+            String openId = (String) data.get("openid");
+
+            /**
+             * 新用户存储用户资料
+             */
+            String access_token = (String) data.get("access_token");
+            String userDataUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
+            JSONObject userData = WeixinUtil.loadJSON(userDataUrl);
+            String weixinInfo = userData.toString();
+            // System.out.println("userDate : " + userData);
+
+
+            System.out.println("loginUserInfo:" + weixinInfo);
+            JSONObject userJson = new JSONObject(weixinInfo);
+            System.out.println("userJson" + userJson);
+
+            String headimgurl = userJson.getString("headimgurl");
+            String sex = userJson.getInt("sex") != 0 ? "男" : "女";
+
+
+            Subject subject = SecurityUtils.getSubject();
+
+            WeiXinCodeToken weiXinCodeToken = new WeiXinCodeToken(code, openId, userJson.getString("nickname"), sex, headimgurl);
+            try {
+                subject.login(weiXinCodeToken);
+            } catch (AuthenticationException e) {
+                e.printStackTrace();
+                logger.error(e);
+            }
+            UserInfo user = (UserInfo) subject.getPrincipal();
+            identityService.setAuthenticatedUserId(user.getId().toString());
+            HttpSession session = request.getSession();
+            CookieUtil.addCookie(response, "JSESSIONID", session.getId(), 3 * 24 * 60 * 60);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            return new ModelAndView("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID + "&redirect_uri="
+                    + "http://xjw.izouma.com/wx/redirectLogin?redirectUri=" + redirectUri
+                    + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
+        }
+        return mav;
+    }
+
+
+    /**
+     * 微信身份获取,登录验证
+     *
+     * @return
+     */
+    @RequestMapping(value = "/Login", method = RequestMethod.GET)
+    @ResponseBody
+    public ModelAndView LoginService(HttpServletRequest request, HttpServletResponse response,
+                                     @RequestParam(required = true, value = "code") String code) {
+
+        ModelAndView mav = new ModelAndView("redirect:../#/");
+        final String APP_ID = PropertiesFileLoader.getProperties("weixinappid");
+        final String APP_SECRET = PropertiesFileLoader.getProperties("weixinsecret");
+        try {
+
+
+            /**
+             * 无缓存用户
+             */
+            // System.out.println("code : " + code);
+            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code
+                    + "&grant_type=authorization_code";
+            JSONObject data = WeixinUtil.loadJSON(url);
+            logger.error("Login微信身份获取,登录验证 data : " + data);
+
+            String openId = (String) data.get("openid");
+
+
+            /**
+             * 新用户存储用户资料
+             */
+            String access_token = (String) data.get("access_token");
+            String userDataUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
+            JSONObject userData = WeixinUtil.loadJSON(userDataUrl);
+            String weixinInfo = userData.toString();
+            // System.out.println("userDate : " + userData);
+
+
+            System.out.println("loginUserInfo:" + weixinInfo);
+            JSONObject userJson = new JSONObject(weixinInfo);
+            System.out.println("userJson" + userJson);
+
+            String headimgurl = userJson.getString("headimgurl");
+            String sex = userJson.getInt("sex") != 0 ? "男" : "女";
+
+            Subject subject = SecurityUtils.getSubject();
+
+            WeiXinCodeToken weiXinCodeToken = new WeiXinCodeToken(code, openId, userJson.getString("nickname"), sex, headimgurl);
+            try {
+                subject.login(weiXinCodeToken);
+            } catch (AuthenticationException e) {
+                e.printStackTrace();
+                logger.error(e);
+            }
+            UserInfo user = (UserInfo) subject.getPrincipal();
+            identityService.setAuthenticatedUserId(user.getId().toString());
+            HttpSession session = request.getSession();
+            CookieUtil.addCookie(response, "JSESSIONID", session.getId(), 3 * 24 * 60 * 60);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            return new ModelAndView("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID + "&redirect_uri="
+                    + "http://xjw.izouma.com/wx/Login" + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
+        }
+        return mav;
+    }
+
+
+    @RequestMapping(value = "/checkSubscribe", method = RequestMethod.GET)
+    @ResponseBody
+    public Result checkSubscribe(@RequestParam("userId") String userId) {
+
+        UserInfo userInfo = new UserInfo();
+        userInfo.setId(Integer.valueOf(userId));
+        userInfo = userInfoService.getUserInfo(userInfo);
+        try {
+            JSONObject jsonObject = WeixinUtil.loadJSON("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + weiXinService.getAccessToken()
+                    + "&openid=" + userInfo.getOpenId());
+            int subscribe = jsonObject.getInt("subscribe");
+            if (subscribe == 1) {
+                return new Result(true, null);
+            } else {
+                return new Result(false, null);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return new Result(false, null);
+    }
+
+
+    public static JSONObject loadJSON(String url) {
+
+        StringBuilder json = new StringBuilder();
+        try {
+            URL oracle = new URL(url);
+            URLConnection yc = oracle.openConnection();
+            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
+            String inputLine = null;
+            while ((inputLine = in.readLine()) != null) {
+                json.append(inputLine);
+            }
+            in.close();
+        } catch (MalformedURLException e) {
+        } catch (IOException e) {
+        }
+        return new JSONObject(json.toString());
+    }
+
+
+}

+ 6 - 0
src/main/resources/spring/beans-shiro.xml

@@ -23,6 +23,7 @@
                 <ref bean="phoneCodeRealm"/>
                 <ref bean="userPasswordRealm"/>
                 <ref bean="appTokenRealm"/>
+                <ref bean="weiXinCodeRealm"/>
             </list>
         </property>
         <!--<property name="subjectFactory" ref="agileSubjectFactory"/>-->
@@ -38,6 +39,7 @@
                 <ref bean="phoneCodeRealm"/>
                 <ref bean="userPasswordRealm"/>
                 <ref bean="appTokenRealm"/>
+                <ref bean="weiXinCodeRealm"/>
             </list>
         </property>
     </bean>
@@ -53,6 +55,10 @@
         <property name="authenticationTokenClass" value="com.izouma.awesomeadmin.shiro.AppToken"/>
     </bean>
 
+    <bean id="weiXinCodeRealm" class="com.izouma.awesomeadmin.shiro.WeiXinCodeRealm">
+        <property name="authenticationTokenClass" value="com.izouma.awesomeadmin.shiro.WeiXinCodeToken"/>
+    </bean>
+
     <bean id="agileSubjectFactory" class="com.izouma.awesomeadmin.shiro.AgileSubjectFactory"/>
 
     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>