Exemple #1
0
        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);
        }
        private async Task GetAppGatewayConfig()
        {
            try
            {
                var data = await _apiGateway.CallAsync(CommonConst.ActionMethods.GET, "/gateway/config", "", null, null, ApplicationConfig.ApiGatewayEndpoint);

                if (data != null && data[CommonConst.CommonField.DATA] != null)
                {
                    appGatewayConfig = data[CommonConst.CommonField.DATA] as JArray;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"Error while GetAppGatewayConfig. {ex.Message}", ex);
            }
        }
Exemple #3
0
        public void PushAssemblyRoute(Assembly assembly)
        {
            if (!string.IsNullOrEmpty(ApplicationConfig.ConnectionString))
            {
                System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
                string version    = fvi.FileVersion;
                string modulename = assembly.GetName().Name;

                _dbService.Delete(CommonConst.Collection.SERVER_ROUTES, new RawQuery(new JObject()
                {
                    [CommonConst.CommonField.MODULE_NAME] = modulename
                }.ToString()));
                if (assembly.GetName().Name != "ZNxt.Net.Core.Module.Gateway" && !string.IsNullOrEmpty(ApplicationConfig.ApiGatewayEndpoint))
                {
                    _apiGatewayService.CallAsync(CommonConst.ActionMethods.POST, "/gateway/installroute", "", new JObject()
                    {
                        [CommonConst.CommonField.NAME] = modulename
                    }, null, ApplicationConfig.ApiGatewayEndpoint).GetAwaiter().GetResult();
                }
                foreach (var route in _assemblyLoader.GetRoulesFromAssembly(assembly))
                {
                    try
                    {
                        var data = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(route));
                        data[CommonConst.CommonField.DISPLAY_ID]  = CommonUtility.GetNewID();
                        data[CommonConst.CommonField.MODULE_NAME] = modulename;
                        data[CommonConst.CommonField.VERSION]     = version;
                        data[CommonConst.CommonField.ÌS_OVERRIDE] = false;
                        data[CommonConst.CommonField.OVERRIDE_BY] = CommonConst.CommonValue.NONE;
                        data[CommonConst.CommonField.KEY]         = $"{route.Method}:{route.Route}";
                        WriteToDB(data, CommonConst.Collection.SERVER_ROUTES);
                        data[CommonConst.CommonField.MODULE_ENDPOINT] = ApplicationConfig.AppEndpoint;
                        if (assembly.GetName().Name != "ZNxt.Net.Core.Module.Gateway" && !string.IsNullOrEmpty(ApplicationConfig.ApiGatewayEndpoint))
                        {
                            _apiGatewayService.CallAsync(CommonConst.ActionMethods.POST, "/gateway/installroute", "", data, null, ApplicationConfig.ApiGatewayEndpoint).GetAwaiter().GetResult();
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"Error InstallRoutes route:{route}", ex);
                    }
                }
                ReLoadRoutes();
            }
        }
        public async Task <bool> SendForgetpasswordEmailWithOTPAsync(UserModel user, string message = null)
        {
            try
            {
                _logger.Debug($"Sending forget password OTP email to {user.email}");
                var template_key    = "forgetpassword_with_email_otp";
                var templateRequest = new JObject()
                {
                    ["key"]             = template_key,
                    ["userdisplayname"] = user.GetDisplayName(),
                    ["userloginemail"]  = user.email,
                    ["userlogin"]       = user.user_name,
                    ["appname"]         = ApplicationConfig.AppName,
                    ["appurl"]          = ApplicationConfig.AppEndpoint,
                    ["message"]         = message
                };

                var resultTemplateBase = await _apiGatewayService.CallAsync(CommonConst.ActionMethods.POST, "/template/process", "", templateRequest, null);

                _logger.Debug("template/process response", resultTemplateBase);
                var resultTemplate = resultTemplateBase["data"] as JObject;
                if (resultTemplate["data"] != null && resultTemplate["subject"] != null && !string.IsNullOrEmpty(resultTemplate["data"].ToString()))
                {
                    var emailModel = new JObject()
                    {
                        ["Subject"]  = resultTemplate["subject"],
                        ["To"]       = user.email,
                        ["Type"]     = "Email",
                        ["Message"]  = resultTemplate["data"],
                        ["OTPType"]  = template_key,
                        ["Duration"] = (60 * 15).ToString(), // TODO : Need to move to config, right now confugure for 15 minutes
                        ["message"]  = message
                    };
                    var result = await _apiGatewayService.CallAsync(CommonConst.ActionMethods.POST, "/notifier/otp/send", "", emailModel, null);

                    return(result["code"].ToString() == "1");
                }
                else
                {
                    _logger.Error($"Error while processing the template. Request :{templateRequest.ToString() }", null, resultTemplateBase);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"Error sending welcome email to {user.email}. Error:{ex.Message}", ex);
                return(false);
            }
        }
Exemple #5
0
 private bool CallGatewayPost(JObject request, string url)
 {
     try
     {
         _logger.Debug($"CallGatewayPost: {url}", request);
         var result = _apiGatewayService.CallAsync(CommonConst.ActionMethods.POST, url, "", request).GetAwaiter().GetResult();
         if (result[CommonConst.CommonField.HTTP_RESPONE_CODE].ToString() == CommonConst.CommonField.SUCCESS_VAL.ToString())
         {
             return(true);
         }
         else
         {
             _logger.Error($"Fail on call : {url}", null, result);
             return(false);
         }
     }
     catch (Exception ex)
     {
         _logger.Error(ex.Message, ex);
         return(false);
     }
 }
        public JObject RegisterActivate()
        {
            try
            {
                var request = _httpContextProxy.GetRequestBody <MobileAuthActivateRequest>();
                request.device_address = _httpContextProxy.GetHeader("device_address");
                request.app_version    = _httpContextProxy.GetHeader("app_version");
                request.x_auth_token   = _httpContextProxy.GetHeader("x_auth_token");

                var results = new Dictionary <string, string>();
                if (request.IsValidModel(out results))
                {
                    var validateRequest = new JObject()
                    {
                        ["To"]            = request.mobile_number,
                        ["OTP"]           = request.OTP,
                        ["OTPType"]       = "mobile_auth_activation",
                        ["SecurityToken"] = request.validation_token
                    };

                    var result = _apiGatewayService.CallAsync(CommonConst.ActionMethods.POST, "/notifier/otp/validate", null, validateRequest).GetAwaiter().GetResult();
                    if (result["code"].ToString() == "1" || MOBILE_AUTH_IGNORE_OTP_VALIDATION)
                    {
                        MobileAuthActivateResponse mobileAuthActivateResponse = _ZNxtUserService.ActivateRegisterMobile(request);

                        if (mobileAuthActivateResponse.code == CommonConst._1_SUCCESS)
                        {
                            JObject userInfo = new JObject();
                            userInfo["mobile_number"]          = "";
                            userInfo["whatsapp_mobile_number"] = "";
                            userInfo["gender"] = "";
                            if (_ZNxtUserService.UpdateUserProfile(mobileAuthActivateResponse.user_id, userInfo))
                            {
                                var obj = mobileAuthActivateResponse.ToJObject();
                                obj.Remove("user_id");
                                return(_responseBuilder.Success(null, obj));
                            }
                            else
                            {
                                return(_responseBuilder.CreateReponseWithError(mobileAuthActivateResponse.code, mobileAuthActivateResponse.errors));
                            }
                        }
                        else
                        {
                            return(_responseBuilder.CreateReponseWithError(mobileAuthActivateResponse.code, mobileAuthActivateResponse.errors));
                        }
                    }
                    else
                    {
                        return(_responseBuilder.Unauthorized());
                    }
                }
                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());
            }
        }
        public JObject GetApis()
        {
            var data = _apiGatewayService.CallAsync(CommonConst.ActionMethods.GET, "/gateway/routes", "", null, null, ApplicationConfig.ApiGatewayEndpoint).GetAwaiter().GetResult();

            return(data);
        }
        public OAuthClient FetchClient(string clientId)
        {
            var route = _apiGatewayService.GetRouteAsync(CommonConst.ActionMethods.GET, oauthClientApiPath).GetAwaiter().GetResult();

            if (route != null)
            {
                var result = _apiGatewayService.CallAsync(CommonConst.ActionMethods.GET, oauthClientApiPath, $"client_id={clientId}").GetAwaiter().GetResult();
                if (result[CommonConst.CommonField.HTTP_RESPONE_CODE].ToString() == CommonConst._1_SUCCESS.ToString())
                {
                    var clientname = result["data"]["client_id"].ToString();
                    if (result["data"]["name"] != null)
                    {
                        clientname = result["data"]["name"].ToString();
                    }
                    var tenantId = string.Empty;
                    if (result["data"]["tenant_id"] != null)
                    {
                        tenantId = result["data"]["tenant_id"].ToString();
                    }
                    var roles = new List <string>();

                    if (result["data"]["roles"] != null)
                    {
                        roles.AddRange((result["data"]["roles"] as JArray).Select(f => f.ToString()));
                    }

                    var salt = string.Empty;
                    if (result["data"]["salt"] != null)
                    {
                        salt = result["data"]["salt"].ToString();
                    }

                    var encKey = string.Empty;
                    if (result["data"]["encryption_key"] != null)
                    {
                        encKey = result["data"]["encryption_key"].ToString();
                    }
                    var ips = new List <string>();

                    if (result["data"]["ips"] != null)
                    {
                        foreach (var ip in result["data"]["ips"] as JArray)
                        {
                            ips.Add(ip["ip"].ToString());
                        }
                    }
                    var client = new OAuthClient
                    {
                        Client = new Client()
                        {
                            AllowedGrantTypes  = GrantTypes.ClientCredentials,
                            ClientName         = clientname,
                            ClientId           = result["data"]["client_id"].ToString(),
                            ClientSecrets      = { new Secret(result["data"]["client_secret"].ToString()) },
                            AllowOfflineAccess = true,
                        },
                        Secret        = result["data"]["client_secret"].ToString(),
                        TenantId      = tenantId,
                        Roles         = roles,
                        Salt          = salt,
                        EncryptionKey = encKey,
                        IPs           = ips
                    };
                    var allowedScopes = new List <string>()
                    {
                        "openid", "profile", "ZNxtCoreAppApi"
                    };
                    if (result["data"]["allowed_scopes"] != null)
                    {
                        allowedScopes.AddRange((result["data"]["allowed_scopes"] as JArray).Select(f => f.ToString()).ToList());
                    }

                    client.Client.AllowedScopes = allowedScopes;
                    _inMemoryCacheService.Put <OAuthClient>($"{cachePrefix}{clientId}", client);
                    return(client);
                }
            }
            return(null);
        }
Exemple #9
0
        public async Task <IActionResult> SignIn(string token, string redirecturl = "~/")
        {
            _logger.Debug($"Auth2Controller.SignIn calling {appAuthValidateRoute}");
            var result = _apiGatewayService.CallAsync(CommonConst.ActionMethods.POST, appAuthValidateRoute, null, new JObject()
            {
                ["token"] = token
            }).GetAwaiter().GetResult();
            var appSecret        = CommonUtility.GetApiAuthKey();
            var unauthorizedPage = CommonUtility.GetAppConfigValue(CommonConst.CommonValue.APP_TOKEN_UNAUTHORIZED_PAGE);

            if (string.IsNullOrEmpty(unauthorizedPage))
            {
                unauthorizedPage = "~/unauthorized.html";
            }
            if (result["code"].ToString() == CommonConst._1_SUCCESS.ToString())
            {
                Model.UserModel user = Newtonsoft.Json.JsonConvert.DeserializeObject <Model.UserModel>(result["data"].ToString());
                //var tokenrequest = new Dictionary<string, string>()
                //{
                //    ["grant_type"] = "password",
                //    ["username"] = result["data"]["user_name"].ToString(),
                //    ["password"] = "******",
                //    ["client_id"] = "auth_client",
                //    ["client_secret"] = appSecret,
                //    ["scope"] = "profile"
                //};
                //var conneturl = $"{ApplicationConfig.SSOEndpoint}/connect/token";
                //var client = new RestClient(conneturl);
                //client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                //var request = new RestRequest(Method.POST);
                //request.AddHeader("content-type", "application/x-www-form-urlencoded");
                //request.AddHeader("token", token);
                //request.AddParameter("application/x-www-form-urlencoded", $"{ string.Join("&", tokenrequest.Select(f => $"{f.Key}={f.Value}").ToList())}", ParameterType.RequestBody);
                //IRestResponse response = client.Execute(request);

                //if (response.StatusCode != HttpStatusCode.OK)
                //{
                //    _logger.Error($"Auth2Controller.SignIn connect url fail: {conneturl},:  {response.StatusCode}");
                //    return Redirect(unauthorizedPage);
                //}

                //var tokenResponse = JObject.Parse(response.Content);
                //var isuser = new IdentityServerUser("auth2")
                //{
                //    DisplayName = "auth2",
                //    AdditionalClaims = new List<Claim>() {
                //    new Claim("access_token", tokenResponse["access_token"].ToString()),
                //}

                AuthenticationProperties props = null;

                props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromHours(1))
                };
                var isuser = new IdentityServerUser(user.user_id)
                {
                    DisplayName      = $"{ user.first_name} {user.last_name}",
                    AdditionalClaims = new List <Claim>()
                    {
                        new Claim(JwtClaimTypes.Subject, user.user_id),
                        new Claim("api_key", appSecret),
                    }
                };

                foreach (var item in user.claims)
                {
                    isuser.AdditionalClaims.Add(new Claim(item.Key, item.Value));
                }
                if (user.user_id != null)
                {
                    isuser.AdditionalClaims.Add(new Claim("user_id", user.user_id));
                }
                if (user.user_name != null)
                {
                    isuser.AdditionalClaims.Add(new Claim("user_name", user.user_name));
                }
                if (user.first_name != null)
                {
                    isuser.AdditionalClaims.Add(new Claim("first_name", user.first_name));
                }
                if (user.last_name != null)
                {
                    isuser.AdditionalClaims.Add(new Claim("last_name", user.last_name));
                }
                if (user.middle_name != null)
                {
                    isuser.AdditionalClaims.Add(new Claim("middle_name", user.middle_name));
                }
                if (user.email != null)
                {
                    isuser.AdditionalClaims.Add(new Claim("email", user.email));
                }
                if (user.user_type != null)
                {
                    isuser.AdditionalClaims.Add(new Claim("user_type", user.user_type));
                }
                isuser.AdditionalClaims.Add(new Claim("roles", Newtonsoft.Json.JsonConvert.SerializeObject(user.roles)));
                var tenants = Newtonsoft.Json.JsonConvert.SerializeObject(user.tenants);
                _logger.Debug($"User tenants {tenants}");
                isuser.AdditionalClaims.Add(new Claim(CommonConst.CommonValue.TENANT_KEY, tenants));

                await HttpContext.SignInAsync(isuser, props);

                return(Redirect(redirecturl));
            }
            else
            {
                _logger.Error($"Auth2Controller.SignIn token validation fail: {token}");
                return(Redirect(unauthorizedPage));
            }
        }