/// <summary> /// 验证Token令牌是否合法 /// </summary> /// <param name="token">令牌</param> /// <param name="appid">应用ID</param> /// <returns>CheckResult</returns> protected virtual ApiResult <string> CheckIdentityToken(string token, Guid appid) { #region 请求参数检查 var checkResult = CheckRequest(token, appid); if (!checkResult.State) { return(ApiResult <string> .Fail(checkResult.Message)); } #endregion #region 请求通道检查 var getAppConfig = AppCfgService.Get(appid); if (!getAppConfig.State) { return(ApiResult <string> .Fail(getAppConfig.Message)); } var appConfig = getAppConfig.Data; #endregion return(ApiAuthenticate.CheckIdentityToken(token, appConfig)); }
/// <summary> /// 创建合法用户的Token /// </summary> /// <param name="userId">用户Id</param> /// <param name="passWord">用户密码</param> /// <param name="signature">加密签名字符串</param> /// <param name="timestamp">时间戳</param> /// <param name="nonce">随机数</param> /// <param name="appid">应用接入ID</param> /// <returns>OperatedResult</returns> protected virtual ApiResult <IdentityToken> CreateIdentityToken(string userId, string passWord, string signature, string timestamp, string nonce, Guid appid) { #region 参数检查 var checkResult = CheckRequest(userId, passWord, signature, timestamp, nonce, appid); if (!checkResult.State) { return(ApiResult <IdentityToken> .Fail(checkResult.Message)); } #endregion #region 用户鉴权 var getIdentityUser = GetIdentityUser(userId, passWord); if (!getIdentityUser.State) { return(ApiResult <IdentityToken> .Fail(getIdentityUser.Message)); } #endregion #region 请求通道检查 var getAppConfig = AppCfgService.Get(appid); if (!getAppConfig.State) { return(ApiResult <IdentityToken> .Fail(getAppConfig.Message)); } var appConfig = getAppConfig.Data; #endregion #region 检查请求签名检查 var checkSignatureResult = ApiAuthorize.CheckRequestSignature(signature, timestamp, nonce, appConfig); if (!checkSignatureResult.State) { return(ApiResult <IdentityToken> .Fail(checkSignatureResult.Message)); } #endregion #region 生成基于Jwt Token var getTokenResult = ApiAuthorize.CreateIdentityToken(getIdentityUser.Data, getAppConfig.Data); if (!getTokenResult.State) { return(ApiResult <IdentityToken> .Fail(getTokenResult.Message)); } return(ApiResult <IdentityToken> .Success(getTokenResult.Data)); #endregion }
public async Task <ApiResult <bool> > WebFileExistsAsync(ApiSession apiSession, string serverFilePath, CancellationToken cancellationToken) { if (apiSession == null) { throw new ArgumentNullException(nameof(apiSession)); } var spaceName = apiSession.SpaceName; var url = UrlHelper.JoinUrl("space", spaceName, "files", serverFilePath); var apiResult = await apiClient.HeadAsync <NoContentResult>(url, null, apiSession.ToHeadersCollection(), cancellationToken); // http ok or http no content means that file exists if (apiResult.IsSucceed) { return(ApiResult <bool> .Ok(true)); } else { // if not found, return Ok with false result if (apiResult.Error is MorphApiNotFoundException) { return(ApiResult <bool> .Ok(false)); } else { // some error occured - return internal error from api result return(ApiResult <bool> .Fail(apiResult.Error)); } } }
/// <summary> /// 检查Token是否合法 /// </summary> /// <param name="token">用户令牌</param> /// <param name="appConfig">AppConfig</param> /// <returns></returns> public ApiResult <string> CheckIdentityToken(string token, AppConfig appConfig) { ValidateOperator.Begin() .NotNullOrEmpty(token, "Token") .NotNull(appConfig, "AppConfig"); try { var tokenText = ParseTokens(token, appConfig.SharedKey); if (string.IsNullOrEmpty(tokenText)) { return(ApiResult <string> .Fail("用户令牌Token为空")); } dynamic root = JObject.Parse(tokenText); string userid = root.iss; double iat = root.iat; var validTokenExpired = new TimeSpan((int)(UnixEpochHelper.GetCurrentUnixTimestamp().TotalSeconds - iat)) .TotalDays > appConfig.TokenExpiredDay; return(validTokenExpired ? ApiResult <string> .Fail($"用户ID{userid}令牌失效") : ApiResult <string> .Success(userid)); } catch (FormatException) { return(ApiResult <string> .Fail("用户令牌非法")); } catch (SignatureVerificationException) { return(ApiResult <string> .Fail("用户令牌非法")); } }
public ApiResult DelService([FromUri] long id, [FromUri] long rid) { var r = db.R_Service_Package.SingleOrDefault(a => a.Id == id); if (r == null) { return(ApiResult.Fail("找不到")); } return(ApiResult.Ok()); }
protected virtual IActionResult Fail(string message = "", int code = -1) { var result = new ApiResult { Message = message, Code = code }; result.Fail(); return(Ok(result)); }
public async Task <IActionResult> Listar() { try { var lista = _clientesService.Listar(); return(Ok(ApiResult.Ok(lista))); } catch (Exception e) { _logger.LogError(e.Message); return(UnprocessableEntity(ApiResult.Fail("Não foi possível listar os usuários, favor comunicar administrador do sistema."))); } }
public ApiResult Delete([FromUri] long id) { var ef = SMSDbContext.Create(); var item = ef.Services.SingleOrDefault(a => a.Id == id); if (item == null) { return(ApiResult.Fail("找不到要删除的服务")); } ef.Services.Remove(item); ef.SaveChangesAsync(); return(ApiResult.Ok()); }
private async Task HandleExceptionAsync(HttpContext context, Exception exception) { var response = context.Response; response.ContentType = "application/json"; response.StatusCode = (int)HttpStatusCode.InternalServerError; var result = JsonConvert.SerializeObject( ApiResult.Fail(exception), new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); await response.WriteAsync(result); }
public async Task <IActionResult> Cadastrar([FromBody] ClientesViewModel cliente) { try { var id = _clientesService.Cadastrar(cliente); return(Ok(ApiResult.Ok(id))); } catch (Exception e) { _logger.LogError(e.Message); return(UnprocessableEntity(ApiResult.Fail("Não foi possível cadastrar, favor comunicar administrador do sistema."))); } }
/// <summary> /// 获得数据列表 /// </summary> /// <param name="where"></param> /// <returns></returns> public ApiResult <List <Request> > GetList(Request model) { try { using (requestDal) { return(requestDal.GetList("")); } } catch (Exception ex) { return(ApiResult <List <Request> > .Fail(ex.Message)); } }
/// <summary> /// 删除一条数据 /// </summary> /// <param name="model"></param> /// <returns></returns> public ApiResult <bool> Delete(Request model) { try { using (requestDal) { return(requestDal.Delete(model)); } } catch (Exception ex) { return(ApiResult <bool> .Fail(ex.Message)); } }
/// <summary> /// 增加多条数据 /// </summary> /// <param name="list"></param> /// <returns></returns> public ApiResult <bool> AddList(List <Request> list) { try { using (requestDal) { return(requestDal.AddList(list)); } } catch (Exception ex) { return(ApiResult <bool> .Fail(ex.Message)); } }
/// <summary> /// 得到一个对象实体 /// </summary> /// <param name="id"></param> /// <returns></returns> public ApiResult <Request> GetOne(Request model) { try { using (requestDal) { return(requestDal.GetOne(model)); } } catch (Exception ex) { return(ApiResult <Request> .Fail(ex.Message)); } }
public ApiResult Change([FromUri] long id, [FromBody] ServicePackageModel model) { var item = db.ServicePackages.SingleOrDefault(a => a.Id == id); if (item == null) { return(ApiResult.Fail("找不到要删除的服务")); } item.Name = model.Name; item.Price = model.Price; item.Remark = model.Remark; item.UpdateTime = DateTime.Now; item.SecurityStamp = Guid.NewGuid().ToString(); db.SaveChangesAsync(); return(ApiResult.Ok()); }
public async Task <ApiResult <TResponse> > Handle(TRequest request, RequestHandlerDelegate <TResponse> next) { if (_validators.Any()) { foreach (var validator in _validators.OrderBy(v => v.Order)) { var result = await validator.InternalValidate(request); if (result.IsFailure) { return(ApiResult <TResponse> .Fail(result.HttpStatusCode, result.ErrorDescription, result.ErrorCode)); } } } return(await next()); }
public ApiResult Delete([FromUri] long id) { var item = db.ServicePackages.SingleOrDefault(a => a.Id == id); if (item == null) { return(ApiResult.Fail("找不到要删除的服务")); } if (item.Services.Any()) { foreach (var s in item.Services) { db.R_Service_Package.Remove(s); } } db.ServicePackages.Remove(item); db.SaveChangesAsync(); return(ApiResult.Ok()); }
public ApiResult Change([FromUri] long id, [FromBody] ServiceCreateModel model) { var ef = SMSDbContext.Create(); var item = ef.Services.SingleOrDefault(a => a.Id == id); if (item == null) { return(ApiResult.Fail("找不到要删除的服务")); } item.Name = model.Name; item.Price = model.Price; item.Remark = model.Remark; item.Type = model.Type; item.Config = model.Config; item.UpdateTime = DateTime.Now; item.SecurityStamp = Guid.NewGuid().ToString(); ef.SaveChangesAsync(); return(ApiResult.Ok()); }
public async Task <ApiResult <string> > UserLogin([FromForm] string userCode, [FromForm] string password) { if (userCode != "admin") { return(ApiResult.Fail <string>("该用户不存在!")); } if (password != "1") { return(ApiResult.Fail <string>("密码错误!")); } await Task.Delay(1); var claims = new Claim[] { new Claim("Id", "admin"), new Claim("UserCode", "admin"), new Claim("UserName", "管理员"), new Claim("UserRoles", ""), new Claim("UserType", "超级管理员"), new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddMinutes(_tokenConfig.AccessExpiration)).ToUnixTimeSeconds().ToString()), }; var key = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(_tokenConfig.Secret)); var token = new JwtSecurityToken( issuer: _tokenConfig.Issuer, audience: _tokenConfig.Audience, claims: claims, notBefore: DateTime.Now, expires: DateTime.Now.AddMinutes(_tokenConfig.AccessExpiration), signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); //生成Token string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); _logger.LogInformation($"【登录用户-->Id:admin,Code:admin,Name:管理员】"); return(ApiResult.Success(jwtToken)); }
public ApiResult <bool> Add(User model) { using (Trans t = new Trans()) { var user = userDal.GetAll("where user_name=@user_name", model, t); if (user.Any()) { return(ApiResult <bool> .Fail("用户名已存在!")); } var add = userDal.Add(model, t); if (!add.Result) { return(add); } t.Commit(); add.Message = "注册成功"; return(add); } }
public ApiResult AddService([FromUri] long id, [FromBody] ServicePackageModel.ServicesModel model) { var package = db.ServicePackages.SingleOrDefault(m => m.Id == id); if (package == null) { return(ApiResult.Fail("找不到要修改套餐")); } if (package.Services.Any(a => a.ServiceId == model.ServiceId)) { return(ApiResult.Fail("服务已经存在请先删除")); } package.Services.Add(new R_ServiceDescription_ServicePackage { PackageId = id, Price = model.Price, SequenceNumber = model.SequenceNumber, ServiceId = model.ServiceId }); db.SaveChanges(); return(ApiResult.Ok()); }
public void OnAuthorization(AuthorizationFilterContext context) { var httpContext = context.HttpContext; if (string.IsNullOrWhiteSpace(_webAppQpHelper.CustomerCode)) { throw new Exception("Customer code should not be empty"); } SiteConfiguration.Set(httpContext, _webAppQpHelper.CustomerCode, _webAppQpHelper.SiteId, _configuration.UseFake); var isAuthorize = _securityChecker.CheckAuthorization(); var ci = new CultureInfo(httpContext.Session.GetString(QPSecurityChecker.UserLanguageKey) ?? QpLanguage.Default.GetDescription()); Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; if (!isAuthorize) { context.Result = new UnauthorizedObjectResult(ApiResult.Fail(new Exception("Unauthorized"))); } }