Browse Source

接口录入完善,及jwt验证。

CrazyIter 5 years ago
parent
commit
3f17be7fc2

+ 0 - 12
HiTeachCE.sln

@@ -7,10 +7,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HiTeachCE", "HiTeachCE\HiTe
 EndProject
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AzureAuth", "AzureAuth\AzureAuth.csproj", "{CE14F94D-714D-4E0A-AAD3-64EE959350D0}"
 EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Heart.Auth.Api", "..\Heart.Auth\Heart.Auth.Api\Heart.Auth.Api.csproj", "{FA15D32D-A330-4725-896D-A5E9CF612175}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Heart.Auth.Db", "..\Heart.Auth\Heart.Auth.Db\Heart.Auth.Db.csproj", "{1949E3D6-87E5-48A9-B1D6-55F529E383C7}"
-EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -25,14 +21,6 @@ Global
 		{CE14F94D-714D-4E0A-AAD3-64EE959350D0}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{CE14F94D-714D-4E0A-AAD3-64EE959350D0}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{CE14F94D-714D-4E0A-AAD3-64EE959350D0}.Release|Any CPU.Build.0 = Release|Any CPU
-		{FA15D32D-A330-4725-896D-A5E9CF612175}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{FA15D32D-A330-4725-896D-A5E9CF612175}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{FA15D32D-A330-4725-896D-A5E9CF612175}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{FA15D32D-A330-4725-896D-A5E9CF612175}.Release|Any CPU.Build.0 = Release|Any CPU
-		{1949E3D6-87E5-48A9-B1D6-55F529E383C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{1949E3D6-87E5-48A9-B1D6-55F529E383C7}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{1949E3D6-87E5-48A9-B1D6-55F529E383C7}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{1949E3D6-87E5-48A9-B1D6-55F529E383C7}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 112 - 25
HiTeachCE/Controllers/LoginController.cs

@@ -3,10 +3,12 @@ using HiTeachCE.Helpers;
 using HiTeachCE.Models;
 using HiTeachCE.Services;
 using IdentityModel;
+using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Options;
 using OpenXmlPowerTools;
+using Org.BouncyCastle.Ocsp;
 using System;
 using System.Collections.Generic;
 using System.Linq;
@@ -56,10 +58,12 @@ namespace HiTeachCE.Controllers
         /// <param name="request"></param>
         /// <returns></returns>
         [HttpPost("regist")]
+        [Authorize]
         public BaseJosnRPCResponse Regist(JosnRPCRequest<Dictionary<string, string>> request)
         {
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
-            List<string> ClientId = new List<string>() { "fb564dde14df423cafac2085936e3b96" };/// GetLoginUser(JwtClaimTypes.ClientId);
+            List<string> ClientId = //new List<string>() { "fb564dde14df423cafac2085936e3b96" };
+           GetLoginUser(JwtClaimTypes.ClientId);
             /**
              "params": {
                     "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
@@ -90,6 +94,7 @@ namespace HiTeachCE.Controllers
         /// <param name="request"></param>
         /// <returns></returns>
         [HttpPost("createGroup")]
+        [Authorize]
         public BaseJosnRPCResponse CreateGroup(JosnRPCRequest<Dictionary<string, string>> request)
         {
             /**
@@ -101,9 +106,9 @@ namespace HiTeachCE.Controllers
              */
 
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
-            List<string> ClientId = new List<string>() { "fb564dde14df423cafac2085936e3b96" };
-                // GetLoginUser(JwtClaimTypes.ClientId);
-            string groupNum = "";
+            List<string> ClientId =// new List<string>() { "fb564dde14df423cafac2085936e3b96" };
+                 GetLoginUser(JwtClaimTypes.ClientId);
+            string groupNum ;
             if (request.@params.TryGetValue("deviceId", out string deviceId) && ClientId.IsNotEmpty())
             {
                 if (RedisHelper.HExists("device:" + ClientId[0], deviceId))
@@ -141,10 +146,13 @@ namespace HiTeachCE.Controllers
         /// <param name="request"></param>
         /// <returns></returns>
         [HttpPost("joinGroup")]
+        [Authorize]
         public BaseJosnRPCResponse JoinGroup(JosnRPCRequest<Dictionary<string, string>> request)
         {
+            List<string> ClientId = //new List<string>() { "fb564dde14df423cafac2085936e3b96" };
+             GetLoginUser(JwtClaimTypes.ClientId);
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
-            Dictionary<string, object> dict = new Dictionary<string, object>();
+            Dictionary<string, object> dict;
             /**
              "params": {
 		            "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
@@ -158,24 +166,7 @@ namespace HiTeachCE.Controllers
             {
                 if (RedisHelper.Exists("group:" + groupNum))
                 {
-                    dynamic groupMember = new { 
-                        deviceId,
-                        name= "🌱菁華浮梦",
-                        unionid= "b180ca87fea84c908a688c005b3f487e",
-                        role= "lecturer",
-                        org= "7f847a9f05224184a5d01ee69a6b00d6",
-                        phone_number="15283771540"
-                    };
-                    Dictionary<string, string> connectInfo = new Dictionary<string, string>() { 
-                        { "brokerHostName", "cdhabook.teammodel.cn" },
-                        { "brokerHostNameWSS", "wss://cdhabook.teammodel.cn/mqtt" },
-                        { "clientID", deviceId },
-                        //使用BCrypt加密
-                        { "password", "cdhabook.teammodel.cn" },
-                        { "username", "cdhabook.teammodel.cn/"+deviceId }
-                    };
-                    RedisHelper.HSet("group:" + groupNum, deviceId, groupMember) ;
-                    dict.Add("mqtt", new Dictionary<string,object>() { { "connectInfo", connectInfo },{ "groupMember", groupMember } });
+                    dict =  MqttInfo(ClientId, deviceId, groupNum);
                 }
                 else {
                     throw new BizException("教室不存在", 2);
@@ -188,6 +179,40 @@ namespace HiTeachCE.Controllers
           
             return builder.Data(dict).build();
         }
+
+        private static Dictionary<string, object> MqttInfo(List<string> ClientId,  string deviceId, string groupNum)
+        {
+            Dictionary<string, object> dict = new Dictionary<string, object>();
+            string password = "cdhabook.teammodel.cn/" + groupNum +"/"+ deviceId +"/"+ ClientId[0];
+            //发给前端使用的
+            string h1 = BCrypt.Net.BCrypt.HashPassword(password);
+            //后端存储使用的
+            string h2 = BCrypt.Net.BCrypt.HashPassword(h1);
+            bool validPassword = BCrypt.Net.BCrypt.Verify(h1, h2);
+            string uname = password;
+            Dictionary<string, string> connectInfo = new Dictionary<string, string>() {
+                        { "brokerHostName", "cdhabook.teammodel.cn" },
+                        { "brokerHostNameWSS", "wss://cdhabook.teammodel.cn/mqtt" },
+                        { "clientID", deviceId },
+                        //使用BCrypt加密
+                        { "password",h1 },
+                        { "username",uname }
+                    };
+            dynamic groupMember = new
+            {
+                deviceId,
+                username = uname,
+                password = h2
+            };
+            RedisHelper.HSet("group:" + groupNum, deviceId, groupMember);
+            Dictionary<string, string> subscribeTopic = BaseConfigModel.Configuration.GetSection("SubscribeTopic").Get<Dictionary<string, string>>();
+            subscribeTopic["receiveMsg"] = subscribeTopic["receiveMsg"].Replace("{deviceId}", deviceId);
+            Dictionary<string, string> publishTopic = BaseConfigModel.Configuration.GetSection("PublishTopic").Get<Dictionary<string, string>>();
+            publishTopic["sendMsg"] = publishTopic["sendMsg"].Replace("{deviceId}", deviceId).Replace("{groupNum}", groupNum);
+            dict.Add("mqtt", new Dictionary<string, object>() { { "connectInfo", connectInfo },{ "publishTopic", publishTopic },{ "subscribeTopic", subscribeTopic } });
+            return dict;
+        }
+
         /// <summary>
         /// 认证
         /// </summary>
@@ -361,8 +386,67 @@ namespace HiTeachCE.Controllers
             }
         }
 
+        //register user
+        [HttpPost("register")]
+        public BaseJosnRPCResponse Register(JosnRPCRequest<RegisterDto> request) {
+            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
+            if (RedisHelper.Exists("ticket:" + request.@params.ticket))
+            {
+                if (request.@params.user != null)
+                {
+                    string[] phone= RedisHelper.HVals("ticket:" + request.@params.ticket);
+                    if (phone.IsNotEmpty())
+                    {
+                        if (!request.@params.user.cellphone.Equals(phone[0])) {
+                            throw new BizException("手机号与凭证不匹配!", 2);
+                        }
+                    }
+                    else {
+                        throw new BizException("凭证无效!", 2);
+                    }
+                    Expression<Func<Lecturer, bool>> linq = null;
+                    linq = m => m.cellphone == request.@params.user.cellphone || m.account == request.@params.user.account;
+                    List<Lecturer> lecturers = lecturerService.GetList(linq);
+                    if (lecturers.IsNotEmpty())
+                    {
+                        throw new BizException("手机号或账号已经存在!", 2);
+                    }
+                    else
+                    {
+                        request.@params.user.id = Guid.NewGuid().ToString();
+                        request.@params.user.unionid = Guid.NewGuid().ToString("N");
+                        request.@params.user.unionid = "86";
+                        if (request.@params.user.password == null)
+                        {
+                            request.@params.user.password = "";
+                        }
+                        bool ib = lecturerService.Insert(request.@params.user);
+                        if (ib)
+                        {
+                            return builder.Data(ib).build();
+                        }
+                        else
+                        {
+                            throw new BizException("注册失败!", 2);
+                        }
+                    }
+                }
+                else
+                {
+                    throw new BizException("参数错误!", 2);
+                }
+            }
+            else {
+                throw new BizException("短信验证过期!", 2);
+            }
+            
 
+        }
 
+        public class RegisterDto { 
+            public Lecturer user { get; set; }
+            public string ticket { get; set; }
+        }
         /// <summary>
         /// 登录
         /// </summary>
@@ -471,7 +555,9 @@ namespace HiTeachCE.Controllers
                 else
                 {
                     //测试组织机构
-                    return new Dictionary<string, object> { { "status", 3 }, { "org", organizationService.GetByIds(new string[] { freeOrg }) } };
+                    Expression<Func<Organization, bool>> olinq = null;
+                    olinq = o =>o.code==freeOrg && o.status == 1;
+                    return new Dictionary<string, object> { { "status", 3 }, { "org", organizationService.GetList(olinq) } };
                 }
             }
             else
@@ -498,7 +584,8 @@ namespace HiTeachCE.Controllers
                                                 areaCode="86",
                                                 registerTime=new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
                                                 status=1,
-                                                setaccount=0
+                                                setaccount=0,
+                                                cellphone=cellphone
                                             }
                                         }
                                     };

+ 1 - 0
HiTeachCE/HiTeachCE.csproj

@@ -4,6 +4,7 @@
     <TargetFramework>netcoreapp3.1</TargetFramework>
   </PropertyGroup>
   <ItemGroup>
+    <PackageReference Include="BCrypt.Net-Core" Version="1.6.0" />
     <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="2.2.0" />
     <PackageReference Include="MQTTnet.AspNetCore" Version="3.0.11" />
     <PackageReference Include="MQTTnet.Extensions.WebSocket4Net" Version="3.0.11" />

+ 5 - 0
HiTeachCE/Models/Lecturer.cs

@@ -1,6 +1,7 @@
 using SqlSugar;
 using System;
 using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
 using System.Linq;
 using System.Threading.Tasks;
 
@@ -12,9 +13,12 @@ namespace HiTeachCE.Models
         [SugarColumn(IsNullable = false, IsPrimaryKey = true)]
         public string id { get; set; }
         public string unionid { get; set; }
+        [Required(ErrorMessage = "用户名必须填写")]
         public string username { get; set; }
         public string password { get; set; }
+        [Required(ErrorMessage = "账号必须填写")]
         public string account { get; set; }
+        [Required(ErrorMessage = "手机号必须填写")]
         public string cellphone { get; set; }
         public string areaCode { get; set; }
         public long registerTime { get; set; }
@@ -23,5 +27,6 @@ namespace HiTeachCE.Models
         public int setaccount { get; set; } = 0;
         public string email { get; set; }
         public string avatar { get; set; }
+        public string gender { get; set; }
     }
 }

+ 3 - 2
HiTeachCE/Program.cs

@@ -17,8 +17,9 @@ namespace HiTeachCE
     {
         public static void Main(string[] args)
         {
-            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
-          
+            string h1= BCrypt.Net.BCrypt.HashPassword("https://sokrates.habookaclass.biz");
+            string h2=  BCrypt.Net.BCrypt.HashPassword(h1);
+            bool validPassword = BCrypt.Net.BCrypt.Verify(h1, h2);
             CreateHostBuilder(args).Build().Run();
         }
 

+ 1 - 1
HiTeachCE/Startup.cs

@@ -176,7 +176,7 @@ namespace HiTeachCE
             //    );
             app.UseRouting();
             app.UseCors("CorsPolicy"); //使用跨域設定
-            app.UseAuthorization();
+            app.UseAuthentication();
             app.UseAuthorization();
             app.UseEndpoints(endpoints =>
             {

+ 10 - 28
HiTeachCE/appsettings.json

@@ -30,36 +30,18 @@
     "AppKey": "ff01c4a2c87ffcda5268f010",
     "Secret": "a4a19a5c556eeae3cffa5242"
   },
-  "PublishTopic": [
+  "PublishTopic": 
     {
-      "code": "getTwin",
-      "value": "$iothub/twin/GET/?$rid=0"
-    },
-    {
-      "code": "patchTwin",
-      "value": "$iothub/twin/PATCH/properties/reported/?$rid=0"
-    },
-    {
-      "code": "sendDirectMethod",
-      "value": "$iothub/methods/res/200/?$rid="
-    },
-    {
-      "code": "sendMsg",
-      "value": "devices/{deviceId}/messages/events/endpoint=coretopiciot&groupNum={groupNum}&deviceId={deviceId}"
+      "getTwin": "$iothub/twin/GET/?$rid=0",
+      "patchTwin": "$iothub/twin/PATCH/properties/reported/?$rid=0",
+      "sendDirectMethod": "$iothub/methods/res/200/?$rid=",
+      "sendMsg": "devices/{deviceId}/messages/events/endpoint=coretopiciot&groupNum={groupNum}&deviceId={deviceId}"
     }
-  ],
-  "SubscribeTopic": [
-    {
-      "code": "receiveMsg",
-      "value": "devices/{deviceId}/messages/devicebound/#"
-    },
-    {
-      "code": "receiveDirectMethod",
-      "value": "$iothub/methods/POST/directMethod/#"
-    },
+  ,
+  "SubscribeTopic": 
     {
-      "code": "receiveTwin",
-      "value": "$iothub/twin/res/#"
+      "receiveMsg": "devices/{deviceId}/messages/devicebound/#",
+      "receiveDirectMethod": "$iothub/methods/POST/directMethod/#",
+      "receiveTwin": "$iothub/twin/res/#"
     }
-  ]
 }