Browse Source

调整 登录 认证及注册设备

黄贺彬 5 years ago
parent
commit
57db908a3a

+ 3 - 3
HiTeachCE/Controllers/BaseController.cs

@@ -13,7 +13,7 @@ namespace HiTeachCE.Controllers
 {
     public class BaseController : Controller
     {
-        public List<string> GetLoginUser(string claimType)
+        public string GetLoginUser(string claimType)
         {
             var tokenHeader = "";
             HttpRequest request = HttpContext.Request;
@@ -34,12 +34,12 @@ namespace HiTeachCE.Controllers
             }
             ClaimModel claimModel = JwtHelper.SerializeJWT(tokenHeader);
             claimModel.Claim.TryGetValue(claimType, out var claimValue);
-            List<string> claimValues = new List<string>();
+            string claimValues = "";
             foreach (Claim claim in claimModel.Claims)
             {
                 if (claim.Type.Equals(claimType))
                 {
-                    claimValues.Add(claim.Value);
+                    claimValues= claim.Value;
                 }
             }
             return claimValues;

+ 330 - 4
HiTeachCE/Controllers/LecturerController.cs

@@ -1,25 +1,68 @@
-using HiTeachCE.Context;
+using Hei.Captcha;
+using HiTeachCE.Context;
+using HiTeachCE.Extension;
+using HiTeachCE.Helpers;
 using HiTeachCE.Models;
 using HiTeachCE.Services;
+using IdentityModel;
 using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Configuration;
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Linq.Expressions;
+using System.Security.Claims;
+using System.Text.Json;
 using System.Threading.Tasks;
+using TEAMModelOS.SDK.Context.Configuration;
+using TEAMModelOS.SDK.Context.Exception;
 using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
 using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
+using TEAMModelOS.SDK.Extension.JwtAuth.Models;
+using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
+using TEAMModelOS.SDK.Helper.Common.JsonHelper;
+using TEAMModelOS.SDK.Helper.Security.ShaHash;
 
 namespace HiTeachCE.Controllers
 {
     [Route("api/[controller]")]
     [ApiController]
    
-    public class LecturerController : Controller
+    public class LecturerController : BaseController
     {
+        public static int smsTTL = 1 * 60;
+        public static int ticketTTL = 1 * 24 * 60 * 60;
+        public static int freeTTL = 7 * 24 * 60 * 60;
+        public static int deviceTTL = 1 * 24 * 60 * 60;
+        public static string freeOrg = "7f847a9f05224184a5d01ee69a6b00d6";
+        public static string model_teach = "teach";
+        public static string model_prepare = "prepare";
         private readonly LecturerService lecturerService;
-        public LecturerController(LecturerService lecturer) {
+        private readonly OrganizationService organizationService;
+        private readonly MemberService memberService;
+        private readonly ActivationCodeService activationCodeService;
+        private readonly SecurityCodeHelper securityCode;
+        public LecturerController(LecturerService lecturer, OrganizationService organization, MemberService member, ActivationCodeService activationCode, SecurityCodeHelper _securityCode) {
             lecturerService = lecturer;
+            organizationService = organization;
+            memberService = member;
+            activationCodeService = activationCode;
+            securityCode = _securityCode;
+        }
+
+        /// <summary>
+        /// 获取知识
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpGet("GetId")]
+        public BaseJosnRPCResponse GetList()
+        {
+            // request.@params.TryAdd("PartitionKey", request.lang);
+            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
+            List<Lecturer> data = lecturerService.GetList();
+            return builder.Data(Guid.NewGuid()).build();
         }
         /// <summary>
         /// 获取知识
@@ -62,5 +105,288 @@ namespace HiTeachCE.Controllers
            
             return builder.Data(Guid.NewGuid()).build();
         }
-    }
+        /// <summary>
+        /// 注册装置
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("regist")]
+        [Authorize(Policy = "lecturer")]
+
+        public BaseJosnRPCResponse Regist(JosnRPCRequest<Dictionary<string, string>> request)
+        {
+            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
+            string unionid = GetLoginUser(JwtClaimTypes.Id);
+            /**
+             "params": {
+                    "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
+                    "clientId": "931dee8c-74be-4c9b-a602-c74583b0e985",
+                }
+             */
+            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 (RedisHelper.HExists("device:" + deviceId, orgCode))
+                    {
+                    }
+                    else
+                    {
+                        RedisHelper.HSet("device:" + deviceId, orgCode, unionid);
+                        RedisHelper.Expire("device:" + deviceId, deviceTTL);
+                    }
+                    return builder.Data(new Dictionary<string, object> { { "deviceId", deviceId } }).build();
+                }
+                else
+                {
+                    throw new BizException("授权失败!", 2);
+                }
+            }
+            else
+            {
+                throw new BizException("参数错误!", 2);
+            }
+        }
+
+
+
+        /// <summary>
+        /// 教学认证
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("auth")]
+        [Authorize(Policy = "lecturer")]
+        public BaseJosnRPCResponse Auth(JosnRPCRequest<object> request)
+        {
+            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
+            string unionid =  GetLoginUser(JwtClaimTypes.Id);
+            Expression<Func<Member, bool>> mlinq = null;
+            mlinq = m => m.unionid == unionid;
+            List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();
+            List<Member> members = memberService.GetList(mlinq);
+            if (members.IsNotEmpty())
+            {
+                foreach (var code in members)
+                {
+                   dict.Add(ActivationValid(code.orgCode, unionid));
+                }
+            }
+            else
+            {
+                long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
+                ///处理该机构是否激活人数达到上线
+                Expression<Func<Member, bool>> limitlinq = null;
+                limitlinq = m => m.orgCode == freeOrg && (m.expires > time || m.expires == -1) && m.status == 1;
+                List<Member> countMembers = memberService.GetList(limitlinq);
+                Expression<Func<ActivationCode, bool>> alinq = null;
+                alinq = m => m.orgCode == freeOrg && m.status == 1;
+                List<ActivationCode> activationCodes = activationCodeService.GetList(alinq);
+                if (activationCodes.IsNotEmpty())
+                {
+                    //判断组织机构人员是否已经达到最大激活数量
+                    if (countMembers.IsNotEmpty() && countMembers.Count >= activationCodes[0].maximum)
+                    {
+                        //throw new BizException(":HiTeachCE(测试)授权人数超过上限!", 2);
+                    }
+                    else
+                    {
+                        Member member = new Member
+                        {
+                            id = Guid.NewGuid().ToString(),
+                            orgCode = freeOrg,
+                            role = "lecturer",
+                            status = 1,
+                            expires = time + freeTTL,
+                            unionid = unionid
+                        };
+                        bool flag = memberService.Insert(member);
+                        if (flag)
+                        {
+
+                            dict.Add(ActivationValid(freeOrg, unionid));
+                        }
+                        else
+                        {
+                            //throw new BizException("无法加入:HiTeachCE(测试)!", 2);
+                        }
+                    }
+                }
+                else { 
+                
+                }
+            }
+            return builder.Data(dict).build();
+        }
+
+
+        public Dictionary<string, object> ActivationValid(string orgCode,string unionid) {
+            //调用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 || activationCodes[0].expires == -1)
+            {
+                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 && (x.expires > time || x.expires == -1)).Select(x => x.unionid).ToList().Contains(unionid))
+                    {
+                        dict["org"] = new { orgCode = org.code, name = org.name };
+                        dict.Add("flag", true);
+                    }
+                    else {
+                        dict.Add("msg", "组织机构未对该用户授权或已经过期!");
+                    }
+                 }
+            }
+            else {
+                dict.Add("msg", "产品授权已经过期!");
+            }
+            return dict;
+        }
+            /// <summary>
+            /// 登录
+            /// </summary>
+            /// <param name="request"></param>
+            /// <returns></returns>
+        [HttpPost("phoneLogin")]
+        public async Task<BaseJosnRPCResponse> PhoneLogin(JosnRPCRequest<Dictionary<string, string>> request)
+        {
+            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
+            if (request.@params.TryGetValue("cellphone", out string cellphone) &&
+                request.@params.TryGetValue("smsCode", out string smsCode)
+                )
+            {
+                string ticket = ShaHashHelper.GetSHA1(cellphone + smsCode);
+                if (RedisHelper.Exists("ticket:" + ticket))
+                {
+                    Dictionary<string, object> dict = UserValid(cellphone);
+                    dict.Add("ticket", ticket);
+                    return builder.Data(dict).build();
+                }
+                if (RedisHelper.Exists(cellphone))
+                {
+                    string[] vals = RedisHelper.HVals<string>(cellphone);
+                    if (vals != null && vals.Length > 0)
+                    {
+                        string resdata = await HttpClientHelper.Post(
+                        BaseConfigModel.Configuration["JPush:Valid"].Replace("{msg_id}", vals[0]),
+                        BaseConfigModel.Configuration["JPush:AppKey"],
+                        BaseConfigModel.Configuration["JPush:Secret"], new Dictionary<string, object> { { "code", smsCode } });
+                        JsonElement element = resdata.FromApiJson<JsonElement>();
+                        if (element.TryGetProperty("is_valid", out JsonElement json))
+                        {
+                            if (json.GetBoolean())
+                            {
+                                ///验证通过 验证信息存放在reids
+                                RedisHelper.HSet("ticket:" + ticket, cellphone, cellphone);
+                                RedisHelper.Expire("ticket:" + ticket, ticketTTL);
+                                Dictionary<string, object> dict = UserValid(cellphone);
+                                dict.Add("ticket", ticket);
+                                return builder.Data(dict).build();
+                            }
+                            else
+                            {
+                                throw new BizException("短信验证码过期!", 2);
+                            }
+                        }
+                        else
+                        {
+                            throw new BizException("短信验证码过期!", 2);
+                        }
+                    }
+                    else
+                    {
+                        throw new BizException("短信验证码过期!", 2);
+                    }
+                }
+                else
+                {
+                    throw new BizException("短信验证码过期!", 2);
+                }
+            }
+            else
+            {
+                throw new BizException("手机号、短信验证码未填写!", 2);
+            }
+
+            //如果验证通过则将验证信息缓存至redis 以防再次远程验证不通过
+
+            //string uid = "";
+            //List<Organization> organizations = GetOrgByUid(uid);
+            //return builder.Data(organizations).build();
+        }
+        private Dictionary<string, object> UserValid(string cellphone)
+        {
+            Expression<Func<Lecturer, bool>> linq = null;
+            linq = m => m.cellphone == cellphone;
+            List<Lecturer> lecturers = lecturerService.GetList(linq);
+            if (lecturers.IsNotEmpty())
+            {
+                var lecturer = lecturers[0];
+                   ClaimModel claimModel = new ClaimModel
+                {
+                    Scope = "WebApp"
+                };
+                claimModel.Claims.Add(new Claim(JwtClaimTypes.Name, lecturer.username));
+                claimModel.Claims.Add(new Claim(JwtClaimTypes.Id, lecturer.unionid));
+                claimModel.Claims.Add(new Claim(JwtClaimTypes.PhoneNumber, lecturer.cellphone));
+                List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
+                string role = "admin,lecturer";
+                if (RootUsers.Contains(lecturers[0].cellphone)) {
+                    role = "root," + role;
+                }
+                // claimModel.Claims.Add(new Claim(JwtClaimTypes.Role, role));
+                // 可以将一个用户的多个角色全部赋予;
+                claimModel.Claims.AddRange(role.Split(',').Select(s => new Claim(JwtClaimTypes.Role, s)));
+                // 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 } };
+            }
+            else {
+                //不存在用户则新增一个
+                Random random = new Random();
+                string seed = new string(Constant.az09);
+                string pfx = "";
+                for (int i = 0; i < 4; i++)
+                {
+                    string c = seed.ToCharArray()[random.Next(0, seed.Length)] + "";
+                    seed.Replace(c, "");
+                    pfx = pfx + c;
+                }
+                return new Dictionary<string, object> {
+                    { "status",1},
+                    { "user",new Lecturer
+                        {
+                            id= Guid.NewGuid().ToString(),
+                            unionid= Guid.NewGuid().ToString("N"),
+                            username=cellphone+"手机用户",
+                            password="",
+                            account="hitmd-"+cellphone.Substring(cellphone.Length-4,4)+"#"+pfx,
+                            areaCode="86",
+                            registerTime=new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
+                            status=1,
+                            setaccount=0,
+                            cellphone=cellphone
+                        }
+                    }
+                };
+            }
+         }
+     }
 }

+ 18 - 18
HiTeachCE/Controllers/LoginController.cs

@@ -65,7 +65,7 @@ namespace HiTeachCE.Controllers
         public BaseJosnRPCResponse Regist(JosnRPCRequest<Dictionary<string, string>> request)
         {
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
-            List<string> ClientId = //new List<string>() { "fb564dde14df423cafac2085936e3b96" };
+             string  ClientId = //new List<string>() { "fb564dde14df423cafac2085936e3b96" };
            GetLoginUser(JwtClaimTypes.ClientId);
             /**
              "params": {
@@ -73,15 +73,15 @@ namespace HiTeachCE.Controllers
                     "clientId": "931dee8c-74be-4c9b-a602-c74583b0e985",
                 }
              */
-            if (request.@params.TryGetValue("deviceId", out string deviceId) && ClientId.IsNotEmpty())
+            if (request.@params.TryGetValue("deviceId", out string deviceId) && string.IsNullOrEmpty(ClientId))
             {
-                if (RedisHelper.HExists("device:" + ClientId[0], deviceId))
+                if (RedisHelper.HExists("device:" + ClientId, deviceId))
                 {
                 }
                 else
                 {
-                    RedisHelper.HSet("device:" + ClientId[0], deviceId, null);
-                    RedisHelper.Expire("device:" + ClientId[0], deviceTTL);
+                    RedisHelper.HSet("device:" + ClientId, deviceId, null);
+                    RedisHelper.Expire("device:" + ClientId, deviceTTL);
                 }
                 return builder.Data(new Dictionary<string, object> { { "deviceId", deviceId } }).build();
             }
@@ -109,14 +109,14 @@ namespace HiTeachCE.Controllers
              */
 
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
-            List<string> ClientId =// new List<string>() { "fb564dde14df423cafac2085936e3b96" };
+             string  ClientId =// new List<string>() { "fb564dde14df423cafac2085936e3b96" };
                  GetLoginUser(JwtClaimTypes.ClientId);
             string groupNum;
-            if (request.@params.TryGetValue("deviceId", out string deviceId) && ClientId.IsNotEmpty())
+            if (request.@params.TryGetValue("deviceId", out string deviceId) && string.IsNullOrEmpty(ClientId))
             {
-                if (RedisHelper.HExists("device:" + ClientId[0], deviceId))
+                if (RedisHelper.HExists("device:" + ClientId, deviceId))
                 {
-                    groupNum = RedisHelper.HGet<string>("device:" + ClientId[0], deviceId);
+                    groupNum = RedisHelper.HGet<string>("device:" + ClientId, deviceId);
                     if (string.IsNullOrEmpty(groupNum)) {
                         do
                         {
@@ -124,7 +124,7 @@ namespace HiTeachCE.Controllers
                         } while (RedisHelper.Exists("group:" + groupNum));
                         RedisHelper.HSet("group:" + groupNum, deviceId, null);
                         RedisHelper.Expire("group:" + groupNum, deviceTTL);
-                        RedisHelper.HSet("device:" + ClientId[0], deviceId, groupNum);
+                        RedisHelper.HSet("device:" + ClientId, deviceId, groupNum);
                     }
                 }
                 else { throw new BizException("装置未注册", 2); }
@@ -152,9 +152,9 @@ namespace HiTeachCE.Controllers
         [Authorize]
         public BaseJosnRPCResponse JoinGroup(JosnRPCRequest<Dictionary<string, string>> request)
         {
-            List<string> ClientId = GetLoginUser(JwtClaimTypes.ClientId);
-            List<string> Unionid = GetLoginUser(JwtClaimTypes.Id);
-            List<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;
             /**
@@ -184,12 +184,12 @@ namespace HiTeachCE.Controllers
             return builder.Data(dict).build();
         }
 
-        private static Dictionary<string, object> MqttInfo(List<string> ClientId, string deviceId, string groupNum, List<string> Unionid, List<string> Role)
+        private static Dictionary<string, object> MqttInfo( string  ClientId, string deviceId, string groupNum,  string  Unionid,  string  Role)
         {
             string brokerHostName = BaseConfigModel.Configuration["brokerHostName"];
 
             Dictionary<string, object> dict = new Dictionary<string, object>();
-            string password = brokerHostName + "/" + groupNum + "/" + deviceId + "/" + ClientId[0];
+            string password = brokerHostName + "/" + groupNum + "/" + deviceId + "/" + ClientId;
             //发给前端使用的
             string h1 = BCrypt.Net.BCrypt.HashPassword(password);
             //后端存储使用的
@@ -225,10 +225,10 @@ namespace HiTeachCE.Controllers
             };
             var groupMember = new MQTTMember
             {
-                clientId = ClientId[0],
+                clientId = ClientId,
                 deviceId = deviceId,
-                unionid = Unionid[0],
-                role = Role[0],
+                unionid = Unionid ,
+                role = "lecturer",
                 groupNum = groupNum
             };
             RedisHelper.HSet("group:" + groupNum, deviceId, groupMember);

+ 1 - 1
HiTeachCE/Models/Member.cs

@@ -12,8 +12,8 @@ namespace HiTeachCE.Models
         [SugarColumn(IsNullable = false, IsPrimaryKey = true)]
         public string id { get ; set ; }
         public string unionid { get; set; }
+        public string memberName { get; set; }
         public string orgCode { get; set; }
-
         /// <summary>
         ///  admin ,lecturer
         /// </summary>