Beispiel #1
0
        public ServiceResult SendMail(MailMessage msg)
        {
            if (HasError)
            {
                return(ServiceResponse.Error("Error sending email."));
            }

            try
            {
                if (string.IsNullOrWhiteSpace(_settings.EncryptionKey))
                {
                    return(ServiceResponse.Error("The encryption key is not set."));
                }

                string hostPassword = Cipher.Crypt(_settings.EncryptionKey, _settings.HostPassword, false);

                //to user gmail without oauth you need to turn on 2 step verification in gmail account and generate an app key.
                SmtpClient smtp = new SmtpClient();

                smtp.Host      = _settings.MailHost;
                smtp.Port      = _settings.MailPort;
                smtp.EnableSsl = _settings.UseSSL;
                //if (smtp.Host.Contains("gmail"))//this wasn't needed for other hosts.
                // {
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                // }
                //   smtp.Timeout = 20000
                smtp.Credentials = new NetworkCredential(_settings.HostUser, hostPassword);

                try
                {
                    _logger.InsertInfo(JsonConvert.SerializeObject(msg), "SMTP", "SendMail(MailMessage)");
                }
                catch { }
                Disable_CertificateValidation();//shouldn't be used in prod, but tmdhosting is throwing bad cert.
                smtp.Send(msg);
            }
            catch (SmtpException smtpex)
            {
                _logger.InsertError(smtpex.DeserializeException(true), "SMTP", "SendMail(MailMessage)");
            }
            catch (Exception ex)
            {
                _logger.InsertError(ex.DeserializeException(true), "SMTP", "SendMail(MailMessage)");
                return(ServiceResponse.Error("Failed to send email."));
            }

            return(ServiceResponse.OK());
        }
Beispiel #2
0
        public ServiceResult AppStatus(string appType)
        {
            if (string.IsNullOrWhiteSpace(appType))
            {
                return(ServiceResponse.Error("You must send an appType to check."));
            }

            if (Globals.Application.Status == "RUNNING")
            {
                NetworkHelper _network = new NetworkHelper();
                string        ip       = _network.GetClientIpAddress(Request);
                _logger.InsertInfo("ip:" + ip + " appType:" + appType, "AppsController", "AppStatus");
            }
            string status = "NOT IMPLEMENTED";

            switch (appType.ToUpper())
            {
            case "WEB":
                status = Globals.Application.Status;
                break;
                //todo. here we can call methods to check on other apps/services..
            }

            return(ServiceResponse.OK("", status));
        }
Beispiel #3
0
        private void Application_Error(object sender, EventArgs e)
        {
            try
            {
                //  _fileLogger.InsertInfo(JsonConvert.SerializeObject(e), "global.asax", "Application_Error");
                // get the exception and re-throw
                Exception ex = Server.GetLastError();
                _fileLogger.InsertInfo(ex.DeserializeException(true), "global.asax", "Application_Error");

                // SystemLogger logger = new SystemLogger(Globals.DBConnectionKey);
                //logger.InsertError(ex.Message, "Golbal.asax", "Application_Error");
                throw ex;
            }
            catch (HttpException httpEx)
            {
                _fileLogger.InsertInfo(httpEx.DeserializeException(true), "global.asax", "SetCorsOptions");
            }
        }
Beispiel #4
0
        public async Task <ServiceResult> RegisterAsync(UserRegister ur)
        {
            NetworkHelper network = new NetworkHelper();
            string        ip      = network.GetClientIpAddress(this.Request);

            if (!ModelState.IsValid)
            {
                SystemLogger logger = new SystemLogger(Globals.DBConnectionKey);
                logger.InsertInfo(" Invalid form data.", "AccountsController", "RegisterAsync:" + ip);

                return(ServiceResponse.Error("Invalid form data."));
            }

            UserManager userManager = new UserManager(Globals.DBConnectionKey, Request?.Headers?.Authorization?.Parameter);

            //if (ur.ClientType != "mobile.app")
            //{ //if not the mobile app then validate the captcha
            //    UserSession us = SessionManager.GetSessionByUser(ur.Captcha?.ToUpper());
            //    if (us == null)
            //    {
            //        us = SessionManager.GetSessionByUser(ip);//in the sitecontroller the captcha doesn't know whoe the user is when registering, so we used the ip addres as the name
            //        if (us == null)
            //            return ServiceResponse.Error("Invalid session.");
            //    }
            //    if (ur.Captcha?.ToUpper() != us.Captcha?.ToUpper())
            //        return ServiceResponse.Error("Code doesn't match.");
            //}

            //if (ur.ClientType == "mobile.app")
            //    sendValidationEmail = false; //if mobile app don't send the validation email.
            ServiceResult res = await userManager.RegisterUserAsync(ur, false, ip);

            return(res);
            //TODO reimplement this. Change the url sent to be encrypted.
            //if (res.Code != 200  )
            //    return res;

            //User newUser = (User)res.Result;

            //EmailSettings settings = new EmailSettings();

            //string appKey = Globals.Application.AppSetting("AppKey");
            //string emailPassword = Globals.Application.AppSetting("EmailHostPassword");
            //// var testHostPassword = Cipher.Crypt(appKey,emailPassword, false);
            //settings.HostPassword =  Globals.Application.AppSetting("EmailHostPassword");
            //settings.EncryptionKey = Globals.Application.AppSetting("AppKey");
            //settings.HostUser= Globals.Application.AppSetting("EmailHostUser");
            //settings.MailHost= Globals.Application.AppSetting("MailHost");
            //settings.MailPort = StringEx.ConvertTo<int>(Globals.Application.AppSetting("MailPort"));
            //settings.SiteDomain= Globals.Application.AppSetting("SiteDomain");
            //settings.SiteEmail= Globals.Application.AppSetting("SiteEmail");
            //settings.UseSSL= StringEx.ConvertTo<bool>(Globals.Application.AppSetting("UseSSL"));

            //ServiceResult emailRes = await userManager.SendUserEmailValidationAsync(newUser, newUser.ProviderUserKey, ip, settings);

            //if (emailRes.Code != 200)
            //{
            //    return ServiceResponse.OK("Registration email failed to send. Check later for email confirmation.");
            //}
            //return emailRes;
        }
Beispiel #5
0
 public EventsController()
 {
     _fileLogger.InsertInfo("EventsController", "EventsController", "EventsController()");
 }
        private void ProcessPayPalPurchase(PayPalResponse ipnResponse)
        {
            if (ipnResponse == null)
            {
                return;
            }

            if (ipnResponse.payment_status?.ToLower() != "completed")
            {
                return;
            }
            try
            {
                using (var transactionScope = new TransactionScope())
                    using (var context = new GreenWerxDbContext(_dbConnectionKey))
                    {
                        Order o = context.GetAll <Order>()?.FirstOrDefault(w => w.CartUUID == ipnResponse.custom);

                        if (o == null)
                        { //  get order by shoppingCartUUID == ipnResponse.custom
                            Debug.Assert(false, "ORDER NOT FOUND");
                            _logger.InsertError("ORDER NOT FOUND custom value:" + ipnResponse.custom, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }

                        if (o.TransactionID == ipnResponse.txn_id)
                        { // check that Txn_id has not been previously processed
                            Debug.Assert(false, "TRANSACTION ALREADY PROCESSED");
                            _logger.InsertError("TRANSACTION ALREADY PROCESSED:" + ipnResponse.txn_id, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }

                        if (o.Total > ipnResponse.mc_gross)
                        {
                            // Debug.Assert(false, "UNDERPAYMENT RECIEVED");
                            o.PayStatus = LedgerFlag.Status.PaymentPartialRecieved;
                            _logger.InsertInfo("UNDERPAYMENT RECIEVED order uuid:" + o.UUID, "PaymentGateway", "ProcessPayPalPurchase");
                            // return;
                        }
                        if (o.Total < ipnResponse.mc_gross)
                        {
                            o.PayStatus = LedgerFlag.Status.OverPaymentReceived;
                            //Debug.Assert(false, "OVERPAYMENT RECIEVED");
                            _logger.InsertInfo("OVERPAYMENT RECIEVED order uuid:" + o.UUID, "PaymentGateway", "ProcessPayPalPurchase");
                            // return;
                        }
                        if (o.Total == ipnResponse.mc_gross)
                        {
                            o.PayStatus = LedgerFlag.Status.Paid;
                        }

                        FinanceAccount financeAccount = context.GetAll <FinanceAccount>()?.FirstOrDefault(w => w.UUID == o.FinancAccountUUID);

                        if (financeAccount == null)
                        {
                            Debug.Assert(false, "Unable to find finance account.");
                            _logger.InsertInfo("Unable to find finance account.:" + o.FinancAccountUUID, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }
                        var    app    = new AppManager(_dbConnectionKey, "web", "");
                        string secret = app.GetSetting("AppKey")?.Value;
                        var    email  = Cipher.Crypt(secret, ipnResponse.receiver_email.ToLower(), true);

                        if (financeAccount.Email != email)
                        { // check that Receiver_email is your Primary PayPal email
                            Debug.Assert(false, "Receiver_email doesn't match financeAccount Email");
                            _logger.InsertInfo("Receiver_email doesn't match financeAccount Email:" + email + ":" + financeAccount.Email, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }
                        Currency currency = context.GetAll <Currency>( )?.FirstOrDefault(w => w.UUID == o.CurrencyUUID);
                        if (currency == null)
                        {
                            Debug.Assert(false, "Unable to find currency .");
                            _logger.InsertInfo("Unable to find currency .:" + o.CurrencyUUID, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }
                        if (!currency.Code.EqualsIgnoreCase(ipnResponse.mc_currency))
                        {                    // check that mc_gross/mc_currency = USD are correct
                            Debug.Assert(false, "mc_currency doesn't match currency.Code");
                            _logger.InsertInfo("mc_currency doesn't match currency.Code:" + ipnResponse.mc_currency + ":" + currency.Code, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }

                        if (o.PayStatus == LedgerFlag.Status.Paid || o.PayStatus == LedgerFlag.Status.OverPaymentReceived)
                        {
                            List <OrderItem> orderItems = context.GetAll <OrderItem>()?.Where(w => w.OrderUUID == o.UUID).ToList();
                            foreach (OrderItem oi in orderItems)
                            {
                                oi.AccessGranted = true;
                                oi.AccessExpires = DateTime.UtcNow.AddDays(120); //todo make configurable.
                                context.Update <OrderItem>(oi);
                            }
                        }
                        //update order status to paid or complete etc.
                        FinanceAccountTransaction payment = new FinanceAccountTransaction()
                        {
                            AccountEmail = financeAccount.Email,
                            DateCreated  = DateTime.UtcNow,
                            Image        = financeAccount.Image,
                            CurrencyUUID = financeAccount.CurrencyUUID,
                            //CustomerIp = ipAddress,
                            CreationDate           = DateTime.Now,
                            LastPaymentStatusCheck = DateTime.UtcNow,
                            OrderUUID                = o.UUID,
                            Balance                  = o.Total - ipnResponse.mc_gross,
                            AmountTransferred        = 0,
                            TransactionDate          = DateTime.UtcNow,
                            TransactionType          = LedgerFlag.TransactionTypes.Credit,
                            Status                   = LedgerFlag.Status.PendingIncome,
                            SelectedPaymentTypeTotal = o.Total,
                            UserUUID                 = o.UserUUID,
                            //   PayFromAccountUUID = todo this is the customers account id. won't need it for now. we could also use it to set up accounts where users
                            //                          can order and be billed later.
                            FinanceAccountUUID        = financeAccount.UUID,
                            PayToAccountUUID          = financeAccount.AccountNumber, //todo this should be the store account",
                            PaymentTypeUUID           = "PayPal",
                            SelectedPaymentTypeSymbol = currency?.Symbol
                                                        //    // = affiliateId,
                        };
                        context.Insert <FinanceAccountTransaction>(payment);

                        transactionScope.Complete();
                    }
            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message);
                _logger.InsertError(ex.Message, "PaymentGateway", "ProcessPayPalPurchase");
            }
        }
Beispiel #7
0
        public ServiceResult SetUserFlag(string userUUID, string userFlag, string flagValue, bool authorize = true)
        {
            User u;

            using (var context = new TreeMonDbContext(this._connectionKey))
            {
                u = context.GetAll <User>().FirstOrDefault(uw => uw.UUID == userUUID);
            }

            if (u == null)
            {
                return(ServiceResponse.Error("User not found."));
            }

            if (authorize)
            {
                if (!this.DataAccessAuthorized(u, "PATCH", false))
                {
                    return(ServiceResponse.Error("You are not authorized this action."));
                }
            }

            if (string.IsNullOrWhiteSpace(userFlag) || string.IsNullOrWhiteSpace(flagValue))
            {
                return(ServiceResponse.Error("You are missing a flag or value to set."));
            }

            switch (userFlag.ToUpper())
            {  // CTRL+SHIFT+U. to toggle case
            case "PROVIDERNAME":
                u.ProviderName = flagValue;
                break;

            case "PROVIDERUSERKEY":
                u.ProviderUserKey = flagValue;
                break;

            case "ACTIVE":
                u.Active = StringEx.ConvertTo <bool>(flagValue);
                break;

            case "DELETED":
                u.Deleted = StringEx.ConvertTo <bool>(flagValue);
                break;

            case "PRIVATE":
                u.Private = StringEx.ConvertTo <bool>(flagValue);
                break;

            case "ANONYMOUS":
                u.Anonymous = StringEx.ConvertTo <bool>(flagValue);
                break;

            case "APPROVED":
                u.Approved = StringEx.ConvertTo <bool>(flagValue);
                break;

            case "BANNED":
                u.Banned = StringEx.ConvertTo <bool>(flagValue);
                break;

            case "LOCKEDOUT":
                u.LockedOut = StringEx.ConvertTo <bool>(flagValue);
                if (u.LockedOut == true)
                {
                    u.LastLockoutDate = DateTime.UtcNow;
                }
                break;

            case "ONLINE":
                u.Online = StringEx.ConvertTo <bool>(flagValue);
                break;

            //case "SITEADMIN": break;// backlog this requires security validation before implementing since its a very powerfull account
            default:
                return(ServiceResponse.Error("Invalid flag."));
            }
            u.LastUpdatedDate = DateTime.UtcNow;
            using (var context = new TreeMonDbContext(this._connectionKey))
            {
                if (context.Update <User>(u) < 0)
                {
                    return(ServiceResponse.Error("Error occurred saving user " + u.Name));
                }
            }

            _logger.InsertInfo("userUUID:" + userUUID + ",userFlag:" + userFlag + ",flagValue:" + flagValue, "UserManager", "SetUserFlag");

            return(ServiceResponse.OK("User " + u.Name + " updated."));
        }