using Ant.Core.Utils; using Ant.Core.WebApi.Enum; using Ant.Core.WebApi.Model; using Central.Control.WebApi.Cache; using Central.Control.WebApi.DbEntity; using Central.Control.WebApi.EFDbContext; using Central.Control.WebApi.Models.Request; using Central.Control.WebApi.Models.Response; using Central.Control.WebApi.Service.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Central.Control.WebApi.Service { /// /// /// public class LoginService: ILoginService { private readonly ICacheHelper _cacheHelper; private readonly IDbContext _dbContent; private readonly IUserService _userService; /// /// /// /// /// public LoginService( ICacheHelper cacheHelper, IDbContext dbContent, IUserService userService) { _cacheHelper = cacheHelper; _dbContent = dbContent; _userService = userService; } /// /// 设备登录接口 /// /// public ApiResult DeviceLogin(DeviceLoginRequestDto req) { var deviceInfo = _dbContent.Set().FirstOrDefault(p => p.Code == req.Code && p.Password == req.Password); if (deviceInfo == null) { return new ApiResult(ApiStatusCode.RecordNotFound, "用户名或密码不正确"); } // 1、验证密码正确,老token进行失效 var oldToken = _cacheHelper.Get(deviceInfo.Code); if (!string.IsNullOrWhiteSpace(oldToken)) { _cacheHelper.Remove(oldToken); } var loginSession = _dbContent.Set().FirstOrDefault(p => p.UserId == deviceInfo.Id); bool isAdd = false; if (loginSession == null) { isAdd = true; loginSession = new SYS_LoginSession() { Id = IdGenerator.NewId() }; } string token = IdGenerator.AntToken(); // 2、存库 loginSession.UserId = deviceInfo.Id; loginSession.UserName = deviceInfo.Code; loginSession.Token = token; loginSession.Expiration = DateTime.MaxValue; if (isAdd) { _dbContent.Set().Add(loginSession); } // 执行保存 _dbContent.SaveChanges(); // 3、存cache _cacheHelper.SetByNotExpired(deviceInfo.Code, token);// 这一份存一个凭证 _cacheHelper.SetByNotExpired(token, loginSession);// 这一份存真正的登录信息 DeviceLoginResponseDto result = new DeviceLoginResponseDto() { Token = token }; return new ApiResult(result); } /// /// 退出登录 /// /// public ApiResult Logout() { var session = _userService.GetLoginSession(); // 删除cache session _cacheHelper.Remove(session.UserName);// 这一份存一个凭证 _cacheHelper.Remove(session.Token);// 这一份存真正的登录信息 // 删除数据库session var e = _dbContent.Set().FirstOrDefault(m => m.UserId == session.UserId); _dbContent.Set().Remove(e); _dbContent.SaveChanges(); return new ApiResult(); } } }