LoginParse.cs 2.97 KB
/*
 * 登录解析
 * 处理登录逻辑,验证客户段提交的账号密码,保存登录信息
 */
using System;
using System.Collections.Generic;
using System.Linq;
using Hh.Mes.Common;
using Hh.Mes.Common.Redis;
using WebRepository;

namespace WebApp
{
    public class LoginParse
    {
        //private ICacheContext _cacheContext; ICacheContext cacheContext,
        public IUnitWork _unitWork;
        public LoginParse( IUnitWork unitWork)
        {
            //_cacheContext = cacheContext;
            _unitWork = unitWork;
        }

        public LoginResult Do(PassportLoginRequest model)
        {
            var result = new LoginResult();
            try
            {
                model.Trim();
                //获取应用信息
                var appInfo = _unitWork.FindSingle<SysInfo>(u => u.AppKey == model.AppKey);
                if (appInfo == null) throw new Exception("应用不存在");

                if (Encryption.Decrypt(appInfo.AppSecret) != "hhweb2.0") throw new Exception("应用密钥不正确!");
                //获取用户信息
                var userInfo = _unitWork.FindSingle<SysUser>(u => u.Account == model.Account);
                if (userInfo == null || userInfo.Account != model.Account) throw new Exception("登录失败,请检查用户名和密码!");
                if (Encryption.Decrypt(userInfo.Password) != model.Password) throw new Exception("登录失败,请检查用户名和密码!");
                
                var orgs = LoadByUser(userInfo.Id);
                var token = Guid.NewGuid().ToString("N");
                var currentSession = new UserAuthSession
                {
                    Account = model.Account,
                    Name = userInfo.Name,
                    Sex= userInfo.Sex,
                    Idcard = userInfo.Idcard,

                    Token= token,
                    Organizations = string.Join(",", orgs.Select(u => u.Name).ToList()),
                    CreateTime = DateTime.Now,
                };

                //创建Session
                //_cacheContext.Set(currentSession.Token, currentSession, DateTime.Now.AddDays(10));
                var cl = new RedisBase();
                cl.SetT(token, currentSession, cl.dayTime);
                result.Code = 200;
                result.ReturnUrl = appInfo.ReturnUrl;
                result.currentSession = currentSession;
                result.Token = token;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }

        public IEnumerable<SysDept> LoadByUser(int? userId)
        {
            var result = from userorg in _unitWork.Find<SysRelevance>(null)
                join org in _unitWork.Find<SysDept>(null) on userorg.SecondId equals org.Id
                where userorg.FirstId == userId && userorg.RelKey == Define.USERORG
                select org;
            return result;
        }
    }
}