Explorar o código

修改天翼云登录

xuanyan %!s(int64=3) %!d(string=hai) anos
pai
achega
e8cfa9bab4

+ 2 - 1
smart-city-grid-yinchuan-manage/src/api/user.js

@@ -65,6 +65,7 @@ export const clearCache = () => request({
 });
 
 export const thirdLogin = () => request({
-  url: '/api/ctwing/login/getCode',
+  // url: '/api/ctwing/login/getCode',
+  url: '/api/ctwing/login/render/ctwing',
   method: 'get'
 });

+ 6 - 0
smart-city-grid-yinchuan-server/pom.xml

@@ -165,6 +165,12 @@
             <version>${just.auth}</version>
         </dependency>
 
+        <dependency>
+            <groupId>com.squareup.okhttp3</groupId>
+            <artifactId>okhttp</artifactId>
+            <version>4.8.0</version>
+        </dependency>
+
 
     </dependencies>
     <build>

+ 55 - 100
smart-city-grid-yinchuan-server/src/main/java/org/springblade/third/auth/controller/CtwingController.java

@@ -8,21 +8,21 @@ import me.zhyd.oauth.model.AuthCallback;
 import me.zhyd.oauth.model.AuthResponse;
 import me.zhyd.oauth.model.AuthUser;
 import me.zhyd.oauth.request.AuthRequest;
+import me.zhyd.oauth.utils.AuthStateUtils;
 import org.springblade.core.tool.api.R;
+import org.springblade.modules.system.entity.User;
+import org.springblade.modules.system.service.IUserService;
 import org.springblade.third.auth.constants.CtwingAuthConstants;
-import org.springblade.third.auth.request.AuthCtwingRequest;
+import org.springblade.third.auth.entity.AccountOauth;
+import org.springblade.third.auth.service.IAccountOauthService;
 import org.springblade.third.auth.util.AuthRequestUtil;
 import org.springblade.third.auth.util.ByteFormat;
-import org.springblade.third.auth.util.HmacSha1Util;
 import org.springblade.third.auth.util.XXTeaUtil;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 import javax.servlet.http.HttpServletRequest;
-import java.util.HashMap;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
 import java.util.Map;
 
 /**
@@ -36,108 +36,63 @@ import java.util.Map;
 @RequestMapping("ctwing/login")
 public class CtwingController {
 
-	@GetMapping("/getCode")
-	public R getCode(){
-		try {
-			// 注意:运行demo前请将天翼账号开放平台申请获取的应用ID(appId)、应用秘钥(appSecret)填写至Constants类中。
-			// 运行前请在Constants类中填写或修改请求所需参数
+	private IAccountOauthService accountOauthService;
+	private IUserService userService;
 
-			// 公共请求参数
-			// 开发者在天翼账号开放平台申请获取的应用ID
-			String appId = CtwingAuthConstants.APP_ID;
-			// 统一为:20100
-			String clientType = CtwingAuthConstants.clientType;
-			// 统一为:redirect(用于重定向接口的显示说明)
-			String format = CtwingAuthConstants.format;
-			// 调用的接口版本号:v2.1
-			String version = CtwingAuthConstants.version;
-			// 加密参数
-			String paras = getParas();
-
-			// 签名所需参数map
-			Map<String, String> signMap = new HashMap<>();
-			signMap.put("appId", appId);
-			signMap.put("clientType", clientType);
-			signMap.put("format", format);
-			signMap.put("version", version);
-			signMap.put("paras", paras);
-
-			// 签名
-			String sign = getSign(signMap);
-
-			// 拼接wap登录框链接(GET请求)
-			String webLoginBxUrl = CtwingAuthConstants.UNIFY_ACCOUNT_LOGIN_URL + "?" + "appId=" + appId + "&clientType=" + clientType
-				+ "&format=" + format + "&version=" + version + "&paras=" + paras + "&sign=" + sign;
-
-			log.info("generate loginbox web url unifyAccountLogin success.");
-			log.info("unifyAccountLogin url : " + webLoginBxUrl);
-
-			// ps: 将生成的链接wapLoginBxUrl复制到浏览器中访问
-			// 链接返回wap登录框界面,登录成功后重定向到指定的URL
-			// 如http://returnURL?appId=123&paras=123&sign=123。returnURL按照本接口规范定义的参数处理方式接收和处理。
-
-			return R.data(webLoginBxUrl);
-		} catch (Exception e){
-			log.error("unifyAccountLogin demo error:",e);
-			return R.status(false);
-		}
-	}
-
-	/**
-	 * 生成paras参数方法
-	 * @return
-	 */
-	private static String getParas() throws Exception {
-		// 非公共请求参数
-		Map<String, String> businessMap = new HashMap<>();
-		// 时间戳
-		businessMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
-		// 回调地址
-		businessMap.put("returnURL", CtwingAuthConstants.returnURL);
-		// 页面Key
-		businessMap.put("pageKey", CtwingAuthConstants.pageKey);
-		// 登录类型
-		businessMap.put("regReturnUrl", CtwingAuthConstants.regReturnUrl);
-		// 状态参数
-		businessMap.put("state", CtwingAuthConstants.state);
-
-		// 拼接非公共请求参数(无顺序要求)
-		StringBuffer sb = new StringBuffer();
-		for(Map.Entry<String, String> entry : businessMap.entrySet()) {
-			sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
-		}
-
-		// XXTea加密非公共加密参数
-		byte[] encValue = XXTeaUtil.encrypt(sb.toString().getBytes(CtwingAuthConstants.DEFAULT_CHARSET)
-			, CtwingAuthConstants.APP_SECRET.getBytes(CtwingAuthConstants.DEFAULT_CHARSET));
-		return ByteFormat.bytesToHexString(encValue);
-	}
-
-	/**
-	 * 获取签名参数方法
-	 * @param signMap
-	 * @return
-	 */
-	private static String getSign(Map<String, String> signMap) throws Exception {
-		// 生成签名加密串(拼接顺序为:appId+clientType+format+version+paras)
-		String signValue = signMap.get("appId") + signMap.get("clientType") + signMap.get("format")
-			+ signMap.get("version") + signMap.get("paras");
-
-		// HMAC-SHA1签名
-		byte[] encValue = HmacSha1Util.getHmacSHA1(signValue, CtwingAuthConstants.APP_SECRET);
-		return ByteFormat.bytesToHexString(encValue);
+	@RequestMapping(value = "/render/{source}")
+	@ResponseBody
+	public R renderAuth(@PathVariable("source") String source, HttpServletResponse response) throws IOException {
+		log.warn("进入render:" + source);
+		AuthRequest authRequest = AuthRequestUtil.getAuthRequest(source);
+		String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
+		log.warn(authorizeUrl);
+		return R.data(authorizeUrl);
 	}
 
 	@RequestMapping("/callBack/{source}")
-	public void ctwingCallBack(@PathVariable("source") String source, AuthCallback callback, HttpServletRequest request){
+	public R ctwingCallBack(@PathVariable("source") String source, AuthCallback callback, HttpServletRequest request){
 		AuthRequest authRequest = AuthRequestUtil.getAuthRequest(source);
 		callback = this.getAuthCallback(source, callback, request);
 		AuthResponse<AuthUser> response = authRequest.login(callback);
 		log.warn(JSONObject.toJSONString(response));
 
-		if (callback.getCode() != null) {
-
+		if (response.ok()) {
+			AuthUser data = response.getData();
+			String uuid = data.getUuid();
+			String mobile = data.getUsername();
+			String avatar = data.getAvatar();
+			AccountOauth dbAccount = accountOauthService.lambdaQuery().eq(AccountOauth::getUuid,uuid).eq(AccountOauth::getSource,source).one();
+			User dbUser = userService.lambdaQuery().eq(User::getPhone,mobile).one();
+			if (dbAccount == null){
+				if (dbUser == null){
+					return R.data("该用户不存在");
+				}else {
+					AccountOauth accountOauth = new AccountOauth();
+					accountOauth.setUuid(uuid);
+					accountOauth.setAccountId(dbUser.getId());
+					accountOauth.setUserName(mobile);
+					accountOauth.setNickName(dbUser.getAccount());
+					accountOauth.setAvatar(avatar);
+					accountOauth.setEmail(dbUser.getEmail());
+					accountOauth.setSource(source);
+					Boolean saveAccount = accountOauthService.save(accountOauth);
+					return R.data(saveAccount);
+				}
+			}else {
+				if (dbUser == null){
+					return R.data("该用户不存在");
+				}else {
+					Boolean updateAccount = accountOauthService.lambdaUpdate()
+						.eq(AccountOauth::getId,dbAccount.getId())
+						.set(AccountOauth::getUserName,mobile)
+						.set(AccountOauth::getNickName,dbUser.getAccount())
+						.set(AccountOauth::getAvatar,avatar)
+						.set(AccountOauth::getEmail,dbUser.getEmail()).update();
+					return R.data(updateAccount);
+				}
+			}
 		}
+		return R.data("请求第三方接口失败");
 	}
 
 	private AuthCallback getAuthCallback(String source, AuthCallback authCallback, HttpServletRequest request){

+ 7 - 0
smart-city-grid-yinchuan-server/src/main/java/org/springblade/third/auth/dto/AccountOauthDTO.java

@@ -16,6 +16,8 @@
  */
 package org.springblade.third.auth.dto;
 
+import com.baomidou.mybatisplus.annotation.TableField;
+import org.springblade.modules.system.entity.User;
 import org.springblade.third.auth.entity.AccountOauth;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
@@ -31,4 +33,9 @@ import lombok.EqualsAndHashCode;
 public class AccountOauthDTO extends AccountOauth {
 	private static final long serialVersionUID = 1L;
 
+	/**
+	 * 当前在线用户
+	 */
+	@TableField(exist = false)
+	private User onLineUser;
 }

+ 0 - 82
smart-city-grid-yinchuan-server/src/main/java/org/springblade/third/auth/entity/AccountOauth.java

@@ -1,82 +0,0 @@
-/*
- *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
- *
- *  Redistribution and use in source and binary forms, with or without
- *  modification, are permitted provided that the following conditions are met:
- *
- *  Redistributions of source code must retain the above copyright notice,
- *  this list of conditions and the following disclaimer.
- *  Redistributions in binary form must reproduce the above copyright
- *  notice, this list of conditions and the following disclaimer in the
- *  documentation and/or other materials provided with the distribution.
- *  Neither the name of the dreamlu.net developer nor the names of its
- *  contributors may be used to endorse or promote products derived from
- *  this software without specific prior written permission.
- *  Author: Chill 庄骞 (smallchill@163.com)
- */
-package org.springblade.third.auth.entity;
-
-import com.baomidou.mybatisplus.annotation.TableName;
-import org.springblade.core.mp.base.BaseEntity;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-/**
- * 账户角色关系表实体类
- *
- * @author BladeX
- * @since 2022-09-30
- */
-@Data
-@TableName("yc_account_oauth")
-@EqualsAndHashCode(callSuper = true)
-@ApiModel(value = "AccountOauth对象", description = "账户角色关系表")
-public class AccountOauth extends BaseEntity {
-
-	private static final long serialVersionUID = 1L;
-
-	/**
-	* 第三方系统用户ID
-	*/
-		@ApiModelProperty(value = "第三方系统用户ID")
-		private String uuid;
-	/**
-	* 系统用户ID
-	*/
-		@ApiModelProperty(value = "系统用户ID")
-		private Long accountId;
-	/**
-	* 账号名,一般是手机号
-	*/
-		@ApiModelProperty(value = "账号名,一般是手机号")
-		private String userName;
-	/**
-	* 用户名
-	*/
-		@ApiModelProperty(value = "用户名")
-		private String nickName;
-	/**
-	* 头像
-	*/
-		@ApiModelProperty(value = "头像")
-		private String avatar;
-	/**
-	* 邮件
-	*/
-		@ApiModelProperty(value = "邮件")
-		private String email;
-	/**
-	* 备注
-	*/
-		@ApiModelProperty(value = "备注")
-		private String mobile;
-	/**
-	* 来源
-	*/
-		@ApiModelProperty(value = "来源")
-		private String source;
-
-
-}