public ResultDto Post([FromBody] CreateMessageBoardDto createMessageBoardDto) { MessageBoard messageBoard = _mapper.Map <MessageBoard>(createMessageBoardDto); messageBoard.Ip = this.GetIp(); messageBoard.Agent = Request.Headers["User-agent"].ToString(); messageBoard.UserHost = Dns.GetHostName(); messageBoard.System = LinCmsUtils.GetOsNameByUserAgent(messageBoard.Agent); if (messageBoard.Ip.IsNotNullOrEmpty()) { IpQueryResult ipQueryResult = LinCmsUtils.IpQueryCity(messageBoard.Ip); messageBoard.GeoPosition = ipQueryResult.errno == 0 ? ipQueryResult.data : ipQueryResult.errmsg; } LinUser linUser = _userService.GetCurrentUser(); if (linUser == null) { messageBoard.Avatar = "/assets/user/" + new Random().Next(1, 360) + ".png"; } else { messageBoard.Avatar = _currentUser.GetFileUrl(linUser.Avatar); } _messageBoardRepository.Insert(messageBoard); return(ResultDto.Success("留言成功")); }
public void Register(LinUser user) { bool isExistGroup = _groupRepository.Select.Any(r => r.Id == user.GroupId); if (!isExistGroup) { throw new LinCmsException("分组不存在", ErrorCode.NotFound); } bool isRepeatNickName = _userRepository.Select.Any(r => r.Nickname == user.Nickname); if (isRepeatNickName) { throw new LinCmsException("用户名重复,请重新输入", ErrorCode.RepeatField); } if (!string.IsNullOrEmpty(user.Email.Trim())) { var isRepeatEmail = _userRepository.Select.Any(r => r.Email == user.Email.Trim()); if (isRepeatEmail) { throw new LinCmsException("注册邮箱重复,请重新输入", ErrorCode.RepeatField); } } user.Active = 1; user.Admin = 1; user.Password = LinCmsUtils.Get32Md5(user.Password); _userRepository.Insert(user); }
public async Task CreateAsync(CreateMessageBoardDto createMessageBoardDto) { MessageBoard messageBoard = _mapper.Map <MessageBoard>(createMessageBoardDto); messageBoard.Ip = this.GetIp(); messageBoard.Agent = _httpContextAccessor.HttpContext.Request.Headers["User-agent"].ToString(); messageBoard.UserHost = Dns.GetHostName(); messageBoard.System = LinCmsUtils.GetOsNameByUserAgent(messageBoard.Agent); if (messageBoard.Ip.IsNotNullOrEmpty()) { IpQueryResult ipQueryResult = LinCmsUtils.IpQueryCity(messageBoard.Ip); messageBoard.GeoPosition = ipQueryResult.errno == 0 ? ipQueryResult.data : ipQueryResult.errmsg; } LinUser linUser = await _userService.GetCurrentUserAsync(); if (linUser == null) { messageBoard.Avatar = "/assets/user/" + new Random().Next(1, 360) + ".png"; } else { messageBoard.Avatar = _currentUser.GetFileUrl(linUser.Avatar); } await _messageBoardRepository.InsertAsync(messageBoard); }
private void HandlerException(ExceptionContext context, ResultDto apiResponse, int statusCode) { apiResponse.Request = LinCmsUtils.GetRequest(context.HttpContext); context.Result = new JsonResult(apiResponse) { StatusCode = statusCode, ContentType = "application/json", }; context.ExceptionHandled = true; }
private void HandlerException(ExceptionContext context, UnifyResponseDto apiResponse, int statusCode) { apiResponse.Request = LinCmsUtils.GetRequest(context.HttpContext); _logger.LogError(JsonConvert.SerializeObject(apiResponse)); context.Result = new JsonResult(apiResponse) { StatusCode = statusCode, ContentType = "application/json", }; context.ExceptionHandled = true; }
public void ChangePassword(ChangePasswordDto passwordDto) { string oldPassword = LinCmsUtils.Get32Md5(passwordDto.OldPassword); _userRepository.Select.Any(r => r.Password == oldPassword && r.Id == _currentUser.Id); string newPassword = LinCmsUtils.Get32Md5(passwordDto.NewPassword); _freeSql.Update <LinUser>(_currentUser.Id).Set(a => new LinUser() { Password = newPassword }).ExecuteAffrows(); }
/// <summary> /// 处理方式:返回Json格式 /// </summary> /// <returns></returns> private async Task JsonHandle(HttpContext context, string errorMsg, ErrorCode errorCode, int statusCode) { ResultDto apiResponse = new ResultDto() { Msg = errorMsg, ErrorCode = errorCode, Request = LinCmsUtils.GetRequest(context) };; context.Response.ContentType = "application/json"; context.Response.StatusCode = statusCode; await context.Response.WriteAsync(apiResponse.ToString(), Encoding.UTF8);; }
/// <summary> /// 本地文件上传,秒传(根据lin_file表中的md5,与当前文件的路径是否在本地),如果不在,重新上传,覆盖文件表记录 /// </summary> /// <param name="file"></param> /// <param name="key"></param> /// <returns></returns> public async Task <FileDto> UploadAsync(IFormFile file, int key = 0) { string md5 = LinCmsUtils.GetHash <MD5>(file.OpenReadStream()); LinFile linFile = await _fileRepository.Where(r => r.Md5 == md5 && r.Type == 1).OrderByDescending(r => r.CreateTime).FirstAsync(); if (linFile != null && File.Exists(Path.Combine(_hostingEnv.WebRootPath, linFile.Path))) { return(new FileDto { Id = linFile.Id, Key = "file_" + key, Path = linFile.Path, Url = _fileStorageOption.LocalFile.Host + linFile.Path }); } long id; var(path, len) = await this.LocalUploadAsync(file); if (linFile == null) { LinFile saveLinFile = new LinFile() { Extension = Path.GetExtension(file.FileName), Md5 = md5, Name = file.FileName, Path = path, Type = 1, Size = len }; id = (await _fileRepository.InsertAsync(saveLinFile)).Id; } else { linFile.Path = path; await _fileRepository.UpdateAsync(linFile); id = linFile.Id; } return(new FileDto { Id = id, Key = "file_" + key, Path = path, Url = _fileStorageOption.LocalFile.Host + path }); }
public void ResetPassword(int id, ResetPasswordDto resetPasswordDto) { bool userExist = _userRepository.Where(r => r.Id == id).Any(); if (userExist == false) { throw new LinCmsException("用户不存在", ErrorCode.NotFound); } string confirmPassword = LinCmsUtils.Get32Md5(resetPasswordDto.ConfirmPassword); _freeSql.Update <LinUser>(id).Set(a => new LinUser() { Password = confirmPassword }).ExecuteAffrows(); }
/// <summary> /// 上传文件至七牛云 /// </summary> /// <param name="file">单个文件</param> /// <param name="key"></param> /// <returns></returns> public FileDto Upload(IFormFile file, int key = 0) { string md5 = LinCmsUtils.GetHash <MD5>(file.OpenReadStream()); LinFile linFile = _freeSql.Select <LinFile>().Where(r => r.Md5 == md5 && r.Type == 2).First(); if (linFile != null) { return(new FileDto { Id = linFile.Id, Key = "file_" + key, Path = linFile.Path, Url = _configuration[LinConsts.Qiniu.Host] + linFile.Path }); } string fileName = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName.Trim().ToString(); string extension = Path.GetExtension(fileName); string path = this.UploadToQiniu(file); long size = 0; LinFile saveLinFile = new LinFile() { Extension = extension, Md5 = md5, Name = fileName, Path = path, Type = 2, CreateTime = DateTime.Now, Size = size }; long id = _freeSql.Insert(saveLinFile).ExecuteIdentity(); return(new FileDto { Id = (int)id, Key = "file_" + key, Path = path, Url = _configuration[LinConsts.Qiniu.Host] + path }); }
/// <summary> /// 验证密码是否正确,生成Claims,返回用户身份信息 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { LinUser user = _useRepository.Where(r => r.Username == context.UserName || r.Email == context.UserName).ToOne(); //验证失败 if (user == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "用户不存在"); return(Task.CompletedTask); } if (user.Password != LinCmsUtils.Get32Md5(context.Password)) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "请输入正确密码!"); return(Task.CompletedTask); } _useRepository.UpdateDiy.Set(r => new LinUser() { LastLoginTime = DateTime.Now }).Where(r => r.Id == user.Id).ExecuteAffrows(); //subjectId 为用户唯一标识 一般为用户id //authenticationMethod 描述自定义授权类型的认证方法 //authTime 授权时间 //claims 需要返回的用户身份信息单元 context.Result = new GrantValidationResult( user.Id.ToString(), OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime, new List <Claim>() { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Email, user.Email ?? ""), new Claim(ClaimTypes.GivenName, user.Nickname ?? ""), new Claim(ClaimTypes.Name, user.Username ?? ""), new Claim(LinCmsClaimTypes.GroupId, user.GroupId.ToString()), new Claim(LinCmsClaimTypes.IsAdmin, user.IsAdmin().ToString()), new Claim(ClaimTypes.Role, user.IsAdmin()?LinGroup.Admin:user.GroupId.ToString()) }); return(Task.CompletedTask); }
/// <summary> /// 上传文件至七牛云,如果本地存在这条记录,直接返回文件的信息 /// </summary> /// <param name="file">单个文件</param> /// <param name="key"></param> /// <returns></returns> public async Task <FileDto> UploadAsync(IFormFile file, int key = 0) { string md5 = LinCmsUtils.GetHash <MD5>(file.OpenReadStream()); LinFile linFile = await _fileRepository.Where(r => r.Md5 == md5 && r.Type == 2).FirstAsync(); if (linFile != null) { return(new FileDto { Id = linFile.Id, Key = "file_" + key, Path = linFile.Path, Url = _fileStorageOption.Qiniu.Host + linFile.Path }); } string path = this.QiniuUpload(file); LinFile saveLinFile = new LinFile() { Extension = Path.GetExtension(file.FileName), Md5 = md5, Name = file.FileName, Path = path, Type = 2, Size = file.Length, }; long id = (await _fileRepository.InsertAsync(saveLinFile)).Id; return(new FileDto { Id = id, Key = "file_" + key, Path = path, Url = _fileStorageOption.Qiniu.Host + path }); }
/// <summary> /// 验证密码是否正确,生成Claims,返回用户身份信息 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { LinUser user = _fsql.Select <LinUser>().Where(r => r.Nickname == context.UserName).ToOne(); //验证失败 if (user == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "用户不存在"); return(Task.CompletedTask); } if (user.Password != LinCmsUtils.Get32Md5(context.Password)) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "请输入正确密码!"); return(Task.CompletedTask); } //subjectId 为用户唯一标识 一般为用户id //authenticationMethod 描述自定义授权类型的认证方法 //authTime 授权时间 //claims 需要返回的用户身份信息单元 context.Result = new GrantValidationResult( user.Id.ToString(), OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime, new List <Claim>() { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.SerialNumber, user.Nickname), new Claim(ClaimTypes.Name, user.Username), new Claim(LinCmsClaimTypes.GroupId, user.GroupId.ToString()), new Claim(LinCmsClaimTypes.IsAdmin, user.IsAdmin().ToString()), new Claim(ClaimTypes.Role, user.IsAdmin()?LinGroup.Administrator:user.GroupId.ToString()) }); return(Task.CompletedTask); }
public List <FileDto> Upload(IFormFile file, int key = 0) { string domainUrl = _configuration["SITE_DOMAIN"]; string fileDir = _configuration["FILE:STORE_DIR"]; string md5 = LinCmsUtils.GetHash <MD5>(file.OpenReadStream()); LinFile linFile = _freeSql.Select <LinFile>().Where(r => r.Md5 == md5).First(); if (linFile != null) { return(new List <FileDto> { new FileDto { Id = linFile.Id, Key = "file_" + key, Path = linFile.Path, Url = domainUrl + "/" + _configuration["FILE:STORE_DIR"] + "/" + linFile.Path } }); } string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim().ToString(); DateTime now = DateTime.Now; string newSaveName = Guid.NewGuid() + Path.GetExtension(filename); string savePath = Path.Combine(_hostingEnv.WebRootPath, fileDir, now.ToString("yyy/MM/dd")); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } int len; using (FileStream fs = System.IO.File.Create(Path.Combine(savePath, newSaveName))) { file.CopyTo(fs); len = (int)fs.Length; fs.Flush(); } LinFile saveLinFile = new LinFile() { Extension = Path.GetExtension(filename), Md5 = md5, Name = filename, Path = Path.Combine(now.ToString("yyy/MM/dd"), newSaveName).Replace("\\", "/"), Type = 1, CreateTime = DateTime.Now, Size = len }; long id = _freeSql.Insert(saveLinFile).ExecuteIdentity(); return(new List <FileDto> { new FileDto { Id = (int)id, Key = "file_" + key, Path = saveLinFile.Path, Url = domainUrl + "/" + fileDir + "/" + saveLinFile.Path } }); }
public override void OnActionExecuted(ActionExecutedContext context) { Stopwatch.Stop(); //当方法或控制器上存在DisableAuditingAttribute特性标签时,不记录日志 if (context.ActionDescriptor is ControllerActionDescriptor d && d.MethodInfo.IsDefined(typeof(DisableAuditingAttribute), true) || context.Controller.GetType().IsDefined(typeof(DisableAuditingAttribute), true) ) { base.OnActionExecuted(context); return; } LinLog linLog = new LinLog() { Method = context.HttpContext.Request.Method, Path = context.HttpContext.Request.Path, StatusCode = context.HttpContext.Response.StatusCode, OtherMessage = $"参数:{ActionArguments}\n耗时:{Stopwatch.Elapsed.TotalMilliseconds} 毫秒" }; ControllerActionDescriptor auditActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; AuditingLogAttribute auditingLogAttribute = auditActionDescriptor.GetCustomAttribute <AuditingLogAttribute>(); if (auditingLogAttribute != null) { linLog.Message = auditingLogAttribute.Template; } LinCmsAuthorizeAttribute linCmsAttribute = auditActionDescriptor.GetCustomAttribute <LinCmsAuthorizeAttribute>(); if (linCmsAttribute != null) { linLog.Authority = linCmsAttribute.Permission; } base.OnActionExecuted(context); if (context.Result is ObjectResult objectResult && objectResult.Value != null) { if (objectResult.Value.ToString().Contains("ErrorCode")) { ResultDto resultDto = JsonConvert.DeserializeObject <ResultDto>(objectResult.Value.ToString()); resultDto.Request = LinCmsUtils.GetRequest(context.HttpContext); context.Result = new JsonResult(resultDto); if (linLog.Message.IsNullOrEmpty()) { linLog.Message = resultDto.Msg?.ToString(); } } } linLog.Message += $"{_currentUser.UserName}访问{context.HttpContext.Request.Path},耗时:{Stopwatch.Elapsed.TotalMilliseconds} 毫秒"; _logService.InsertLog(linLog); //记录文本日志 _logger.LogInformation(JsonConvert.SerializeObject(linLog)); //MiniProfiler.Current.CustomTiming($"OnActionExecuted ->", str); }
public void Get32Md5One() { string result = LinCmsUtils.Get32Md5("123qwe"); _testOutputHelper.WriteLine(result); }
public LinUser Authorization(string username, string password) { LinUser user = _userRepository.Select.Where(r => r.Nickname == username && r.Password == LinCmsUtils.Get32Md5(password)).First(); return(user); }
public ResultDto(ErrorCode errorCode, object msg, HttpContext httpContext) { ErrorCode = errorCode; Msg = msg; Request = LinCmsUtils.GetRequest(httpContext); }
public void test() { var d = LinCmsUtils.IpQueryCity("117.83.181.123"); }
public FileDto Upload(IFormFile file, int key = 0) { string domainUrl = _configuration[LinConsts.SITE_DOMAIN]; string fileDir = _configuration[LinConsts.File.STORE_DIR]; string md5 = LinCmsUtils.GetHash <MD5>(file.OpenReadStream()); LinFile linFile = _freeSql.Select <LinFile>().Where(r => r.Md5 == md5 && r.Type == 1).OrderByDescending(r => r.CreateTime).First(); if (linFile != null && File.Exists(Path.Combine(_hostingEnv.WebRootPath, fileDir, linFile.Path))) { return(new FileDto { Id = linFile.Id, Key = "file_" + key, Path = linFile.Path, Url = domainUrl + fileDir + "/" + linFile.Path }); } string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim().ToString(); string extension = Path.GetExtension(fileName); string now = DateTime.Now.ToString("yyy/MM/dd"); string newSaveName = Guid.NewGuid() + extension; string savePath = Path.Combine(_hostingEnv.WebRootPath, fileDir, now); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } long len; using (FileStream fs = File.Create(Path.Combine(savePath, newSaveName))) { file.CopyTo(fs); len = fs.Length; fs.Flush(); } long id; string path = Path.Combine(now, newSaveName).Replace("\\", "/"); if (linFile == null) { LinFile saveLinFile = new LinFile() { Extension = Path.GetExtension(fileName), Md5 = md5, Name = fileName, Path = path, Type = 1, CreateTime = DateTime.Now, Size = len }; id = _freeSql.Insert(saveLinFile).ExecuteIdentity(); } else { _freeSql.Update <LinFile>(linFile.Id).Set(a => a.Path, path).ExecuteAffrows(); id = linFile.Id; } return(new FileDto { Id = (int)id, Key = "file_" + key, Path = path, Url = domainUrl + "/" + fileDir + "/" + path }); }
public UnifyResponseDto(ErrorCode errorCode, object message, HttpContext httpContext) { Code = errorCode; Message = message; Request = LinCmsUtils.GetRequest(httpContext); }