protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            try
            {
                if (authCookie != null)
                {
                    _userBiz = IocInitializer.GetInstance(typeof(IUserBusiness)) as Business.Implement.UserBusiness;
                    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    JavaScriptSerializer      serializer = new JavaScriptSerializer();
                    var currentUser = serializer.Deserialize <CurrentUserPrincipal>(authTicket.UserData);
                    currentUser.SetIdentity(authTicket.Name);
                    var rep = _userBiz.GetAvailableActions(currentUser.UserId);
                    if (rep != null)
                    {
                        currentUser.UserActionList = rep.Items.ToList();
                        HttpContext.Current.User   = currentUser;
                    }
                }
            }
            catch (Exception ex)
            {
                FileLoger.Info(authCookie.Value, GlobalVariable.LogPath);
                FileLoger.Error(ex, GlobalVariable.LogPath);
                RedirectToAuthentication();
            }
        }
Beispiel #2
0
        public async Task<IResponse<int>> Add(int orderId)
        {
            var order = await _appUOW.OrderRepo.FirstOrDefaultAsync(x => x.OrderId == orderId, new List<System.Linq.Expressions.Expression<System.Func<Order, object>>> { x => x.FromAddress, x => x.ToAddress, x => x.User });
            if (order == null) return new Response<int> { Message = ServiceMessage.RecordNotExist };
            UserComment userComment = null;
            try { userComment = order.UserComment.DeSerializeJson<UserComment>(); } catch { }
            using var deliveryPriceHttp = new HttpClient();
            var callDeliveryAPI = await deliveryPriceHttp.PostAsync(_configuration["Delivery:Add"], new StringContent(new DeliveryOrderDTO
            {
                Addresses = new List<DeliveryOrderLocationDTO>
                {
                    new DeliveryOrderLocationDTO
                    {
                        Type = "origin",
                        Lat = order.FromAddress.Latitude,
                        Lng = order.FromAddress.Longitude
                    },
                    new DeliveryOrderLocationDTO
                    {
                        Type = "destination",
                        Lat = order.ToAddress.Latitude,
                        Lng = order.ToAddress.Longitude,
                        Description=order.OrderComment,
                        PersonFullName =userComment?.Reciever,
                        PersonPhone = userComment?.RecieverMobileNumber
                    }
                }
            }.SerializeToJson(), Encoding.UTF8, "application/json"));
            if (!callDeliveryAPI.IsSuccessStatusCode)
            {
                FileLoger.Info($"Add Delivery Api Failed: {callDeliveryAPI.StatusCode}");
                return new Response<int> { IsSuccessful = false };
            }
            var add = (await callDeliveryAPI.Content.ReadAsStringAsync()).DeSerializeJson<Response<OrderResult>>();
            if (!add.IsSuccessful)
            {
                FileLoger.Info($"Add Delivery Api Failed: {add.Message}");
                return new Response<int> { IsSuccessful = false };
            }
            order.DeliveryDetailJson = new
            {
                add.Result.OrderId,
                add.Result.PayAtDestination,
                add.Result.OrderToken

            }.SerializeToJson();
            _appUOW.OrderRepo.Update(order);
            var update = await _appUOW.ElkSaveChangesAsync();
            if (!update.IsSuccessful)
            {
                FileLoger.Info($"Update Ordder DeliveryDetailJson Failed: {update.Message}");
                return new Response<int> { IsSuccessful = false };
            }
            return new Response<int> { IsSuccessful = true };
        }
        public string GetText(MessagingType type, ConcreteKey key)
        {
            var template = GetAll().FirstOrDefault(x => x.MessagingType == type && x.Key == key.ToString());

            if (template == null)
            {
                FileLoger.Info($"Sms Tempalte With Key {key} Been Removed From Database");

                return("sms template is removed");
            }
            return(template.Text);
        }
Beispiel #4
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var cachePeriod = "0";

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(); app.UseStaticFiles();
                app.UseStaticFiles();
                cachePeriod = "1";
            }
            else
            {
                cachePeriod = "604800";
                app.UseStaticFiles(new StaticFileOptions
                {
                    OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}"); }
                });

                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();

                app.Use(async(context, next) =>
                {
                    await next.Invoke();
                    if (!context.Request.IsAjaxRequest())
                    {
                        var handled    = context.Features.Get <IStatusCodeReExecuteFeature>();
                        var exp        = context.Features.Get <IExceptionHandlerFeature>();
                        var statusCode = context.Response.StatusCode;
                        if (handled == null && statusCode >= 400)
                        {
                            FileLoger.Info(exp.Error.Message);
                            context.Response.Redirect($"/Error/Index?code={statusCode}");
                        }
                    }
                });
            }
            app.UseRouting();

            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Register}");
            });
        }
Beispiel #5
0
        public async Task <FileResult> Android([FromServices] IWebHostEnvironment env)
        {
            try
            {
                var path = Path.Combine(env.WebRootPath, "Files", "DarmanNaft.apk");

                FileLoger.Info($"Download Android Clicked: {path}");

                var memory = new MemoryStream();
                using (var stream = new FileStream(path, FileMode.Open))
                {
                    await stream.CopyToAsync(memory);
                }
                memory.Position = 0;
                return(File(memory, "application/vnd.android.package-archive", Path.GetFileName(path)));
            }
            catch (Exception e)
            {
                FileLoger.Error(e);
                return(null);
            }
        }
        public IActionResponse <string> Verify(PaymentGateway gateway, Transaction model, object responseGateway = null)
        {
            try
            {
                var result    = (SadadPurchaseResult)responseGateway;
                var dataBytes = Encoding.UTF8.GetBytes(result.Token);
                var symmetric = SymmetricAlgorithm.Create("TripleDes");
                symmetric.Mode    = CipherMode.ECB;
                symmetric.Padding = PaddingMode.PKCS7;
                var encryptor  = symmetric.CreateEncryptor(Convert.FromBase64String(gateway.MerchantId), new byte[8]);
                var signedData = Convert.ToBase64String(encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length));
                var data       = new
                {
                    token    = result.Token,
                    SignData = signedData
                };

                var res = CallApi <VerifyResultData>("https://sadad.shaparak.ir/VPG/api/v0/Advice/Verify", data);
                FileLoger.Info(JsonConvert.SerializeObject(res.Result), GlobalVariable.LogPath);
                if (res != null && res.Result != null)
                {
                    if (res.Result.ResCode == "0")
                    {
                        model.IsSuccess  = true;
                        model.TrackingId = res.Result.RetrivalRefNo;
                        model.Status     = "1";
                        if (model.OrderId != 0)
                        {
                            _orderBusiness.UpdateStatus(model.OrderId);
                        }
                        _transactionBusiness.Update(model);

                        _observerManager.Value.Notify(ConcreteKey.Success_Payment, new ObserverMessage
                        {
                            SmsContent = string.Format(LocalMessage.Transaction_Add_Sms, (HttpContext.Current.User as ICurrentUserPrincipal).FullName, model.OrderId),
                            BotContent = string.Format(LocalMessage.Transaction_Add_Bot, (HttpContext.Current.User as ICurrentUserPrincipal).FullName,
                                                       model.OrderId, gateway.BankName.GetLocalizeDescription(),
                                                       model.Price.ToString("0,0"),
                                                       model.TrackingId),
                            Key    = nameof(Transaction),
                            UserId = (HttpContext.Current.User as ICurrentUserPrincipal).UserId,
                        });

                        return(new ActionResponse <string>
                        {
                            IsSuccessful = true,
                            Message = "عملیات پرداخت با موفقیت انجام شد",
                            Result = res.Result.RetrivalRefNo
                        });
                    }
                    return(new ActionResponse <string>
                    {
                        IsSuccessful = false,
                        Message = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید",
                        Result = "-----"
                    });
                }
                else
                {
                    model.IsSuccess  = false;
                    model.TrackingId = result.VerifyResultData.RetrivalRefNo.ToString();
                    model.Status     = "-1";
                    _transactionBusiness.Update(model);
                    return(new ActionResponse <string>
                    {
                        IsSuccessful = false,
                        Message = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید",
                        Result = "----"
                    });
                }
            }
            catch (Exception ex)
            {
                FileLoger.Error(ex, GlobalVariable.LogPath);
                return(new ActionResponse <string>
                {
                    IsSuccessful = false,
                    Message = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید",
                    Result = "---"
                });
            }
        }
        public IActionResponse <string> Verify(PaymentGateway gateway, Transaction model, object responseGateway = null)
        {
            try
            {
                var deserializeResponse = new GatewayPayResponseModel();
                if (responseGateway == null || ((PayRedirectModel)(responseGateway)).status == 0)
                {
                    return new ActionResponse <string>
                           {
                               IsSuccessful = false,
                               Message      = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید",
                           }
                }
                ;

                using (HttpClient http = new HttpClient())
                {
                    var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

                    var response = http.PostAsync($"https://pay.ir/payment/verify?api={gateway.MerchantId.Trim()}&transId={((PayRedirectModel)(responseGateway)).transId}", content).Result;
                    FileLoger.Info("webservice response : " + response.Content.ReadAsStringAsync().Result, GlobalVariable.LogPath);
                    deserializeResponse = JsonConvert.DeserializeObject <GatewayPayResponseModel>(response.Content.ReadAsStringAsync().Result);
                }

                if (deserializeResponse != null && deserializeResponse.status == 1)
                {
                    model.IsSuccess  = true;
                    model.TrackingId = ((PayRedirectModel)(responseGateway)).transId.ToString();
                    model.Status     = deserializeResponse.status.ToString();
                    if (model.OrderId != 0)
                    {
                        _orderBusiness.UpdateStatus(model.OrderId);
                    }
                    _transactionBusiness.Update(model);

                    _observerManager.Value.Notify(ConcreteKey.Success_Payment, new ObserverMessage
                    {
                        SmsContent = string.Format(LocalMessage.Transaction_Add_Sms, (HttpContext.Current.User as ICurrentUserPrincipal).FullName, model.OrderId),
                        BotContent = string.Format(LocalMessage.Transaction_Add_Bot, (HttpContext.Current.User as ICurrentUserPrincipal).FullName,
                                                   model.OrderId, gateway.BankName.GetLocalizeDescription(),
                                                   model.Price.ToString("0,0"),
                                                   model.TrackingId),
                        Key    = nameof(Transaction),
                        UserId = (HttpContext.Current.User as ICurrentUserPrincipal).UserId,
                    });
                    return(new ActionResponse <string>
                    {
                        IsSuccessful = true,
                        Message = "عملیات پرداخت با موفقیت انجام شد",
                        Result = model.TrackingId.ToString()
                    });
                }
                else
                {
                    model.IsSuccess  = false;
                    model.TrackingId = model.TrackingId.ToString();
                    model.Status     = deserializeResponse.status.ToString();
                    _transactionBusiness.Update(model);
                    return(new ActionResponse <string>
                    {
                        IsSuccessful = false,
                        Message = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید",
                        Result = model.TrackingId.ToString()
                    });
                }
            }
            catch (Exception e)
            {
                FileLoger.Error(e, GlobalVariable.LogPath);
                return(new ActionResponse <string>
                {
                    IsSuccessful = false,
                    Message = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید",
                    Result = model.TrackingId.ToString()
                });
            }
        }
Beispiel #8
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var ip = ClientInfo.GetIP(filterContext.HttpContext);

            if (filterContext.HttpContext.Request.Headers["Token"].Count > 0)
            {
                if (Guid.TryParse(filterContext.HttpContext.Request.Headers["Token"][0], out Guid token))
                {
                    var applicationRepo = (ApplicationRepo)filterContext.HttpContext.RequestServices.GetService(typeof(IApplicationRepo));
                    var application     = applicationRepo.GetAsync(token).Result;
                    if (application != null)
                    {
                        //if (application.ValidIp.Split(',').Any(x => x == ip))
                        //{
                        if (filterContext.ActionArguments.ContainsKey("Application"))
                        {
                            filterContext.ActionArguments["Application"] = application;
                        }

                        base.OnActionExecuting(filterContext);
                        //}
                        //else
                        //{
                        //    FileLoger.Info($"Invalid Token To Access Api. Ip Not Valid !" + Environment.NewLine +
                        //    $"IP:{ip}" + Environment.NewLine +
                        //    $"Token:{filterContext.HttpContext.Request.Headers["Token"][0]}");

                        //    filterContext.HttpContext.Response.StatusCode = 403;
                        //    filterContext.Result = new JsonResult(new
                        //    {
                        //        IsSuccessful = false,
                        //        Result = 403,
                        //        Message = "UnAuthorized Access. Ip Not Valid."
                        //    });
                        //}
                    }
                    else
                    {
                        FileLoger.Info($"Invalid Token To Access Api  !" + Environment.NewLine +
                                       $"IP:{ip}" + Environment.NewLine +
                                       $"Token:{filterContext.HttpContext.Request.Headers["Token"][0]}");

                        filterContext.HttpContext.Response.StatusCode = 200;
                        filterContext.Result = new JsonResult(new
                        {
                            Message      = "UnAuthorized Access. Invalid Token To Access Api.",
                            Result       = 200,
                            IsSuccessful = false
                        });
                    }
                }
                else
                {
                    FileLoger.Info($"Invalid Token Type To Access Api  !" + Environment.NewLine +
                                   $"IP:{ip}" + Environment.NewLine +
                                   $"Token:{filterContext.HttpContext.Request.Headers["Token"][0]}");

                    filterContext.HttpContext.Response.StatusCode = 200;
                    filterContext.Result = new JsonResult(new
                    {
                        Message      = "UnAuthorized Access. Invalid Token To Access Api.",
                        Result       = 200,
                        IsSuccessful = false
                    });
                }
            }
            else
            {
                FileLoger.Info($"UnAuthorized Access To Api ! IP:{ip}");

                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = new JsonResult(new
                {
                    Message      = "UnAuthorized Access. Token Not Sent.",
                    Result       = 403,
                    IsSuccessful = false
                });
            }
        }