فهرست منبع

小程序登录验证

CrazyIter 5 سال پیش
والد
کامیت
bc87e46f2b

+ 1 - 1
HiTeachCE/Controllers/ActivationCodeController.cs

@@ -167,7 +167,7 @@ namespace HiTeachCE.Controllers
         /// 时长-1 永久 ,大于0 按天计算
         /// </summary>
         [Required(ErrorMessage = "授权时限必须填写")]
-        [Range(0, 3650, ErrorMessage = "请输入-1~3650的整数")]
+        [Range(0, 3650, ErrorMessage = "请输入0~3650的整数")]
         public int expires { get; set; }
         public int status { get; set; }
     }

+ 68 - 36
HiTeachCE/Controllers/LoginController.cs

@@ -76,7 +76,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.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))
                     {
@@ -269,7 +269,10 @@ namespace HiTeachCE.Controllers
             {
                 foreach (var code in members)
                 {
-                    dict.Add(ActivationValid(code.orgCode, unionid));
+                    var dt = ActivationValid(code.orgCode, unionid);
+                    if (dt!=null) {
+                        dict.Add(dt);
+                    }
                 }
             }
             else
@@ -308,9 +311,10 @@ namespace HiTeachCE.Controllers
                         };
                         bool flag = memberService.Insert(member);
                         if (flag)
-                        {
-
-                            dict.Add(ActivationValid(freeOrg, unionid));
+                        { var dt = ActivationValid(freeOrg, unionid);
+                            if (dt != null) {
+                                dict.Add(dt);
+                            }
                         }
                         else
                         {
@@ -331,42 +335,67 @@ namespace HiTeachCE.Controllers
         {
             //调用ActivationCode
             Expression<Func<Organization, bool>> olinq = null;
-            olinq = m => m.code == orgCode && m.status == 1;
-            Organization org = organizationService.GetList(olinq).First();
-            Dictionary<string, object> dict = new Dictionary<string, object>() { { "org", new { orgCode = "", name = org.name } }, { "flag", false } };
-            //验证组织机构的激活码状态,时间,最大人数
-            Expression<Func<ActivationCode, bool>> linq = null;
-            linq = m => m.orgCode == org.code;
-            List<ActivationCode> activationCodes = activationCodeService.GetList(linq);
-            long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
-            if (activationCodes[0].expires > time )
-            {
-                int max = activationCodes[0].maximum;
-                Expression<Func<Member, bool>> mlinq = null;
-                mlinq = l => l.orgCode == org.code;
-                List<Member> members = memberService.GetList(mlinq);
-                if (members.Count >= max)
+            olinq = m => m.code == orgCode;
+            Organization org = organizationService.GetList(olinq).FirstOrDefault();
+            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", "产品授权人数超过上限!");
+
+                    dict.Add("msg", "组织机构被禁用!");
                 }
-                else
-                {
-                    if (members.Where(x => x.status == 1 ).Select(x => x.unionid).ToList().Contains(unionid))
+                else {
+                    //验证组织机构的激活码状态,时间,最大人数
+                    Expression<Func<ActivationCode, bool>> linq = null;
+                    linq = m => m.orgCode == org.code;
+                    List<ActivationCode> activationCodes = activationCodeService.GetList(linq);
+                    if (activationCodes.IsNotEmpty())
                     {
-                        dict["org"] = new { orgCode = org.code, name = org.name };
-                        dict.Add("flag", true);
+                        if (activationCodes[0].status == 1)
+                        {
+                            long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
+
+                            if (activationCodes[0].expires > time)
+                            {
+                                int max = activationCodes[0].maximum;
+                                Expression<Func<Member, bool>> mlinq = null;
+                                mlinq = l => l.orgCode == org.code;
+                                List<Member> members = memberService.GetList(mlinq);
+                                if (members.Count > max)
+                                {
+                                    dict.Add("msg", "产品授权人数超过上限!");
+                                }
+                                else
+                                {
+                                    if (members.Where(x => x.status == 1).Select(x => x.unionid).ToList().Contains(unionid))
+                                    {
+                                        dict["org"] = new { orgCode = org.code, name = org.name };
+                                        dict["flag"] = true;
+                                    }
+                                    else
+                                    {
+                                        dict.Add("msg", "组织机构未对该用户授权!");
+                                    }
+                                }
+                            }
+                            else
+                            {
+                                dict.Add("msg", "产品授权已经过期!");
+                            }
+                        }
+                        else {
+                            dict.Add("msg", "组织机构授权状态被禁用!");
+                        }
                     }
-                    else
-                    {
-                        dict.Add("msg", "组织机构未对该用户授权!");
+                    else {
+                        dict.Add("msg", "组织机构没有授权信息!");
                     }
+                    
                 }
+               
+                return dict;
             }
-            else
-            {
-                dict.Add("msg", "产品授权已经过期!");
-            }
-            return dict;
+            return null ;
         }
 
 
@@ -497,7 +526,8 @@ namespace HiTeachCE.Controllers
                 // claimModel.Claims.Add(new Claim(JwtClaimTypes.ClientId, activationCodes[0].clientId));
                 //  claimModel.Claims.Add(new Claim("org", orgCode));
                 JwtResponse jwtResponse = JwtHelper.IssueJWT(claimModel);
-                return new Dictionary<string, object> { { "status", 2 }, { "jwt", jwtResponse } };
+                lecturer.password = "";
+                return new Dictionary<string, object> { { "status", 2 }, { "jwt", jwtResponse },{ "user", lecturer } };
             }
             else
             {
@@ -511,6 +541,7 @@ namespace HiTeachCE.Controllers
                     seed.Replace(c, "");
                     pfx = pfx + c;
                 }
+                
                 return new Dictionary<string, object> {
                     { "status",1},
                     { "user",new Lecturer
@@ -524,7 +555,8 @@ namespace HiTeachCE.Controllers
                             registerTime=new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
                             status=1,
                             setaccount=0,
-                            cellphone=cellphone
+                            cellphone=cellphone,
+                            avatar= "https://cdhabook.teammodel.cn/avatar/usertile"+random.Next(10, 44)+".png"
                         }
                     }
                 };

+ 2 - 1
HiTeachCE/Controllers/OrganizationController.cs

@@ -184,7 +184,8 @@ namespace HiTeachCE.Controllers
                     registerTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
                     status = 1,
                     setaccount = 0,
-                    cellphone = request.@params.adminCellphone
+                    cellphone = request.@params.adminCellphone,
+                    avatar = "https://cdhabook.teammodel.cn/avatar/usertile" + random.Next(10, 44) + ".png"
                 };
                 lecturerService.Insert(lecturer);
             }

+ 210 - 0
HiTeachCE/Extension/Mqtt/MQTTExtension.cs

@@ -0,0 +1,210 @@
+using HiTeachCE.Models;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using MQTTnet.AspNetCore;
+using MQTTnet.Client.Receiving;
+using MQTTnet.Protocol;
+using MQTTnet.Server;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace HiTeachCE.Extension.Mqtt
+{
+    public static class MQTTExtension
+    {
+        public static void MQTTConnection(this IServiceCollection services) {
+            services.AddHostedMqttServerWithServices(
+           builder =>
+           {
+                //builder.WithDefaultEndpoint();
+
+                builder.WithDefaultEndpointPort(3000);
+               builder.WithConnectionValidator(c =>
+               {
+                    //从IServiceCollection中构建     ServiceProvider, 用以使用注入访问数据库的服务
+                    //  var serprovider = services.BuildServiceProvider();
+
+                    //  _logger.LogInformation($" ClientId:{c.ClientId} Endpoint:{c.Endpoint} Username:{c.Username} Password:{c.Password} WillMessage:{c.WillMessage}");
+
+                    //if (c.ClientId.Length < 5)
+                    //{
+                    //    c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
+                    //    return;
+                    //}
+
+                     
+                    MQTTInfo info= RedisHelper.HGet<MQTTInfo>("mqtt:"+c.ClientId, c.ClientId);
+                    if (info != null)
+                    {
+                        if (c.Username != info.username)
+                        {
+                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
+                            return;
+                        }
+                        if (!BCrypt.Net.BCrypt.Verify(c.Password,info.password))
+                        {
+                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
+                            return;
+                        }
+                    }
+                    else {
+                        c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
+                        return;
+                    }
+                   c.ReasonCode = MqttConnectReasonCode.Success;
+                    
+               })
+               .WithApplicationMessageInterceptor(context =>
+               {
+                    ///发送消息拦截器
+                    ///
+                     
+                    MQTTInfo info = RedisHelper.HGet<MQTTInfo>("mqtt:" + context.ClientId, context.ClientId);
+                    if (info != null)
+                    {
+                        bool match = false;
+                        foreach (string topic in info.topic)
+                        {
+                            //if (context.TopicFilter.Topic .StartsWith(topic)) {
+                            if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, topic))
+                            {
+                                match = true;
+                                break;
+                            }
+                        }
+                        if (match)
+                        {
+                            context.AcceptPublish = true;
+                        }
+                        else
+                        {
+                            context.AcceptPublish = false;
+                        }
+                    }
+                    else {
+                        context.AcceptPublish = false;
+                    }
+                     
+                    //if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "/myTopic/WithTimestamp/#"))
+                    //{
+                    //    context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
+                    //}
+
+                    //if (context.ApplicationMessage.Topic == "not_allowed_topic")
+                    //{
+                    //    context.AcceptPublish = false;
+                    //    context.CloseConnection = true;
+                    //}
+
+                    // _logger.Log(LogLevel.Information, $"clientId:{context.ClientId}, topic:{context.ApplicationMessage.Topic}");
+                    //  _logger.Log(LogLevel.Information, $"Payload:{Encoding.Default.GetString(context.ApplicationMessage.Payload)}");
+                })///订阅拦截验证
+                .WithSubscriptionInterceptor((context) =>
+               {
+                     
+                    MQTTInfo info = RedisHelper.HGet<MQTTInfo>("mqtt:" + context.ClientId, context.ClientId);
+                    if (info != null)
+                    {
+                        bool match = false;
+                        foreach (string topic in info.topic)
+                        {
+                            //if (context.TopicFilter.Topic .StartsWith(topic)) {
+                            if (MqttTopicFilterComparer.IsMatch(context.TopicFilter.Topic, topic))
+                            {
+                                match = true;
+                                break;
+                            }
+                        }
+                        if (match)
+                        {
+                            context.AcceptSubscription = true;
+                        }
+                        else
+                        {
+                            context.AcceptSubscription = false;
+                        }
+                    }
+                    else {
+                        context.AcceptSubscription = false;
+                    }
+                    
+                    //   context.ClientId
+                    //if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
+                    //{
+                    //    context.AcceptSubscription = false;
+                    //}
+
+                    //if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
+                    //{
+                    //    context.AcceptSubscription = false;
+                    //    context.CloseConnection = true;
+                    //}
+
+                    // context.TopicFilter.Topic.start
+                });
+           });
+            services.AddMqttTcpServerAdapter();
+            services.AddMqttWebSocketServerAdapter();
+            services.AddMqttConnectionHandler().AddConnections();
+        }
+
+        public static void UseMqtt(this IApplicationBuilder app) {
+            app.UseMqttServer(
+                   server =>
+                   {
+                       server.UseApplicationMessageReceivedHandler(e =>
+                       {
+
+                       });
+
+                       server.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
+                       {
+                           Console.WriteLine(
+                               $"'{e.ClientId}' reported '{e.ApplicationMessage.Topic}' > '{Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0])}'",
+                               ConsoleColor.Magenta);
+                       });
+                       server.StartedHandler = new MqttServerStartedHandlerDelegate((
+                           e =>
+                           {
+
+                           }));
+                       server.StoppedHandler = new MqttServerStoppedHandlerDelegate(
+                           e =>
+                           {
+
+                           });
+
+                       server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(
+                           e =>
+                           {
+                           //  _logger.LogInformation($"{e.ClientId} is connectioned");
+                           // _logger.LogInformation($"目前连接总数:{ server.GetClientStatusAsync().Result.Count}");
+                       });
+                       server.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(
+                           e =>
+                           {
+
+                           // _logger.LogInformation($"{e.ClientId} is disconnectioned");
+                           //  _logger.LogInformation($"目前连接总数:{ server.GetClientStatusAsync().Result.Count}");
+                       });
+                   //开启订阅以及取消订阅
+                   server.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate((args) => {
+                           Console.WriteLine("订阅" + args.ClientId + args.TopicFilter.Topic);
+                       });
+                       server.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate((args) => {
+                           Console.WriteLine("取消订阅" + args.ClientId + args.TopicFilter);
+                       });
+                       server.UseClientConnectedHandler(x => {
+                           Console.WriteLine(x.ClientId + "连接");
+                       });
+                       server.UseClientDisconnectedHandler(x => {
+                           Console.WriteLine(x.ClientId + "断开连接");
+                       });
+                   });
+        }
+    }
+}

+ 18 - 15
HiTeachCE/Models/WeChatUser.cs

@@ -1,20 +1,25 @@
-using System;
+using SqlSugar;
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
 
 namespace HiTeachCE.Models
 {
+    [SugarTable("WeChatUser")]
     public class WeChatUser : Model
     {
+        [SugarColumn(IsNullable = false, IsPrimaryKey = true)]
         public string id { set; get; }
         /// <summary>
         /// 真实姓名
         /// </summary>
+        [SugarColumn(IsNullable = true)]
         public string fullName { get; set; }
         /// <summary>
         /// 昵称
         /// </summary>
+        [SugarColumn(IsNullable = false)]
         public string nickName { get; set; }
         /// <summary>
         /// 性别
@@ -23,47 +28,45 @@ namespace HiTeachCE.Models
         /// <summary>
         /// unionId
         /// </summary>
+        [SugarColumn(IsNullable = true)]
         public string unionId { get; set; }
         /// <summary>
         /// 头像
         /// </summary>
+        [SugarColumn(IsNullable = true)]
         public string avatarUrl { get; set; }
-        /// <summary>
-        /// 
-        /// </summary>
-        public string countryId { get; set; }
+
         /// <summary>
         /// 国家
         /// </summary>
+        [SugarColumn(IsNullable = true)]
         public string country { get; set; }
-        /// <summary>
-        /// 
-        /// </summary>
-        public string provinceId { get; set; }
+
         /// <summary>
         /// 省
         /// </summary>
+        [SugarColumn(IsNullable = true)]
         public string province { get; set; }
-        /// <summary>
-        /// 市
-        /// </summary>
-        public string cityId { get; set; }
+
         /// <summary>
         /// 
         /// </summary>
+        [SugarColumn(IsNullable = true)]
         public string city { get; set; }
         /// <summary>
         /// 注册时间
         /// </summary>
         public long registerTime { get; set; }
+        [SugarColumn(IsNullable = true)]
         public string phoneCode { get; set; }
         /// <summary>
         /// 手机号
         /// </summary>
+        [SugarColumn(IsNullable = true)]
         public string cellphone { get; set; }
         // 用户标识
+        [SugarColumn(IsNullable = true)]
         public string openId { get; set; }
-        public string language { get; set; }
-        public string appid { get; set; }
+      
     }
 }

+ 48 - 40
HiTeachCE/Services/WeChatService.cs

@@ -6,10 +6,12 @@ using Microsoft.Extensions.Configuration;
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Linq.Expressions;
 using System.Security.Claims;
 using System.Threading.Tasks;
 using TEAMModelOS.SDK.Context.Configuration;
 using TEAMModelOS.SDK.Extension.JwtAuth.Models;
+using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
 using TEAMModelOS.SDK.Helper.Common.JsonHelper;
 using TEAMModelOS.SDK.Helper.Network.HttpHelper;
 using JwtSetting = HiTeachCE.Extension.JwtSetting;
@@ -18,6 +20,11 @@ namespace HiTeachCE.Services
 {
     public class WeChatService : IBusinessService
     {
+        public WeChatUserService weChatUserService;
+        public WeChatService(WeChatUserService _weChatUserService) {
+            weChatUserService = _weChatUserService;
+        }
+
         public async Task<object> VerifyWeChat(Dictionary<string, object> dict)
         {
             if (dict.TryGetValue("code", out object code))
@@ -143,7 +150,7 @@ namespace HiTeachCE.Services
         /// <param name="unionid"></param>
         /// <param name="access_token"></param>
         /// <returns></returns>
-        public async Task<WeChatUser> GetWeChatUserInfo(string session_key, Dictionary<string, object> dict)
+        public   WeChatUser GetWeChatUserInfo(string session_key, Dictionary<string, object> dict)
         {
             string enData = "";
             if (dict.TryGetValue("encryptedData", out object encryptedData) && dict.TryGetValue("iv", out object iv))
@@ -175,20 +182,43 @@ namespace HiTeachCE.Services
             MiniAPPUserInfo miniAPPUser = enData.FromApiJson<MiniAPPUserInfo>();
             if (miniAPPUser != null)
             {
-                WeChatUser weChatUser = new WeChatUser();
-                weChatUser.id = miniAPPUser.unionId;
-              //  weChatUser.PartitionKey = miniAPPUser.country;
-                weChatUser.nickName = miniAPPUser.nickName;
-                weChatUser.gender = miniAPPUser.gender;
-                weChatUser.avatarUrl = miniAPPUser.avatarUrl;
-                weChatUser.country = miniAPPUser.country;
-                weChatUser.city = miniAPPUser.city;
-                weChatUser.province = miniAPPUser.province;
-                weChatUser.openId = miniAPPUser.openId;
-                weChatUser.unionId = miniAPPUser.unionId;
-                weChatUser.appid = miniAPPUser.watermark.appid;
-             //   await SaveOrUpdate<WeChatUser>(weChatUser);
-                return weChatUser;
+
+                Expression<Func<WeChatUser, bool>> linq = null;
+                linq = l => l.unionId == miniAPPUser.unionId;
+                var weChatUsers = weChatUserService.GetList(linq);
+
+                
+                //   await SaveOrUpdate<WeChatUser>(weChatUser);
+             
+                if (weChatUsers.IsNotEmpty())
+                {
+                    var weChatUser = weChatUsers[0];
+                    weChatUser.nickName = miniAPPUser.nickName;
+                    weChatUser.gender = miniAPPUser.gender;
+                    weChatUser.avatarUrl = miniAPPUser.avatarUrl;
+                    weChatUser.country = miniAPPUser.country;
+                    weChatUser.city = miniAPPUser.city;
+                    weChatUser.province = miniAPPUser.province;
+                    weChatUser.openId = miniAPPUser.openId;
+                    weChatUser.unionId = miniAPPUser.unionId;
+                    weChatUserService.Update(weChatUser);
+                    return weChatUser;
+                }
+                else {
+                    var   weChatUser = new WeChatUser();
+                    weChatUser.id = Guid.NewGuid().ToString();
+                    weChatUser.nickName = miniAPPUser.nickName;
+                    weChatUser.gender = miniAPPUser.gender;
+                    weChatUser.avatarUrl = miniAPPUser.avatarUrl;
+                    weChatUser.country = miniAPPUser.country;
+                    weChatUser.city = miniAPPUser.city;
+                    weChatUser.province = miniAPPUser.province;
+                    weChatUser.openId = miniAPPUser.openId;
+                    weChatUser.unionId = miniAPPUser.unionId;
+                    weChatUser.registerTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
+                    weChatUserService.Insert(weChatUser);
+                    return weChatUser;
+                }
             }
             else
             {
@@ -198,7 +228,7 @@ namespace HiTeachCE.Services
         public async Task<JwtResponse> MiniAPPLogin(Dictionary<string, object> dict)
         {
             MiniAPPLoginInfo loginInfo = await VerifyMiniAPP(dict);
-            WeChatUser weChatUser = await GetWeChatUserInfo(loginInfo.session_key, dict);
+            WeChatUser weChatUser =   GetWeChatUserInfo(loginInfo.session_key, dict);
             JwtResponse jwt = CreateJwtToken(weChatUser, loginInfo.session_key);
             LoginInfo login = new LoginInfo();
             login.id = Guid.NewGuid().ToString();
@@ -219,8 +249,8 @@ namespace HiTeachCE.Services
                 model.Claims.Add(new Claim(JwtClaimTypes.SessionId, sessionKey));
                 model.Claims.Add(new Claim(JwtClaimTypes.Name, user.nickName));
                 model.Claims.Add(new Claim(JwtClaimTypes.Id, user.unionId));
-                model.Claims.AddRange("Student".Split(',').Select(s => new Claim(JwtClaimTypes.Role, s)));
-                model.Roles.Add("Student");
+                model.Claims.AddRange("learner".Split(',').Select(s => new Claim(JwtClaimTypes.Role, s)));
+                model.Roles.Add("learner");
                 JwtResponse jwtResponse = JwtHelper.IssueJWT(model);
                 return jwtResponse;
             }
@@ -229,27 +259,5 @@ namespace HiTeachCE.Services
                 throw new Exception("Validation failure,user is null !");
             }
         }
-        public JwtResponse CreateJwtToken(LoginInfo login, string tiket)
-        {
-            ClaimModel model = new ClaimModel
-            {
-                Scope = "WebAPP"
-            };
-            if (login != null)
-            {
-                model.Claims.Add(new Claim(JwtClaimTypes.SessionId, tiket));
-                model.Claims.Add(new Claim(JwtClaimTypes.Name, login.Name));
-                model.Claims.Add(new Claim(JwtClaimTypes.Id, login.TeamModelId));
-                model.Claims.AddRange("Teacher".Split(',').Select(s => new Claim(JwtClaimTypes.Role, s)));
-                model.Roles.Add("Teacher");
-                JwtResponse jwtResponse = JwtHelper.IssueJWT(model);
-                return jwtResponse;
-            }
-            else
-            {
-                throw new Exception("Validation failure,user is null !");
-            }
-        }
-
     }
 }

+ 14 - 0
HiTeachCE/Services/WeChatUserService.cs

@@ -0,0 +1,14 @@
+using HiTeachCE.Context;
+using HiTeachCE.Models;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using TEAMModelOS.SDK.Context.Configuration;
+
+namespace HiTeachCE.Services
+{
+    public class WeChatUserService : DBContext<WeChatUser>, IBusinessService
+    {
+    }
+}

+ 5 - 186
HiTeachCE/Startup.cs

@@ -30,6 +30,7 @@ using TEAMModelOS.SDK.Extension.JwtAuth;
 using static HiTeachCE.Controllers.LoginController;
 using VueCliMiddleware;
 using Microsoft.AspNetCore.SpaServices;
+using HiTeachCE.Extension.Mqtt;
 
 namespace HiTeachCE
 {
@@ -82,139 +83,7 @@ namespace HiTeachCE
                 x.MultipartBodyLengthLimit = long.MaxValue; // In case of multipart
                 x.MultipartHeadersLengthLimit = int.MaxValue;
             });
-            services.AddHostedMqttServerWithServices(
-            builder =>
-            {
-               //builder.WithDefaultEndpoint();
-
-                builder.WithDefaultEndpointPort(3000);
-                builder.WithConnectionValidator(c =>
-                {
-                    //从IServiceCollection中构建     ServiceProvider, 用以使用注入访问数据库的服务
-                    //  var serprovider = services.BuildServiceProvider();
-
-                    //  _logger.LogInformation($" ClientId:{c.ClientId} Endpoint:{c.Endpoint} Username:{c.Username} Password:{c.Password} WillMessage:{c.WillMessage}");
-
-                    //if (c.ClientId.Length < 5)
-                    //{
-                    //    c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
-                    //    return;
-                    //}
-
-                    /**
-                    MQTTInfo info= RedisHelper.HGet<MQTTInfo>("mqtt:"+c.ClientId, c.ClientId);
-                    if (info != null)
-                    {
-                        if (c.Username != info.username)
-                        {
-                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
-                            return;
-                        }
-                        if (!BCrypt.Net.BCrypt.Verify(c.Password,info.password))
-                        {
-                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
-                            return;
-                        }
-                    }
-                    else {
-                        c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
-                        return;
-                    }
-                   c.ReasonCode = MqttConnectReasonCode.Success;
-                    **/
-                })
-                .WithApplicationMessageInterceptor(context =>
-                   {
-                       ///发送消息拦截器
-                       ///
-                       /**
-                       MQTTInfo info = RedisHelper.HGet<MQTTInfo>("mqtt:" + context.ClientId, context.ClientId);
-                       if (info != null)
-                       {
-                           bool match = false;
-                           foreach (string topic in info.topic)
-                           {
-                               //if (context.TopicFilter.Topic .StartsWith(topic)) {
-                               if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, topic))
-                               {
-                                   match = true;
-                                   break;
-                               }
-                           }
-                           if (match)
-                           {
-                               context.AcceptPublish = true;
-                           }
-                           else
-                           {
-                               context.AcceptPublish = false;
-                           }
-                       }
-                       else {
-                           context.AcceptPublish = false;
-                       }
-                       **/
-                       //if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "/myTopic/WithTimestamp/#"))
-                       //{
-                       //    context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
-                       //}
-
-                       //if (context.ApplicationMessage.Topic == "not_allowed_topic")
-                       //{
-                       //    context.AcceptPublish = false;
-                       //    context.CloseConnection = true;
-                       //}
-
-                       // _logger.Log(LogLevel.Information, $"clientId:{context.ClientId}, topic:{context.ApplicationMessage.Topic}");
-                       //  _logger.Log(LogLevel.Information, $"Payload:{Encoding.Default.GetString(context.ApplicationMessage.Payload)}");
-                   })///订阅拦截验证
-                .WithSubscriptionInterceptor((context) =>
-               {
-                   /**
-                   MQTTInfo info = RedisHelper.HGet<MQTTInfo>("mqtt:" + context.ClientId, context.ClientId);
-                   if (info != null)
-                   {
-                       bool match = false;
-                       foreach (string topic in info.topic)
-                       {
-                           //if (context.TopicFilter.Topic .StartsWith(topic)) {
-                           if (MqttTopicFilterComparer.IsMatch(context.TopicFilter.Topic, topic))
-                           {
-                               match = true;
-                               break;
-                           }
-                       }
-                       if (match)
-                       {
-                           context.AcceptSubscription = true;
-                       }
-                       else
-                       {
-                           context.AcceptSubscription = false;
-                       }
-                   }
-                   else {
-                       context.AcceptSubscription = false;
-                   }
-                   **/
-                   //   context.ClientId
-                   //if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
-                   //{
-                   //    context.AcceptSubscription = false;
-                   //}
-
-                   //if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
-                   //{
-                   //    context.AcceptSubscription = false;
-                   //    context.CloseConnection = true;
-                   //}
-
-                   // context.TopicFilter.Topic.start
-               });
-            });
-            services.AddMqttTcpServerAdapter();
-            services.AddMqttWebSocketServerAdapter();
-            services.AddMqttConnectionHandler().AddConnections();
+            services.MQTTConnection();
         }
 
         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -248,7 +117,8 @@ namespace HiTeachCE
             //    typeof(Lecturer),
             //    typeof(Member),
             //    typeof(Organization),
-            //    typeof(Subscriber)
+            //    typeof(Subscriber),
+            //    typeof(WeChatUser)
             //    );
             app.UseRouting();
             app.UseAuthentication();
@@ -272,58 +142,7 @@ namespace HiTeachCE
                 endpoints.MapFallbackToFile("index.html");
 #endif
             });
-            app.UseMqttServer(
-               server =>
-               {
-                   server.UseApplicationMessageReceivedHandler(e =>
-                   {
-
-                   });
-
-                   server.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
-                   {
-                       Console.WriteLine(
-                           $"'{e.ClientId}' reported '{e.ApplicationMessage.Topic}' > '{Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0])}'",
-                           ConsoleColor.Magenta);
-                   });
-                   server.StartedHandler = new MqttServerStartedHandlerDelegate((
-                       e =>
-                       {
-
-                       }));
-                   server.StoppedHandler = new MqttServerStoppedHandlerDelegate(
-                       e =>
-                       {
-
-                       });
-
-                   server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(
-                       e =>
-                       {
-                            //  _logger.LogInformation($"{e.ClientId} is connectioned");
-                            // _logger.LogInformation($"目前连接总数:{ server.GetClientStatusAsync().Result.Count}");
-                        });
-                   server.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(
-                       e =>
-                       {
-
-                            // _logger.LogInformation($"{e.ClientId} is disconnectioned");
-                            //  _logger.LogInformation($"目前连接总数:{ server.GetClientStatusAsync().Result.Count}");
-                        });
-                    //开启订阅以及取消订阅
-                    server.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate((args) => {
-                       Console.WriteLine("订阅" + args.ClientId + args.TopicFilter.Topic);
-                   });
-                   server.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate((args) => {
-                       Console.WriteLine("取消订阅" + args.ClientId + args.TopicFilter);
-                   });
-                   server.UseClientConnectedHandler(x => {
-                       Console.WriteLine(x.ClientId + "连接");
-                   });
-                   server.UseClientDisconnectedHandler(x => {
-                       Console.WriteLine(x.ClientId + "断开连接");
-                   });
-               });
+            app.UseMqtt();
         }
     }
 }