123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491 |
- 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;
- 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 SshNet.Security.Cryptography;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Security.Claims;
- using System.Text.Json;
- using System.Threading.Tasks;
- using System.Web;
- 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 LoginController : BaseController
- {
- public static int smsTTL = 4 * 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;
- private readonly OrganizationService organizationService;
- private readonly MemberService memberService;
- private readonly ActivationCodeService activationCodeService;
- private readonly SecurityCodeHelper securityCode;
- public LoginController(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>
- [HttpPost("dingLogin")]
- public BaseJosnRPCResponse DingLogin(JosnRPCRequest<string> request)
- {
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
-
- string accessKey = BaseConfigModel.Configuration["DingAuth:appId"];
- string appSecret = BaseConfigModel.Configuration["DingAuth:appSecret"];
- IDingTalkClient client = new DefaultDingTalkClient(BaseConfigModel.Configuration["DingAuth: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);
- list[0].dingOpenid = rsp.UserInfo.Openid;
- list[0].dingUnionid = rsp.UserInfo.Unionid;
- list[0].dingNick = rsp.UserInfo.Nick;
- lecturerService.Update(list[0]);
- 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>
- /// 重置密码
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("resetPassword")]
- public BaseJosnRPCResponse ResetPassword(JosnRPCRequest<UserPwdRandom> request)
- {
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
- string captcha = RedisHelper.HGet<string>("captcha:" + request.@params.randCode, request.@params.randCode);
- if (!string.IsNullOrEmpty(captcha) && captcha.Equals(request.@params.captcha.ToLower()))
- {
- string account = request.@params.account;
- Expression<Func<Lecturer, bool>> expression = null;
- expression = e => e.cellphone == account;
- List<Lecturer> lecturers = lecturerService.GetList(expression);
- if (lecturers.IsNotEmpty())
- {
- Lecturer lecturer = lecturers[0];
- string validPassword = BCrypt.Net.BCrypt.HashPassword(request.@params.password);
- lecturer.password = validPassword;
- return builder.Data(lecturerService.Update(lecturer)).build();
- }
- else
- {
- throw new BizException("手机号未注册!", 2);
- }
- }
- else
- {
- throw new BizException("验证码错误!", 2);
- }
- }
- /// <summary>
- /// 登录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("accountLogin")]
- public BaseJosnRPCResponse AccountLogin(JosnRPCRequest<UserPwdRandom> request)
- {
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
- string captcha = RedisHelper.HGet<string>("captcha:" + request.@params.randCode, request.@params.randCode);
- if (!string.IsNullOrEmpty(captcha) && captcha.Equals(request.@params.captcha.ToLower()))
- {
- string account = request.@params.account;
- Expression<Func<Lecturer, bool>> expression = null;
- expression = e => e.account == account;
- expression = expression.Or(x => x.cellphone == account);
- List<Lecturer> lecturers = lecturerService.GetList(expression);
- if (lecturers.IsNotEmpty())
- {
- Lecturer lecturer = lecturers[0];
- if (!string.IsNullOrEmpty(lecturer.password))
- {
- bool validPassword = BCrypt.Net.BCrypt.Verify(request.@params.password, lecturer.password);
- if (validPassword)
- {
- Dictionary<string, object> dict = UserValid(lecturer.cellphone);
- 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);
- }
- }
- /// <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))
- {
- List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
- if (RootUsers.Contains(cellphone) && smsCode.Equals("000000"))
- {
- ///验证通过 验证信息存放在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
- {
- 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();
- }
- // [HttpPost("GetOrgByUid")]
- public List<Organization> GetOrgByUid(string uid)
- {
- Expression<Func<Member, bool>> mlinq = null;
- mlinq = m => m.unionid == uid && m.status == 1;
- List<Member> members = memberService.GetList(mlinq);
- if (members.IsNotEmpty())
- {
- Expression<Func<Organization, bool>> olinq = null;
- olinq = o => members.Select(x => x.orgCode).ToList().Contains(o.code) && o.status == 1;
- List<Organization> organizations = organizationService.GetList(olinq);
- ///返回前端后倒计时10秒自动选择组织机构,以防再次验证的时候 reids过期
- return organizations;
- }
- else { return null; }
- }
- 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);
- lecturer.password = "";
- Expression<Func<Member, bool>> expression = null;
- expression = m => m.unionid == lecturer.unionid;
- bool access = memberService.GetList(expression).IsNotEmpty();
- return new Dictionary<string, object> { { "status", 2 }, { "jwt", jwtResponse }, { "user", lecturer },{ "access", access } };
- }
- 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,
- avatar= "https://cdhabook.teammodel.cn/avatar/usertile"+random.Next(10, 44)+".png"
- }
- }
- };
- }
- }
- /// <summary>
- /// 钉钉初始化登录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("dingConfig")]
- public BaseJosnRPCResponse DingConfig(JosnRPCRequest<object> request)
- {
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
- string appId = BaseConfigModel.Configuration["DingAuth:appId"];
- // string appSecret = BaseConfigModel.Configuration["DingAuth:appSecret"];
- string callback = BaseConfigModel.Configuration["DingAuth:callback"];
- return builder.Data(new { appId,callback}).build();
- }
- /// <summary>
- /// 初始化登录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("init")]
- public BaseJosnRPCResponse Init(JosnRPCRequest<string> request)
- {
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
- if (!string.IsNullOrEmpty(request.@params))
- {
- var code = securityCode.GetRandomEnDigitalText(4).ToLower();
- var imgbyte = securityCode.GetEnDigitalCodeByte(code);
- string base64 = "data:image/png;base64," + Convert.ToBase64String(imgbyte);
- RedisHelper.HSet("captcha:" + request.@params, request.@params, code);
- RedisHelper.Expire("captcha:" + request.@params, smsTTL);
- return builder.Data(base64).build();
- }
- else
- {
- throw new BizException("随机码为空!", 2);
- }
- }
- /// <summary>
- /// 发送短信
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("sendSMS")]
- public async Task<BaseJosnRPCResponse> SendSMS(JosnRPCRequest<CaptchaSms> request)
- {
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
- 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)
- {
- string key = request.@params.cellphone;
- if (RedisHelper.Exists(key))
- {
- string[] vals = RedisHelper.HVals<string>(key);
- if (vals != null && vals.Length > 0)
- {
- Dictionary<string, object> data = new Dictionary<string, object>() { { "msgid", vals[0] }, { "repeat", true } };
- return builder.Data(data).build();
- }
- else
- {
- return builder.Data(await SendMsg(key)).build();
- }
- }
- else
- {
- return builder.Data(await SendMsg(key)).build();
- }
- }
- else
- {
- throw new BizException("验证码错误!", 2);
- }
- }
- private static async Task<Dictionary<string, object>> SendMsg(string key)
- {
- 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;
- RedisHelper.Del(new string[] { key });
- RedisHelper.HSet(key, key, msgidstr);
- RedisHelper.Expire(key, smsTTL);
- return new Dictionary<string, object>() { { "msgid", msgidstr }, { "repeat", false } };
- }
- else
- {
- string resdata = await HttpClientHelper.Post(
- BaseConfigModel.Configuration["JPush:Push"],
- BaseConfigModel.Configuration["JPush:AppKey"],
- BaseConfigModel.Configuration["JPush:Secret"], data);
- JsonElement element = resdata.FromApiJson<JsonElement>();
- if (element.TryGetProperty("msg_id", out JsonElement msgid))
- {
- string msgidstr = msgid.GetString();
- RedisHelper.Del(new string[] { key });
- RedisHelper.HSet(key, key, msgidstr);
- RedisHelper.Expire(key, smsTTL);
- return new Dictionary<string, object>() { { "msgid", msgidstr }, { "repeat", false } };
- }
- else
- {
- throw new BizException("短信发送失败!", 2);
- }
- }
- }
- }
- }
|