public JObject InstallModule() { try { var request = _httpContextProxy.GetRequestBody <ModuleInstallRequest>(); if (request == null) { return(_responseBuilder.BadRequest()); } if (request.InstallationKey != _moduleInstallationKey) { _logger.Error("Installation key validation fail"); return(_responseBuilder.Unauthorized()); } if (request.Name != "ZNxt.Net.Core.Module.Gateway") { GetAppGatewayConfig().GetAwaiter().GetResult(); } JObject moduleObject = new JObject(); moduleObject[CommonConst.CommonField.NAME] = request.Name; moduleObject[CommonConst.CommonField.VERSION] = request.Version; moduleObject[CommonConst.MODULE_INSTALL_COLLECTIONS_FOLDER] = "collections";// config[CommonConst.MODULE_INSTALL_COLLECTIONS_FOLDER]; InstallWWWRoot(request); InstallCollections(request); InstallDlls(request); _routing.ReLoadRoutes(); return(_responseBuilder.Success()); } catch (Exception ex) { _logger.Error(ex.Message, ex); return(_responseBuilder.ServerError()); } }
public JObject InstallPage() { try { var request = _httpContextProxy.GetRequestBody <JObject>(); if (request == null) { return(_responseBuilder.BadRequest()); } var id = request[CommonConst.CommonField.DISPLAY_ID].ToString(); var moduleName = request[CommonConst.CommonField.MODULE_NAME].ToString(); var path = request[CommonConst.CommonField.FILE_PATH].ToString(); var data = request[CommonConst.CommonField.DATA].ToString(); string cleanupWWWRootFilter = "{ " + CommonConst.CommonField.MODULE_NAME + ":'" + moduleName + "', " + CommonConst.CommonField.FILE_PATH + ": '" + path + "'}"; foreach (var item in _dbService.Get(CommonConst.Collection.STATIC_CONTECT, new RawQuery(cleanupWWWRootFilter))) { _keyValueStorage.Delete(CommonConst.Collection.STATIC_CONTECT, item[CommonConst.CommonField.DISPLAY_ID].ToString()); } _keyValueStorage.Put <string>(CommonConst.Collection.STATIC_CONTECT, id, data); request.Remove(CommonConst.CommonField.DATA); WriteToDB(request, moduleName, CommonConst.Collection.STATIC_CONTECT, CommonConst.CommonField.FILE_PATH); return(_responseBuilder.Success()); } catch (Exception ex) { _logger.Error(ex.Message, ex); return(_responseBuilder.ServerError()); } }
public JObject Send() { var model = _httpContextProxy.GetRequestBody <NotifyModel>(); if (model == null) { return(_responseBuilder.BadRequest()); } var to = model.To.Split(';').ToList(); var message = model.Message; if (model.Type == "SMS") { JObject dataresponse = new JObject(); foreach (var res in _smsService.Send(to, message)) { dataresponse[res.Key] = res.Value; } return(_responseBuilder.Success(dataresponse)); } else { if (_emailService.Send(to, _appSettingService.GetAppSettingData(CommonConst.CommonField.FROM_EMAIL_ID), model.CC.Split(';').ToList(), message, model.Subject)) { return(_responseBuilder.Success()); } else { return(_responseBuilder.ServerError()); } } }
public JObject InstallRoute() { var routeObj = _httpContextProxy.GetRequestBody <JObject>(); var endpoint = routeObj[CommonConst.CommonField.MODULE_ENDPOINT]; var moduleName = routeObj[CommonConst.CommonField.MODULE_NAME]; if (endpoint == null || moduleName == null) { _responseBuilder.BadRequest("module_name or module_endpoint missing"); } routeObj.Remove(CommonConst.CommonField.MODULE_ENDPOINT); WriteToDB(routeObj, moduleName.ToString(), GATEWAY_ROUTE_COLLECTION, CommonConst.CommonField.KEY); var moduleEndPountData = new JObject() { [CommonConst.CommonField.DISPLAY_ID] = CommonUtility.GetNewID(), [CommonConst.CommonField.MODULE_ENDPOINT] = endpoint, [CommonConst.CommonField.MODULE_NAME] = moduleName, [CommonConst.CommonField.ÌS_OVERRIDE] = false }; WriteToDB(moduleEndPountData, moduleName.ToString(), GATEWAY_MODULE_ENDPOINT, CommonConst.CommonField.MODULE_NAME); return(_responseBuilder.Success()); }
public JObject Generate() { var data = _httpContextProxy.GetRequestBody <GenerateAuthTokenRequest>(); var userAccontHelper = _serviceResolver.Resolve <UserAccontHelper>(); if (userAccontHelper.ValidateUser(data.UserName, data.Password)) { var user = userAccontHelper.GetUser(data.UserName); if (GetAuthTokenCount(_dbService, user) < MAX_KEYS) { var apikey = GenerateApiKey(); var apikeydata = GenerateApiKeyData(user, apikey); if (_dbService.WriteData(CommonConst.Collection.AUTH_TOKEN_COLLECTION, apikeydata)) { apikeydata[CommonConst.CommonField.AUTH_TOKEN] = apikey; return(_responseBuilder.Success(apikeydata)); } else { _logger.Error("Error in writing data"); return(_responseBuilder.ServerError()); } } else { return(_responseBuilder.CreateReponse(ApiKeyResponseCode._MAX_AUTH_TOKEN_REACHED)); } } else { return(_responseBuilder.Unauthorized()); } }
public JObject AcceptMobileAuthTnC() { try { var request = _httpContextProxy.GetRequestBody <MobileAuthAcceptTnCRequestModel>(); request.device_address = _httpContextProxy.GetHeader("device_address"); var results = new Dictionary <string, string>(); if (request.IsValidModel(out results)) { JObject tncResponse = new JObject() { ["security_code"] = "dummy_security_code" }; return(_responseBuilder.Success(null, tncResponse)); } else { _logger.Debug("Model validation fail"); JObject errors = new JObject(); foreach (var error in results) { errors[error.Key] = error.Value; } return(_responseBuilder.BadRequest(errors)); } } catch (Exception ex) { _logger.Error(ex.Message, ex); return(_responseBuilder.ServerError()); } }
private void StartInstall(IHttpContextProxy httpProxy) { try { UpdateInstallStatus(AppInstallStatus.Start); var requestData = httpProxy.GetRequestBody <AppInstallerConfig>(); if (requestData == null) { httpProxy.SetResponse(CommonConst._400_BAD_REQUEST); httpProxy.ContentType = CommonConst.CONTENT_TYPE_APPLICATION_JSON; return; } UpdateInstallStatus(AppInstallStatus.Inprogress); WriteCustomConfig(requestData); RunInstallScripts(); InstallModule(requestData, httpProxy); UpdateInstallStatus(AppInstallStatus.Finish); _routings.LoadRoutes(); httpProxy.SetResponse(CommonConst._200_OK, GetStatus()); httpProxy.ContentType = CommonConst.CONTENT_TYPE_APPLICATION_JSON; } catch (Exception ex) { httpProxy.SetResponse(CommonConst._500_SERVER_ERROR, ex.Message); httpProxy.ContentType = CommonConst.CONTENT_TYPE_APPLICATION_JSON; _logger.Error(string.Format("Error in App install {0}", ex.Message), ex); } }
public JObject AuthAppTokenValidate() { try { _logger.Debug("calling AuthAppTokenValidate"); var token = _httpContextProxy.GetRequestBody <JObject>(); var data = _appAuthTokenHandler.GetTokenModel("znxt", token["token"]?.ToString()); if (data != null) { var user = _appAuthTokenHandler.GetUser(data); if (user != null) { return(_responseBuilder.Success(user.ToJObject())); } else { _logger.Error("AuthAppTokenValidate GetUser fail", null, data.ToJObject()); return(_responseBuilder.Unauthorized()); } } else { _logger.Error("AuthAppTokenValidate Token validation fail", null, token); return(_responseBuilder.Unauthorized()); } } catch (Exception ex) { _logger.Error(ex.Message, ex); return(_responseBuilder.ServerError()); } }
public JObject SetDb() { var data = _httpContextProxy.GetRequestBody <DBConnection>(); _dbConfig.Set(data.Database, data.ConnectionString); ApplicationConfig.AppInstallStatus = AppInstallStatus.Init; var db = _serviceResolver.Resolve <IDBService>(); if (db.IsConnected) { _dbConfig.Save(); return(_responseBuilder.Success()); } else { ApplicationConfig.AppInstallStatus = AppInstallStatus.DBNotSet; return(_responseBuilder.ServerError(new JObject { [CommonConst.CommonField.ERR_MESSAGE] = "DB Connection error" })); } }
private void BuildRequestBody(JObject requestBody, HttpRequestMessage request) { if (requestBody != null) { var stringContent = new StringContent(requestBody.ToString(), Encoding.UTF8, "application/json"); request.Content = stringContent; } else { var requestBodyString = _httpContextProxy.GetRequestBody(); if (!string.IsNullOrEmpty(requestBodyString)) { var stringContent = new StringContent(requestBodyString, Encoding.UTF8, "application/json"); request.Content = stringContent; } } }
public JObject Process() { try { var request = _httpContextProxy.GetRequestBody <JObject>(); if (request != null && request["key"] != null) { var data = _dbService.Get(_collection, new RawQuery("{'key':'" + request["key"].ToString() + "','override_by':'none'}")); if (data.Count == 1 && data.First()["data"] != null) { var template = data.First()["data"].ToString(); var subject = data.First()["subject"] != null?data.First()["subject"].ToString() : ""; request.Remove("key"); foreach (var item in request) { subject = subject.Replace("{{" + item.Key.ToString() + "}}", item.Value.ToString()); template = template.Replace("{{" + item.Key.ToString() + "}}", item.Value.ToString()); } JObject response = new JObject(); response["data"] = template; response["subject"] = subject; var apiresponse = _responseBuilder.Success(response); _logger.Debug("templete process response", apiresponse); return(apiresponse); } else { _logger.Error($"key not found {request["key"]}"); return(_responseBuilder.NotFound());; } } else { _logger.Error("Bad request"); return(_responseBuilder.BadRequest());; } } catch (Exception ex) { _logger.Error(ex.Message, ex); return(_responseBuilder.ServerError()); } }
public void Error(string message, Exception ex) { if (LogLevels.Contains("Error")) { JObject logData = null; if (_httpContextProxy != null) { logData = new JObject() { ["RequestBody"] = _httpContextProxy.GetRequestBody(), ["RequestUrl"] = _httpContextProxy.GetURIAbsolutePath(), ["RequestQueryString"] = _httpContextProxy.GetQueryString() }; logData["RequestHeader"] = string.Join(";", _httpContextProxy.GetHeaders().Select(f => string.Format("{0}:{1}", f.Key, f.Value))); } Error(message, ex, logData); } }
private void WriteStartTransaction(ILogger loggerController, IHttpContextProxy httpProxy, RoutingModel route) { JObject objTxnStartData = new JObject(); objTxnStartData[CommonConst.CommonField.URL] = httpProxy.GetURIAbsolutePath(); objTxnStartData[CommonConst.CommonField.ROUTE] = JObject.Parse(route.GetJson()); string strPayload = httpProxy.GetRequestBody();; JObject payload = null; if (JObjectHelper.TryParseJson(strPayload, ref payload)) { objTxnStartData[CommonConst.CommonField.PAYLOAD] = payload; } else { objTxnStartData[CommonConst.CommonField.PAYLOAD] = strPayload; } //TODO // objTxnStartData[CommonConst.CommonField.USER] = httpProxy.GetRequestBody(); // loggerController.Transaction(objTxnStartData, TransactionState.Start); }
public async Task <JObject> Login() { try { JObject response = null; var data = _httpContextProxy.GetRequestBody <UserLoginModel>(); if (data == null) { response = _responseBuilder.BadRequest(); } var userAccontHelper = _serviceResolver.Resolve <UserAccontHelper>(); var user = userAccontHelper.GetUser(data.UserName); if (user == null) { response = _responseBuilder.Unauthorized(); } if (userAccontHelper.ValidateUser(user, data.Password)) { ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(user), CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal principal = new ClaimsPrincipal(identity); await _serviceResolver.Resolve <IHttpContextAccessor>().HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); response = _responseBuilder.Success(); } else { response = _responseBuilder.Unauthorized(); } return(await Task.FromResult <JObject>(response)); } catch (Exception ex) { _logger.Error(ex.Message, ex); return(await Task.FromResult <JObject>(_responseBuilder.ServerError())); } }
private static Dictionary <string, dynamic> SetDefaultModel(IDBService dbProxy, IHttpContextProxy httpProxy, ILogger logger, IViewEngine viewEngine, IActionExecuter actionExecuter, Dictionary <string, dynamic> model, string folderPath = null) { ISessionProvider sessionProvider = new SessionProvider(httpProxy, dbProxy, logger); if (model == null) { model = new Dictionary <string, dynamic>(); } model[CommonConst.CommonValue.METHODS] = new Dictionary <string, dynamic>(); Func <string, string, JArray> getData = (string collection, string filter) => { return(dbProxy.Get(collection, filter)); }; Func <string, string> getAppSetting = (string key) => { var response = AppSettingService.Instance.GetAppSettingData(key); if (string.IsNullOrEmpty(response)) { response = ConfigurationManager.AppSettings[key]; } return(response); }; Func <string, JObject> getSessionValue = (string key) => { return(sessionProvider.GetValue <JObject>(key)); }; Func <string, string> includeTemplete = (string templatePath) => { FileInfo fi = new FileInfo(string.Format("c:\\{0}{1}", folderPath, templatePath)); string path = fi.FullName.Replace("c:", ""); model[CommonConst.CommonValue.PAGE_TEMPLATE_PATH] = path; return(string.Empty); }; Func <string, bool> authorized = (string authGroups) => { var sessionUser = sessionProvider.GetValue <UserModel>(CommonConst.CommonValue.SESSION_USER_KEY); if (sessionUser == null) { return(false); } if (!authGroups.Split(',').Where(i => sessionUser.groups.Contains(i)).Any()) { return(false); } else { return(true); } }; Func <string, JObject, JObject> ActionExecute = (string actionPath, JObject data) => { var param = ActionExecuterHelper.CreateParamContainer(null, httpProxy, logger, actionExecuter); if (data != null) { foreach (var item in data) { Func <dynamic> funcValue = () => { return(item.Value); }; param.AddKey(item.Key, funcValue); } } return(actionExecuter.Exec <JObject>(actionPath, dbProxy, param)); }; Func <string, JObject, Dictionary <string, dynamic> > IncludeModel = (string includeModelPath, JObject data) => { try { var param = ActionExecuterHelper.CreateParamContainer(null, httpProxy, logger, actionExecuter); Dictionary <string, dynamic> modelData = new Dictionary <string, dynamic>(); if (data != null) { foreach (var item in data) { Func <dynamic> funcValue = () => { return(item.Value); }; param.AddKey(item.Key, funcValue); } } object response = actionExecuter.Exec(includeModelPath, dbProxy, param); if (response is Dictionary <string, dynamic> ) { return(response as Dictionary <string, dynamic>); } else { throw new InvalidCastException(string.Format("Invalid respone from {0}", includeModelPath)); } } catch (UnauthorizedAccessException ex) { logger.Error(string.Format("Error While executing Route : {0}, Error : {1}", includeModelPath, ex.Message), ex); throw; } }; model[CommonConst.CommonValue.METHODS]["IncludeModel"] = IncludeModel; model[CommonConst.CommonValue.METHODS]["ExecuteAction"] = ActionExecute; model[CommonConst.CommonValue.METHODS]["InclueTemplate"] = includeTemplete; model[CommonConst.CommonValue.METHODS]["GetData"] = getData; Func <JObject> requestBody = () => httpProxy.GetRequestBody <JObject>(); model[CommonConst.CommonValue.METHODS]["RequestBody"] = requestBody; Func <string, string> queryString = (string key) => httpProxy.GetQueryString(key); model[CommonConst.CommonValue.METHODS]["QueryString"] = queryString; model[CommonConst.CommonValue.METHODS]["AppSetting"] = getAppSetting; model[CommonConst.CommonValue.METHODS]["GetSessionData"] = getSessionValue; model[CommonConst.CommonValue.METHODS]["Authorized"] = authorized; Func <string, JObject, string> includeBlock = (string blockPath, JObject blockModel) => { var inputBlockModel = new Dictionary <string, dynamic>(); if (blockModel != null) { foreach (var item in blockModel) { inputBlockModel[item.Key] = item.Value; } } if (model != null) { foreach (var item in model) { inputBlockModel[item.Key] = item.Value; } } FileInfo fi = new FileInfo(string.Format("c:\\{0}{1}", folderPath, blockPath)); string path = fi.FullName.Replace("c:", ""); var data = StaticContentHandler.GetStringContent(dbProxy, logger, path); data = viewEngine.Compile(data, path, ServerPageModelHelper.SetDefaultModel(dbProxy, httpProxy, logger, viewEngine, actionExecuter, inputBlockModel, path.Replace(fi.Name, ""))); return(data); }; model[CommonConst.CommonValue.METHODS]["Include"] = includeBlock; Func <string> randerBody = () => { if (model.ContainsKey(CommonConst.CommonValue.RENDERBODY_DATA)) { return(model[CommonConst.CommonValue.RENDERBODY_DATA]); } else { return(string.Empty); } }; model[CommonConst.CommonValue.METHODS]["RenderBody"] = randerBody; return(model); }
public virtual async Task <JObject> CallRemoteRouteCalls(HttpContext context, RoutingModel route) { var appToken = "route-call"; _logger.Debug(string.Format("Executing remote route:{0}:{1}", route.Method, route.Route)); var headers = new Dictionary <string, string>(); headers[CommonConst.CommonField.API_AUTH_TOKEN] = appToken; var response = await _apiGatewayService.CallAsync(_httpContextProxy.GetHttpMethod(), _httpContextProxy.GetURIAbsolutePath(), _httpContextProxy.GetQueryString(), _httpContextProxy.GetRequestBody <JObject>(), headers); return(response); }
public JObject AdminAddUser() { try { var request = _httpContextProxy.GetRequestBody <AdminAddUserModel>(); _logger.Debug("Validation model"); var results = new Dictionary <string, string>(); if (request.IsValidModel(out results)) { _logger.Debug("Getting user service"); _logger.Debug("Calling GetUserByEmail"); if (_ZNxtUserService.GetUserByUsername(request.user_name) == null) { var userModel = new UserModel() { email = request.email, user_id = long.Parse($"{CommonUtility.GetUnixTimestamp(DateTime.UtcNow)}{CommonUtility.RandomNumber(4)}").ToString(), user_name = request.user_name, first_name = request.first_name, middle_name = request.middle_name, last_name = request.last_name, salt = CommonUtility.GetNewID(), is_enabled = true, user_type = "user_pass", //dob = request.dob, id = CommonUtility.GetNewID(), roles = new List <string> { "init_login_email_otp" } }; _logger.Debug("Calling CreateUser"); var response = _ZNxtUserService.CreateUser(userModel, false); if (response) { JObject userInfo = new JObject(); userInfo["mobile_number"] = request.mobile_number; userInfo["whatsapp_mobile_number"] = request.whatsapp_mobile_number; userInfo["gender"] = request.gender; if (_ZNxtUserService.UpdateUserProfile(userModel.user_id, userInfo)) { _userNotifierService.SendWelcomeEmailWithOTPLoginAsync(userModel).GetAwaiter().GetResult(); var resonseData = new JObject() { [CommonConst.CommonField.USER_ID] = userModel.user_id }; return(_responseBuilder.Success(resonseData)); } else { _logger.Error($"Error while updating user profile {userModel.user_id}", null, userInfo); return(_responseBuilder.ServerError()); } } else { return(_responseBuilder.ServerError()); } } else { JObject errors = new JObject(); errors["error"] = $"User id already registered : {request.user_name}"; return(_responseBuilder.BadRequest(errors)); } } else { _logger.Debug("Model validation fail"); JObject errors = new JObject(); foreach (var error in results) { errors[error.Key] = error.Value; } return(_responseBuilder.BadRequest(errors)); } } catch (Exception ex) { _logger.Error(ex.Message, ex); return(_responseBuilder.ServerError()); } }