Browse Source

钉钉绑定Unionid

黄贺彬 5 năm trước cách đây
mục cha
commit
e50b781c79

+ 41 - 0
HiTeachCE/Controllers/LecturerController.cs

@@ -1,4 +1,5 @@
 using HiTeachCE.Context;
+using HiTeachCE.Dtos;
 using HiTeachCE.Extension;
 using HiTeachCE.Helpers;
 using HiTeachCE.Models;
@@ -130,6 +131,8 @@ namespace HiTeachCE.Controllers
                 request.@params.registerTime = lecturer.registerTime;
                 request.@params.cellphone = lecturer.cellphone;
                 request.@params.areaCode = lecturer.areaCode;
+                request.@params.dingOpenid = lecturer.dingOpenid;
+                request.@params.dingUnionid = lecturer.dingUnionid;
                 b = lecturerService.Update(request.@params);
             }
             return b;
@@ -150,6 +153,42 @@ namespace HiTeachCE.Controllers
             bool b = UpdateLecture(request, lecturer);
             return builder.Data(b).build();
         }
+
+        /// <summary>
+        /// 绑定钉钉  参数 TmpAuthCode
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("bindDing")]
+        [Authorize(Policy = Constant.Role_WebAll)]
+        public BaseJosnRPCResponse BindDing(JosnRPCRequest<string> request)
+        {
+            bool flag = false;
+            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
+            if (RedisHelper.Exists("TmpAuthCode:" + request.@params))
+            {
+                DingUserInfo dingUserInfo = RedisHelper.HGet<DingUserInfo>("TmpAuthCode:" + request.@params, request.@params);
+                string unionid = GetLoginUser(JwtClaimTypes.Id);
+                Expression<Func<Lecturer, bool>> linq = null;
+                linq = l => l.unionid == unionid;
+                List<Lecturer> list = lecturerService.GetList(linq);
+                if (list.IsNotEmpty()&& dingUserInfo!=null)
+                {
+                    Lecturer lecturer = list[0];
+                    lecturer.dingOpenid = dingUserInfo.Openid;
+                    lecturer.dingUnionid = dingUserInfo.Unionid;
+                    flag =  lecturerService.Update(lecturer);
+                }
+            }
+            else {
+                throw new BizException("钉钉临时授权码过期", 2);
+            }
+            return builder.Data(flag).build();
+        }
+
+        //Unbound 解除绑定
+
+
         /// <summary>
         /// 注册用户
         /// </summary>
@@ -159,6 +198,7 @@ namespace HiTeachCE.Controllers
         public BaseJosnRPCResponse Register(JosnRPCRequest<RegisterDto> request)
         {
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
+           
             if (RedisHelper.Exists("ticket:" + request.@params.ticket))
             {
                 if (request.@params.user != null)
@@ -218,6 +258,7 @@ namespace HiTeachCE.Controllers
             {
                 throw new BizException("短信验证过期!", 2);
             }
+            
         }
     }
 }

+ 106 - 52
HiTeachCE/Controllers/LoginController.cs

@@ -1,4 +1,8 @@
+using DingTalk.Api;
+using DingTalk.Api.Request;
+using DingTalk.Api.Response;
 using Hei.Captcha;
+using HiTeachCE.Dtos;
 using HiTeachCE.Extension;
 using HiTeachCE.Helpers;
 using HiTeachCE.Models;
@@ -78,7 +82,7 @@ namespace HiTeachCE.Controllers
             if (request.@params.TryGetValue("deviceId", out string deviceId) && request.@params.TryGetValue("orgCode", out string orgCode) && string.IsNullOrEmpty(unionid))
             {
                 Dictionary<string, object> dict = ActivationValid(orgCode, unionid);
-                if (dict!=null && dict.TryGetValue("flag", out object flag) && bool.Parse(flag.ToString()))
+                if (dict != null && dict.TryGetValue("flag", out object flag) && bool.Parse(flag.ToString()))
                 {
                     if (RedisHelper.HExists("device:" + deviceId, orgCode))
                     {
@@ -120,15 +124,16 @@ namespace HiTeachCE.Controllers
              */
 
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
-             string  ClientId =// new List<string>() { "fb564dde14df423cafac2085936e3b96" };
-                 GetLoginUser(JwtClaimTypes.ClientId);
+            string ClientId =// new List<string>() { "fb564dde14df423cafac2085936e3b96" };
+                GetLoginUser(JwtClaimTypes.ClientId);
             string groupNum;
             if (request.@params.TryGetValue("deviceId", out string deviceId) && string.IsNullOrEmpty(ClientId))
             {
                 if (RedisHelper.HExists("device:" + ClientId, deviceId))
                 {
                     groupNum = RedisHelper.HGet<string>("device:" + ClientId, deviceId);
-                    if (string.IsNullOrEmpty(groupNum)) {
+                    if (string.IsNullOrEmpty(groupNum))
+                    {
                         do
                         {
                             groupNum = RandGroupNum();
@@ -140,12 +145,14 @@ namespace HiTeachCE.Controllers
                 }
                 else { throw new BizException("装置未注册", 2); }
             }
-            else {
+            else
+            {
                 throw new BizException("参数错误", 2);
             }
             return builder.Data(groupNum).build();
         }
-        public string RandGroupNum() {
+        public string RandGroupNum()
+        {
             Random random = new Random();
             String result = "";
             for (int i = 0; i < 6; i++)
@@ -163,9 +170,9 @@ namespace HiTeachCE.Controllers
         [Authorize(Policy = Constant.Role_LecturerLearner)]
         public BaseJosnRPCResponse JoinGroup(JosnRPCRequest<Dictionary<string, string>> request)
         {
-            string  ClientId = GetLoginUser(JwtClaimTypes.ClientId);
-            string  Unionid = GetLoginUser(JwtClaimTypes.Id);
-            string  Role = GetLoginUser(JwtClaimTypes.Role);
+            string ClientId = GetLoginUser(JwtClaimTypes.ClientId);
+            string Unionid = GetLoginUser(JwtClaimTypes.Id);
+            string Role = GetLoginUser(JwtClaimTypes.Role);
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
             Dictionary<string, object> dict;
             /**
@@ -183,7 +190,8 @@ namespace HiTeachCE.Controllers
                 {
                     dict = MqttInfo(ClientId, deviceId, groupNum, Unionid, Role);
                 }
-                else {
+                else
+                {
                     throw new BizException("教室不存在", 2);
                 }
             }
@@ -195,7 +203,7 @@ namespace HiTeachCE.Controllers
             return builder.Data(dict).build();
         }
 
-        private static Dictionary<string, object> MqttInfo( string  ClientId, string deviceId, string groupNum,  string  Unionid,  string  Role)
+        private static Dictionary<string, object> MqttInfo(string ClientId, string deviceId, string groupNum, string Unionid, string Role)
         {
             string brokerHostName = BaseConfigModel.Configuration["brokerHostName"];
 
@@ -238,7 +246,7 @@ namespace HiTeachCE.Controllers
             {
                 clientId = ClientId,
                 deviceId = deviceId,
-                unionid = Unionid ,
+                unionid = Unionid,
                 role = "lecturer",
                 groupNum = groupNum
             };
@@ -250,7 +258,7 @@ namespace HiTeachCE.Controllers
 
 
 
-      
+
         /// <summary>
         /// 教学认证
         /// </summary>
@@ -272,7 +280,8 @@ namespace HiTeachCE.Controllers
                 foreach (var code in members)
                 {
                     var dt = ActivationValid(code.orgCode, unionid);
-                    if (dt!=null) {
+                    if (dt != null)
+                    {
                         dict.Add(dt);
                     }
                 }
@@ -282,7 +291,7 @@ namespace HiTeachCE.Controllers
                 long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
                 ///处理该机构是否激活人数达到上线
                 Expression<Func<Member, bool>> limitlinq = null;
-                limitlinq = m => m.orgCode == freeOrg  && m.status == 1;
+                limitlinq = m => m.orgCode == freeOrg && m.status == 1;
                 List<Member> countMembers = memberService.GetList(limitlinq);
                 Expression<Func<ActivationCode, bool>> alinq = null;
                 alinq = m => m.orgCode == freeOrg && m.status == 1;
@@ -298,7 +307,8 @@ namespace HiTeachCE.Controllers
                     {
                         List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
                         string role = "admin,lecturer";
-                        if (RootUsers.Contains(phoneNumber)) {
+                        if (RootUsers.Contains(phoneNumber))
+                        {
                             role = "root," + role;
                         }
                         Member member = new Member
@@ -307,14 +317,16 @@ namespace HiTeachCE.Controllers
                             orgCode = freeOrg,
                             admin = 0,
                             status = 1,
-                           // expires = time + freeTTL,
+                            // expires = time + freeTTL,
                             unionid = unionid,
                             createTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()
                         };
                         bool flag = memberService.Insert(member);
                         if (flag)
-                        { var dt = ActivationValid(freeOrg, unionid);
-                            if (dt != null) {
+                        {
+                            var dt = ActivationValid(freeOrg, unionid);
+                            if (dt != null)
+                            {
                                 dict.Add(dt);
                             }
                         }
@@ -339,14 +351,16 @@ namespace HiTeachCE.Controllers
             Expression<Func<Organization, bool>> olinq = null;
             olinq = m => m.code == orgCode;
             Organization org = organizationService.GetList(olinq).FirstOrDefault();
-            if (org != null) {
+            if (org != null)
+            {
                 Dictionary<string, object> dict = new Dictionary<string, object>() { { "org", new { orgCode = "", name = org.name } }, { "flag", false } };
                 if (org.status != 1)
                 {
 
                     dict.Add("msg", "组织机构被禁用!");
                 }
-                else {
+                else
+                {
                     //验证组织机构的激活码状态,时间,最大人数
                     Expression<Func<ActivationCode, bool>> linq = null;
                     linq = m => m.orgCode == org.code;
@@ -385,43 +399,79 @@ namespace HiTeachCE.Controllers
                                 dict.Add("msg", "产品授权已经过期!");
                             }
                         }
-                        else {
+                        else
+                        {
                             dict.Add("msg", "组织机构授权状态被禁用!");
                         }
                     }
-                    else {
+                    else
+                    {
                         dict.Add("msg", "组织机构没有授权信息!");
                     }
-                    
+
                 }
-               
+
                 return dict;
             }
-            return null ;
+            return null;
         }
 
+
+
+
+      
         /// <summary>
         /// 登录
         /// </summary>
         /// <param name="request"></param>
         /// <returns></returns>
         [HttpPost("dingLogin")]
-        public   BaseJosnRPCResponse  DingLogin(JosnRPCRequest<Dictionary<string, string>> request)
+        public BaseJosnRPCResponse DingLogin(JosnRPCRequest<string> request)
         {
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
-            // 根据timestamp, appSecret计算签名值
-            string stringToSign = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000+"";
-             
-            string appSecret = "";
-            byte[] key = System.Text.Encoding.UTF8.GetBytes(appSecret);
-            byte[] content = System.Text.Encoding.UTF8.GetBytes(stringToSign);
-            var hmacsha256 = new HMACSHA256(key);
-            byte[] signatureBytes = hmacsha256.ComputeHash(content);
-            string signature =  Convert.ToBase64String(signatureBytes);
-            string urlEncodeSignature = HttpUtility.UrlEncode(signature);
-            string dingAuth =  "https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=xxx&timestamp=xxx&signature=xxx";
-
-            return builder.build();
+         
+            string accessKey = "dingoabikplouc0kaoq7io";
+            string appSecret = "05FZlu_DY3PnrpHTxrWQHA-zRIkV1fE-zECbMCULr5SlCUmhmY7x44U4H1-oyhpc";
+            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
+            OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest();
+            req.TmpAuthCode = request.@params;
+            OapiSnsGetuserinfoBycodeResponse rsp = client.Execute(req, accessKey, appSecret);
+
+            if (rsp.UserInfo != null && !string.IsNullOrEmpty(rsp.UserInfo.Unionid))
+            {
+                ///验证通过 验证信息存放在reids
+                RedisHelper.HSet("TmpAuthCode:" + request.@params, request.@params, new DingUserInfo
+                {
+                    Unionid = rsp.UserInfo.Unionid,
+                    Nick = rsp.UserInfo.Nick,
+                    Openid = rsp.UserInfo.Openid
+                });
+                RedisHelper.Expire("TmpAuthCode:" + request.@params, ticketTTL);
+
+                Expression<Func<Lecturer, bool>> linq = null;
+                linq = l => l.dingUnionid == rsp.UserInfo.Unionid;
+                List<Lecturer> list = lecturerService.GetList(linq);
+                if (list.IsNotEmpty() && !string.IsNullOrEmpty(list[0].cellphone))
+                {
+                    RedisHelper.HSet("ticket:" + request.@params, list[0].cellphone, list[0].cellphone);
+                    RedisHelper.Expire("ticket:" + request.@params, ticketTTL);
+                    Dictionary<string, object> dict = UserValid(list[0].cellphone);
+                    dict.Add("ticket", request.@params );
+                    return builder.Data(dict).build();
+                }
+                else
+                {
+                    Dictionary<string, object> dict =  new Dictionary<string, object> {
+                        { "status",1},
+                    };
+                    dict.Add("TmpAuthCode", request.@params);
+                    return builder.Data(dict).build();
+                }
+            }
+            else
+            {
+                throw new BizException("钉钉后端验证失败", 2);
+            }
         }
         /// <summary>
         /// HmacSHA256算法,返回的结果始终是32位
@@ -469,7 +519,8 @@ namespace HiTeachCE.Controllers
                         dict.Add("ticket", ticket);
                         return builder.Data(dict).build();
                     }
-                    else {
+                    else
+                    {
                         string[] vals = RedisHelper.HVals<string>(cellphone);
                         if (vals != null && vals.Length > 0)
                         {
@@ -524,7 +575,7 @@ namespace HiTeachCE.Controllers
         public List<Organization> GetOrgByUid(string uid)
         {
             Expression<Func<Member, bool>> mlinq = null;
-            mlinq = m => m.unionid == uid  && m.status == 1;
+            mlinq = m => m.unionid == uid && m.status == 1;
             List<Member> members = memberService.GetList(mlinq);
             if (members.IsNotEmpty())
             {
@@ -565,7 +616,7 @@ namespace HiTeachCE.Controllers
                 //  claimModel.Claims.Add(new Claim("org", orgCode));
                 JwtResponse jwtResponse = JwtHelper.IssueJWT(claimModel);
                 lecturer.password = "";
-                return new Dictionary<string, object> { { "status", 2 }, { "jwt", jwtResponse },{ "user", lecturer } };
+                return new Dictionary<string, object> { { "status", 2 }, { "jwt", jwtResponse }, { "user", lecturer } };
             }
             else
             {
@@ -579,7 +630,7 @@ namespace HiTeachCE.Controllers
                     seed.Replace(c, "");
                     pfx = pfx + c;
                 }
-                
+
                 return new Dictionary<string, object> {
                     { "status",1},
                     { "user",new Lecturer
@@ -621,13 +672,14 @@ namespace HiTeachCE.Controllers
                 RedisHelper.Expire("captcha:" + request.@params, smsTTL);
                 return builder.Data(base64).Extend(new Dictionary<string, object> { { "code", code } }).build();
             }
-            else {
+            else
+            {
                 throw new BizException("随机码为空!", 2);
             }
-            
+
         }
 
-   
+
 
         /// <summary>
         /// 发送短信
@@ -641,8 +693,8 @@ namespace HiTeachCE.Controllers
             string captcha = RedisHelper.HGet<string>("captcha:" + request.@params.randCode, request.@params.randCode);
             List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
             bool f = !string.IsNullOrEmpty(captcha) && captcha.Equals(request.@params.captcha.ToLower());
-            bool s= RootUsers.Contains(request.@params.cellphone) && request.@params.captcha.ToLower().Equals("0000");
-            if (f||s)
+            bool s = RootUsers.Contains(request.@params.cellphone) && request.@params.captcha.ToLower().Equals("0000");
+            if (f || s)
             {
                 string key = request.@params.cellphone;
 
@@ -664,7 +716,8 @@ namespace HiTeachCE.Controllers
                     return builder.Data(await SendMsg(key)).build();
                 }
             }
-            else {
+            else
+            {
                 throw new BizException("验证码错误!", 2);
             }
         }
@@ -673,7 +726,7 @@ namespace HiTeachCE.Controllers
         {
             List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
             Dictionary<string, object> data = new Dictionary<string, object>() { { "mobile", key }, { "temp_id", 1 }, { "sign_id", "" } };
-            
+
             if (RootUsers.Contains(key))
             {
                 string msgidstr = key;
@@ -682,7 +735,8 @@ namespace HiTeachCE.Controllers
                 RedisHelper.Expire(key, smsTTL);
                 return new Dictionary<string, object>() { { "msgid", msgidstr }, { "repeat", false } };
             }
-            else {
+            else
+            {
                 string resdata = await HttpClientHelper.Post(
                 BaseConfigModel.Configuration["JPush:Push"],
                 BaseConfigModel.Configuration["JPush:AppKey"],

+ 14 - 0
HiTeachCE/Dtos/DingUserInfo.cs

@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace HiTeachCE.Dtos
+{
+    public class DingUserInfo
+    {
+        public string Nick { get; set; }
+        public string Openid { get; set; }
+        public string Unionid { get; set; }
+    }
+}

+ 1 - 0
HiTeachCE/Helpers/Constant.cs

@@ -8,6 +8,7 @@ namespace HiTeachCE.Helpers
     public class Constant
     {
         public static string az09 = "qwertyuiopasdfghjklzxcvbnm0123456789";
+        public static string num09 = "0123456789";
         public const string Role_WebAll = "WebAll";
         public const string Role_Root = "root";
         public const string Role_Admin = "admin";

+ 7 - 1
HiTeachCE/HiTeachCE.csproj

@@ -34,11 +34,17 @@
  
  
   <ItemGroup>
-    <Folder Include="Dtos\" />
     <Folder Include="wwwroot\" />
     <Folder Include="OfficeFile\" />
     
   </ItemGroup>
+ 
+ 
+  <ItemGroup>
+    <Reference Include="topsdk-net-core">
+      <HintPath>Lib\topsdk-net-core.dll</HintPath>
+    </Reference>
+  </ItemGroup>
   
   <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build">
     <!-- Build Target:  Ensure Node.js is installed -->

BIN
HiTeachCE/Lib/topsdk-net-core.dll


+ 4 - 0
HiTeachCE/Models/Lecturer.cs

@@ -12,6 +12,7 @@ namespace HiTeachCE.Models
     {
         [SugarColumn(IsNullable = false, IsPrimaryKey = true)]
         public string id { get; set; }
+        [SugarColumn(IsNullable = false)]
         public string unionid { get; set; }
         [Required(ErrorMessage = "用户名必须填写")]
         public string username { get; set; }
@@ -19,6 +20,7 @@ namespace HiTeachCE.Models
         [Required(ErrorMessage = "账号必须填写")]
         public string account { get; set; }
         [Required(ErrorMessage = "手机号必须填写")]
+        [SugarColumn(IsNullable = false)]
         public string cellphone { get; set; }
         public string areaCode { get; set; }
         public long registerTime { get; set; }
@@ -29,5 +31,7 @@ namespace HiTeachCE.Models
         public string avatar { get; set; }
         public string gender { get; set; }
         public string region { get; set; }
+        public string dingOpenid { get; set; }
+        public string dingUnionid { get; set; }
     }
 }

+ 2 - 0
HiTeachCE/Models/RegisterDto.cs

@@ -9,5 +9,7 @@ namespace HiTeachCE.Models
     {
         public Lecturer user { get; set; }
         public string ticket { get; set; }
+
+        public string tmpAuthCode { get; set; }
     }
 }

+ 10 - 10
HiTeachCE/Startup.cs

@@ -103,23 +103,23 @@ namespace HiTeachCE
             app.UseHttpsRedirection();
             app.UseStaticFiles();
 
-            //SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
-            //{
-            //    ConnectionString = BaseConfigModel.Configuration["DbConnection:MySqlConnectionString"],
-            //    DbType = DbType.MySql,
-            //    IsAutoCloseConnection = true,
-            //    InitKeyType = InitKeyType.Attribute
-            //});
-            //db.CodeFirst.InitTables(
+            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
+            {
+                ConnectionString = BaseConfigModel.Configuration["DbConnection:MySqlConnectionString"],
+                DbType = DbType.MySql,
+                IsAutoCloseConnection = true,
+                InitKeyType = InitKeyType.Attribute
+            });
+            db.CodeFirst.InitTables(
             //    typeof(ActivationCode),
             //    typeof(Classroom),
             //    typeof(Learner),
-            //    typeof(Lecturer),
+                typeof(Lecturer)
             //    typeof(Member),
             //    typeof(Organization),
             //    typeof(Subscriber),
             //    typeof(WeChatUser)
-            //    );
+                );
             app.UseRouting();
             app.UseAuthentication();
             app.UseAuthorization();