public async Task <JsonResult> CreateNewUser(PegaUser user) { if (!ModelState.IsValid) { return(Json(ResultsItem.Error(ModelState.GetAllErrorsString()))); } if (!Regex.IsMatch(user.Username, @"^[a-zA-Z0-9_\-\.]+$")) { return(Json(ResultsItem.Error("Username must contain only: Letters(A-Z), Numbers(0-9), _, -, or ."))); } if (!Utilities.IsValidEmailAddress(user.Email)) { return(Json("Please enter a valid email address.")); } var createPair = await AuthorizationLogic.CreateNewUser(user); if (createPair.Result.IsSuccess) { SetSession(Constant.Session.SessionCurrentUser, createPair.Value); TempData["UserCreatedTransferMessage"] = createPair.Result.Message; return(Json(ResultsItem.Success("Success"))); } return(Json(ResultsItem.Error(createPair.Result.Message))); }
public async Task <JsonResult> CurrentUserChangePassword(PegaUser user) { if (user.NewChangedPassword.Length < 8 || user.NewChangedPassword.Length > 30) { return(Json(ResultsItem.Error("Password changed failed: Password length must be from 8 - 30 characters."))); } if (user.NewChangedPassword != user.ConfirmNewChangedPassword) { return(Json(ResultsItem.Error("Passwords does not match."))); } if (CurrentUser.Username != user.Username) { return(Json(ResultsItem.Error("Username does not match."))); } // do-later: check if current pw is valid first. if (!AuthorizationLogic.AuthorizeUser(CurrentUser.Username, user.Password)) // Change password var pwChangeResult = await AuthorizationLogic.ChangePassword(user.Username, user.NewChangedPassword); if (!pwChangeResult.IsSuccess) { return(Json(pwChangeResult)); } HttpContext.Session.Clear(); string successMessage = "Your password has been successfully reset. Please login again"; TempData["message"] = successMessage; return(Json(ResultsItem.Success(successMessage))); }
public static async Task <ResultsItem> CreateBBComment(LocalCommunity.BBComment comment, LocalAccount.PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { comment.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); BBComments serviceComment = comment.Adapt <BBComments>(); serviceComment.CreateDate = DateTime.Now; serviceComment.UserId = user.UserId; serviceComment.Message = serviceComment.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); db.BBComments.Add(serviceComment); await db.SaveChangesAsync(); return(ResultsItem.Success("Successfully posted a new comment.")); } } catch (Exception ex) { Utilities.LogException(new[] { $"User:{user.Username}" }, ex); return(ResultsItem.Error($"Unable to create a comment. {ex.Message}")); } }
public static async Task <ResultsItem> CreateBBThread(LocalCommunity.BBThread thread, LocalAccount.PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { thread.Message = thread.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); thread.UserId = user.UserId; BBThreads serviceMessageThread = thread.Adapt <BBThreads>(); serviceMessageThread.CreateDate = DateTime.Now; serviceMessageThread.UserId = user.UserId; serviceMessageThread.Message = serviceMessageThread.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); serviceMessageThread.Title = serviceMessageThread.Title.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); db.BBThreads.Add(serviceMessageThread); await db.SaveChangesAsync(); return(ResultsItem.Success("Successfully created a new thread")); } } catch (Exception ex) { Utilities.LogException(new[] { $"User:{user.Username}" }, ex); return(ResultsItem.Error($"Unable to create a new thread. {ex.Message}")); } }
public static async Task <ResultsItem> DeleteBBThread(int threadId, LocalAccount.PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { BBThreads serviceThread = db.BBThreads.FirstOrDefault(x => x.ThreadId == threadId); if (serviceThread == null) { return(ResultsItem.Error("This thread was not found or has already been deleted.")); } if (serviceThread.UserId != user.UserId) { return(ResultsItem.Error("This thread belongs to another user.")); } db.Remove(serviceThread); await db.SaveChangesAsync(); return(ResultsItem.Success("Successfully deleted this thread. Please refresh the page to see changes.")); } } catch (Exception ex) { Utilities.LogException(new[] { $"User:{user.Username}" }, ex); return(ResultsItem.Error($"Unable to delete this thread. {ex.Message}")); } }
public static async Task <ResultsItem> UpdateUserCoinAsync(LocalCoins.CryptoCoin coin) { try { using (PegasunDBContext db = new PegasunDBContext()) { Coins serviceCoin = db.Coins.FirstOrDefault(x => x.CoinId == coin.CoinId); if (serviceCoin == null) { return(ResultsItem.Error("This coin was not found.")); } serviceCoin.Shares = coin.Shares; serviceCoin.CoinCurrency = (short)coin.CoinCurrency; serviceCoin.PricePerUnit = coin.PricePerUnit; serviceCoin.TotalPricePaidUsd = coin.TotalPricePaidUSD; serviceCoin.Exchange = (short)coin.Exchange; serviceCoin.OrderType = (short)coin.OrderType; serviceCoin.OrderDate = coin.OrderDate; serviceCoin.SoldCoinCurrency = (short)coin.SoldCoinCurrency; serviceCoin.SoldPricePerUnit = coin.SoldPricePerUnit; serviceCoin.TotalSoldPricePaidUsd = coin.TotalSoldPricePaidUSD; db.Update(serviceCoin); await db.SaveChangesAsync(); } return(ResultsItem.Success("Successfully updated coin.")); } catch (Exception ex) { Utilities.LogException(new[] { "UpdateUserCoinAsync", $"coinId:{coin.CoinId},portfolioId:{coin.PortfolioId}" }, ex); return(ResultsItem.Error($"Unable to updated coin. {ex.Message}")); } }
public static ResultsItem InsertNewAPI(LocalCoins.ExchangeApiInfo exchangeApiDetails, PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { ApiDetails serviceApi = new ApiDetails { Name = exchangeApiDetails.Name.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }), Exchange = (short)exchangeApiDetails.Exchange, ApiAction = (short)exchangeApiDetails.ApiAction, ApiPublic = Cryptography.Encrypt(exchangeApiDetails.ApiPublic, Types.EncryptionType.ApiKey_Public, user), ApiPrivate = Cryptography.Encrypt(exchangeApiDetails.ApiPrivate, Types.EncryptionType.ApiKey_Private, user), ApiThirdKey = exchangeApiDetails.ApiThirdKey.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }), DateAdded = DateTime.Now, UserId = user.UserId, }; db.ApiDetails.Add(serviceApi); db.SaveChanges(); } return(ResultsItem.Success("Successfully created a new API.")); } catch (Exception ex) { return(ResultsItem.Error($"Unable to create a new API. {ex.Message}")); } }
public static async Task <ResultsItem> DeleteUserCoinsAsync(List <CryptoCoin> coins, PegaUser user) { if (coins.Any(x => !IsValidDBRequest(user, x.PortfolioId, validatePortfolio: true).IsSuccess)) { return(ResultsItem.Error(Lang.PortfolioNotFound)); } return(await CryptoRepository.DeleteUserCoinAsync(coins)); }
public async Task <JsonResult> ImportSyncAPI(int apiId, int portfolioId) { ExchangeApiInfo exchangeApiInfo = CurrentUser.ExchangeApiList.FirstOrDefault(x => x.Id == apiId); if (exchangeApiInfo == null) { return(Json(ResultsItem.Error("This API Id cannot be found"))); } if (!CurrentUser.HasPortfolio(portfolioId)) { return(Json(ResultsItem.Error(Lang.PortfolioNotFound))); } // Test -> Move to .Tests solution //List<Core.Data.ServiceModels.ImportedCoin> importedCoins = FetchAPILogic.ImportCSV_Coins(exchangeApiInfo.Exchange, // System.IO.File.OpenRead(@"C:\Users\Ref\Downloads\pegatrade_importFiles\api_test1\2nd-half.csv")); List <Core.Data.ServiceModels.ImportedCoin> importedCoins = await FetchAPILogic.ImportAPI_Coins(exchangeApiInfo, CurrentUser); if (importedCoins.IsNullOrEmpty()) { return(Json(ResultsItem.Error(Lang.UnableToImportWrongKeyPermission))); } List <CryptoCoin> existingExchangeCoins = (await CryptoLogic.GetAllUserCoinsByPortfolioIdAsync(portfolioId)).Where(x => x.Exchange == exchangeApiInfo.Exchange).ToList(); DateTime latestDate = existingExchangeCoins.IsNullOrEmpty() ? DateTime.MinValue : existingExchangeCoins.Max(x => x.OrderDate); // Get rid of ANY imported coins that are less than already existing date. // We dont' want to mess with those, we just want to add new ones. importedCoins = importedCoins.Where(x => x.OrderDate > latestDate).ToList(); if (importedCoins.IsNullOrEmpty()) { Json(ResultsItem.Error(Lang.ApiAlreadyUptoDate)); } List <CryptoCoin> fetchedCoins = FetchAPILogic.FormatCoinsAndGenerateTotalPricePaid(importedCoins, await GetAllHistoricCoinPrices()); if (fetchedCoins.Count > 0) { // Get all current holding coins that will be affected by new coins. Delete them from db as well, we'll re-add them. existingExchangeCoins = existingExchangeCoins.Where(x => x.OrderType == Types.OrderType.Buy && fetchedCoins.Any(f => f.Symbol.EqualsTo(x.Symbol))).ToList(); await CryptoLogic.DeleteUserCoinsAsync(existingExchangeCoins, CurrentUser); existingExchangeCoins.ForEach(x => x.CoinId = 0); // Reset PK so DB can generate a new one. existingExchangeCoins.AddRange(fetchedCoins); existingExchangeCoins = CryptoLogic.FormatCoinsAndBoughtSoldLogicUpdate(existingExchangeCoins); ResultsItem insertResults = await CryptoLogic.InsertCoinsToUserPortfolioAsync(existingExchangeCoins, CurrentUser, portfolioId); if (insertResults.IsSuccess) { return(Json(ResultsItem.Success("Successfully imported coins to your portfolio."))); } } return(Json(ResultsItem.Error(Lang.ApiNoNewTradesOrError))); }
public async Task <ResultsItem> CreateBBThread(BBThread thread) { if (!ModelState.IsValid) { return(ResultsItem.Error(ModelState.GetAllErrorsString())); } OnThreadUpdatedCacheHandler(thread.CategoryCode, thread.OfficialCoinId.GetValueOrDefault()); return(await CommunityLogic.CreateBBThread(thread, CurrentUser)); }
public async Task <ResultsItem> CreateBBComment(BBComment comment) { if (!ModelState.IsValid) { return(ResultsItem.Error(ModelState.GetAllErrorsString())); } OnThreadUpdatedCacheHandler(threadId: comment.ThreadId); OnCommentsUpdatedCacheHandler(comment.ThreadId); return(await CommunityLogic.CreateBBComment(comment, CurrentUser)); }
public JsonResult CreateNewImportAPI(ExchangeApiInfo exchangeApiInfo) { if (!ModelState.IsValid) { return(Json(ResultsItem.Error(ModelState.GetAllErrorsString()))); } exchangeApiInfo.ApiAction = Types.ApiAction.TradesImport; exchangeApiInfo.ApiPrivate = exchangeApiInfo.ApiPrivate.Replace("%2B", "+"); ResultsItem apiResult = CryptoLogic.InsertNewAPI(exchangeApiInfo, CurrentUser); return(Json(apiResult)); }
private ResultsItem CoinManagementValidation(CoinManagementVM vm, bool isSoldMode = false) { if (!ModelState.IsValid) { return(ResultsItem.Error(ModelState.GetAllErrorsString())); } if (!isSoldMode) { vm.Coin.Symbol = vm.Coin.Symbol.ToUpperInvariant(); if (!vm.Coin.Symbol.StartsWith("BTC-") && !vm.Coin.Symbol.StartsWith("ETH-") && !vm.Coin.Symbol.StartsWith("USD-") && !vm.Coin.Symbol.StartsWith("USDT-")) { return(ResultsItem.Error("Error: The coin symbol must start with BTC-, ETH-, USD-, or USDT-")); } if (vm.Coin.OrderDate > DateTime.Now) { return(ResultsItem.Error("Error: Order date must be today or the past.")); } vm.Coin.CoinCurrency = CryptoLogic.GenerateCoinCurrencyFromSymbol(vm.Coin.Symbol); if (vm.Coin.CoinCurrency == Types.CoinCurrency.Unknown || vm.Coin.CoinCurrency == Types.CoinCurrency.EUR) { return(ResultsItem.Error("Error: only BTC, ETH, and USD currency is currently supported.")); } if (vm.Coin.PricePerUnit <= 0) { return(ResultsItem.Error("Please enter Price Per Unit.")); } } else { if (!CurrentUser.HasPortfolio(vm.Coin.PortfolioId)) { return(ResultsItem.Error(Lang.PortfolioNotFound)); } if (vm.Coin.SoldCoinCurrency == Types.CoinCurrency.Unknown || vm.Coin.SoldPricePerUnit.GetValueOrDefault() <= 0) { return(ResultsItem.Error("Please enter all sold details. TotalSoldPrice is optional.")); } if (vm.SoldDate < vm.Coin.OrderDate) { return(ResultsItem.Error("Sold date cannot be lower than Buy date. Unless you're a time traveler.")); } } return(ResultsItem.Success()); }
public async Task <JsonResult> DeleteCoin(int coinId, int portfolioId) { CryptoCoin fetchedCoin = await CryptoLogic.GetSingleCoinByUser(coinId, CurrentUser); if (fetchedCoin?.PortfolioId != portfolioId) { return(Json(ResultsItem.Error(Lang.PortfolioNotFound))); } return(Json(await CryptoLogic.DeleteUserCoinsAsync(new List <CryptoCoin> { new CryptoCoin { CoinId = coinId, PortfolioId = portfolioId } }, CurrentUser))); }
public static async Task <ResultsItem> VoteBBComment(long commentId, bool isUpvote, LocalAccount.PegaUser user) { try { string message = "Successfully updated your vote. It will be reflected shortly."; using (PegasunDBContext db = new PegasunDBContext()) { var getServiceCommentTask = db.BBComments.FirstOrDefaultAsync(x => x.CommentId == commentId); var getExistingVoteTask = db.BBCommentVotes.FirstOrDefaultAsync(x => x.CommentId == commentId && x.UserId == user.UserId); var serviceComment = await getServiceCommentTask; var existingVote = await getExistingVoteTask; if (serviceComment == null) { return(ResultsItem.Error("This comment does not exist.")); } if (existingVote != null) { if (existingVote.IsUpvote == isUpvote) { db.Remove(existingVote); message = "Successfully removed your vote. It will be reflected shortly."; } // Same vote (e.g. clicked on upvote twice), which means they are re-tracing their vote. else { existingVote.IsUpvote = isUpvote; } } else { var newServiceVote = new BBCommentVotes { CommentId = commentId, IsUpvote = isUpvote, UserId = user.UserId }; db.BBCommentVotes.Add(newServiceVote); } db.SaveChanges(); return(ResultsItem.Success(message)); } } catch (Exception ex) { Utilities.LogException(new[] { $"User:{user.Username}", $"CommentId:{commentId}" }, ex); return(ResultsItem.Error($"Unable to submit your vote. {ex.Message}")); } }
public ActionResult UpdatePortfolio(int portfolioId) { Portfolio portfolio = CurrentUser.Portfolios.FirstOrDefault(x => x.PortfolioId == portfolioId); if (portfolio == null) { return(Json(ResultsItem.Error("Unable to find the correct portfolio associated with logged in user."))); } PortfolioVM vm = new PortfolioVM { Portfolio = portfolio, IsCreateMode = false }; return(PartialView("Crud/_ManagePortfolio", vm)); }
/// <summary> /// Returns the API result from Pegasun API /// </summary> /// <param name="response">the HttpResponseMessage</param> /// <param name="successMessage">You can send a custom success message or leave it empty. If empty, will use APIResult's default message.</param> public static ResultsItem GetSimpleHttpResponseResult(HttpResponseMessage response, string successMessage) { if (response.IsSuccessStatusCode) { string jsonString = response.Content.ReadAsStringAsync().Result; ResultsItem apiResult = NetJSON.NetJSON.Deserialize <PegasunAPIResult>(jsonString).ConvertToResultsItem(); if (apiResult.ResultType == ResultsType.Successful) { return(ResultsItem.Success(string.IsNullOrEmpty(successMessage) ? apiResult.Message : successMessage)); } return(apiResult); // Error } return(ResultsItem.Error(Lang.ServerConnectionError)); }
private static ResultsItem IsValidDBRequest(PegaUser user, int id, bool validateAPI = false, bool validatePortfolio = false, bool validateDemoUser = true) { if (validateDemoUser && user.Username.ToUpperInvariant() == "DEMOUSER") { return(ResultsItem.Error("DemoUser is not allowed to perform this action. Please login or create an account for free.")); } if (validatePortfolio && !user.HasPortfolio(id)) { return(ResultsItem.Error(Lang.PortfolioNotFound)); } if (validateAPI && !user.ExchangeApiList.Any(x => x.Id == id)) { return(ResultsItem.Error(Lang.ApiDeleteNotFound)); } return(ResultsItem.Success(string.Empty)); }
public JsonResult SubmitContactUs(ContactUsVM vm) { if (ModelState.IsValid) { if (!Utilities.IsValidEmailAddress(vm.Email)) { return(Json(ResultsItem.Error("Please enter a valid email address."))); } // Send the email and grab the result bool mailSendSuccess = Utilities.SendEmailUsingSyneiGmail(vm.Email, vm.Name, vm.Subject, $"{vm.Name}, {vm.Email} | {vm.Message}"); return(mailSendSuccess ? Json(ResultsItem.Success("Your email has been successfully sent. We'll get back to you as soon as possible. Thanks!")) : Json(ResultsItem.Error("Sending has failed. Please email us manually at [email protected]."))); } return(Json(ResultsItem.Error(ModelState.GetAllErrorsString()))); }
// Warn, this will delete previous imported Exchange (BitTrex, Kraken, etc) trades public async Task <IActionResult> PostCSVTradeHistoryFile(IFormFile file, Types.Exchanges exchange, int portfolioId) { if (file == null || file.Length > 100000 || (!file.FileName.EndsWith(".csv", StringComparison.OrdinalIgnoreCase) && !file.FileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase))) { return(Json(ResultsItem.Error("Please select a proper .csv/.xlsx file that is less than 100kb."))); } List <Core.Data.ServiceModels.ImportedCoin> importedCoins = new List <Core.Data.ServiceModels.ImportedCoin>(); using (var stream = file.OpenReadStream()) { importedCoins = FetchAPILogic.ImportCSV_Coins(exchange, stream); } if (importedCoins.IsNullOrEmpty()) { return(Json(ResultsItem.Error(Lang.ImportFailedCSV))); } int maxAllowedImport = SubscriptionLogic.GetMaxAllowedTradesImportPerUser(CurrentUser.PTUserInfo.SubscriptionLevel); if (importedCoins.Count > maxAllowedImport) { return(Json(ResultsItem.Error(string.Format(Lang.CSVMaxImportAllowed, maxAllowedImport)))); } List <CryptoCoin> fetchedCoins = FetchAPILogic.FormatCoinsAndGenerateTotalPricePaid(importedCoins, await GetAllHistoricCoinPrices()); if (fetchedCoins.Count > 0) { fetchedCoins = CryptoLogic.FormatCoinsAndBoughtSoldLogicUpdate(fetchedCoins); await CryptoLogic.DeleteAllUserCoinByExchangeAsync(portfolioId, exchange, CurrentUser); ResultsItem insertResults = await CryptoLogic.InsertCoinsToUserPortfolioAsync(fetchedCoins, CurrentUser, portfolioId); if (insertResults.IsSuccess) { return(Json(ResultsItem.Success("Successfully imported coins to your portfolio."))); } } return(Json(ResultsItem.Error("An error occured when trying to import trades. Are you sure the import .csv file has correct format?"))); }
public async Task <JsonResult> ExecutePortfolioChanges(PortfolioVM vm) { if (!ModelState.IsValid) { return(Json(ResultsItem.Error(ModelState.GetAllErrorsString()))); } int maxPortfolioAllowed = SubscriptionLogic.GetMaxAllowedPortfolioPerUser(CurrentUser.PTUserInfo.SubscriptionLevel); if (vm.IsCreateMode && CurrentUser.Portfolios.Count >= maxPortfolioAllowed) { return(Json(ResultsItem.Error($"We're sorry, you can only have {maxPortfolioAllowed} portfolios max for your subscription level: {CurrentUser.PTUserInfo.SubscriptionLevel.ToString()}"))); } var portfolioResultPair = vm.IsCreateMode ? (await CryptoLogic.InsertNewPortfolio(CurrentUser, vm.Portfolio.Name, vm.Portfolio.DisplayType, vm.Portfolio.IsDefault)) : CryptoLogic.UpdatePortfolio(vm.Portfolio.PortfolioId, vm.Portfolio.Name, vm.Portfolio.DisplayType, vm.Portfolio.IsDefault, CurrentUser); return(Json(portfolioResultPair.Result)); }
public static async Task <ResultsItem> DeleteAllUserCoinByExchangeAsync(int portfolioId, Types.Exchanges exchange) { try { int exchangeId = (int)exchange; using (PegasunDBContext db = new PegasunDBContext()) { var coins = db.Coins.Where(x => x.PortfolioId == portfolioId && x.Exchange == exchangeId); db.Coins.RemoveRange(coins); await db.SaveChangesAsync(); } return(ResultsItem.Success("Successfully deleted all coins by exchange.")); } catch (Exception ex) { return(ResultsItem.Error($"Unable to delete all coins. {ex.Message}")); } }
public static async Task <ResultsItem> DeletePortfolio(int portfolioId) { try { using (PegasunDBContext db = new PegasunDBContext()) { Portfolios portfolio = db.Portfolios.FirstOrDefault(x => x.PortfolioId == portfolioId); if (portfolio != null) { db.Portfolios.Remove(portfolio); await db.SaveChangesAsync(); } } return(ResultsItem.Success("Successfully deleted portfolio.")); } catch (Exception ex) { return(ResultsItem.Error($"Unable to delete portfolio. {ex.Message}")); } }
public static async Task <ResultsItem> DeleteUserCoinAsync(List <LocalCoins.CryptoCoin> coins) { try { using (PegasunDBContext db = new PegasunDBContext()) { List <Coins> serviceCoins = coins.Select(x => new Coins { CoinId = x.CoinId }).ToList(); db.RemoveRange(serviceCoins); await db.SaveChangesAsync(); } return(ResultsItem.Success("Successfully deleted coin.")); } catch (Exception ex) { return(ResultsItem.Error($"Unable to delete coin. {ex.Message}")); } }
public static async Task <ResultsItem> DeletePegaUser(string username) { using (HttpClient client = new HttpClient()) { var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Username", username) }); HttpResponseMessage response = await client.PostAsync($"{baseUrl}/v1/Account/DeleteUser", content); if (response.IsSuccessStatusCode) { string jsonString = await response.Content.ReadAsStringAsync(); return(NetJSON.NetJSON.Deserialize <PegasunAPIResult>(jsonString).ConvertToResultsItem()); } } return(ResultsItem.Error(Lang.ServerConnectionError)); }
public static ResultsItem DeleteAPI(int apiId) { try { using (PegasunDBContext db = new PegasunDBContext()) { ApiDetails apiDetail = db.ApiDetails.FirstOrDefault(x => x.Id == apiId); if (apiDetail != null) { db.ApiDetails.Remove(apiDetail); db.SaveChanges(); } } return(ResultsItem.Success("Successfully updated deleted API.")); } catch (Exception ex) { return(ResultsItem.Error($"Unable to delete API. {ex.Message}")); } }
public async Task <JsonResult> Login(PegaUser user) { ModelState.Remove("Email"); if (!ModelState.IsValid) { return(Json(ResultsItem.Error(ModelState.GetAllErrorsString()))); } if (!Regex.IsMatch(user.Username, @"^[a-zA-Z0-9_\-\.@]+$")) { return(Json(ResultsItem.Error("Username must contain only: Letters(A-Z), Numbers(0-9), _, -, ., or an email address."))); } ResultsPair <PegaUser> pair = await AuthorizationLogic.AuthorizeUser(user.Username, user.Password); if (pair.Result.IsSuccess) { SetSession(Constant.Session.SessionCurrentUser, pair.Value); return(Json(ResultsItem.Success("Success"))); } return(Json(ResultsItem.Error(pair.Result.Message))); }
public async Task <JsonResult> ChooseNewResetPassword(PasswordUpdateRequest passRequest) { if (passRequest.NewPassword.Length < 8 || passRequest.NewPassword.Length > 30) { return(Json(ResultsItem.Error("Password changed failed: Password length must be from 8 - 30 characters."))); } if (passRequest.NewPassword != passRequest.ConfirmNewPassword) { return(Json(ResultsItem.Error("Passwords does not match."))); } PasswordUpdateRequest savedRequest = TempData["ResetPasswordRequest"] == null ? null : Utilities.Deserialize <PasswordUpdateRequest>(TempData["ResetPasswordRequest"].ToString()); if (savedRequest == null || string.IsNullOrEmpty(savedRequest.AuthenticationHash)) { return(Json(ResultsItem.Error("Password reset form expired. Please request another password reset."))); } if (savedRequest.Username != passRequest.Username) { return(Json(ResultsItem.Error("Passwords does not match."))); } if (Utilities.GenerateHmacSHA256Hash($"{savedRequest.Username}{savedRequest.EmailAuthCode}_ptpwresetreq", "PTPWRESET") != passRequest.AuthenticationHash) { return(Json(ResultsItem.Error("Authentication failed."))); } // Change password var pwChangeResult = await AuthorizationLogic.ChangePassword(passRequest.Username, passRequest.NewPassword); if (!pwChangeResult.IsSuccess) { return(Json(pwChangeResult)); } string successMessage = "Your password has been successfully reset. Please login again"; TempData["message"] = successMessage; return(Json(ResultsItem.Success(successMessage))); }
public static async Task <ResultsItem> InsertCoinsToUserPortfolioAsync(List <CryptoCoin> coins, PegaUser user, int?portfolioId = null) { // Validation: Do not allow symbol to end in -USD. if (coins.Any(x => x.Symbol.ToUpperInvariant().Contains("-USD"))) { if (coins.Count == 1) { return(ResultsItem.Error("The coin symbol must not end in -USD. It should be USD-. For example: USD-ETH, USD-XRP.")); } coins = coins.Where(x => !x.Symbol.ToUpperInvariant().Contains("-USD")).ToList(); } if (portfolioId != null) { coins.ForEach(x => x.PortfolioId = portfolioId.Value); } if (coins.Any(x => !IsValidDBRequest(user, x.PortfolioId, validatePortfolio: true).IsSuccess)) { return(ResultsItem.Error(Lang.PortfolioNotFound)); } return(await CryptoRepository.InsertCoinsToUserPortfolioAsync(coins)); }
public static async Task <ResultsItem> InsertCoinsToUserPortfolioAsync(List <LocalCoins.CryptoCoin> coins) { try { using (PegasunDBContext db = new PegasunDBContext()) { List <Coins> serviceCoins = coins.Where(x => x.Symbol.Length < 10).Select(x => new Coins { CoinId = x.CoinId, Symbol = x.Symbol.Clean(new [] { Types.CleanInputType.Letters, Types.CleanInputType.Digits, Types.CleanInputType.Dash }), Shares = x.Shares, OrderDate = x.OrderDate, CoinCurrency = (short)x.CoinCurrency, PricePerUnit = x.PricePerUnit, TotalPricePaidUsd = x.TotalPricePaidUSD, OrderType = (short)x.OrderType, //Notes = x.Notes, Exchange = (short)x.Exchange, PortfolioId = x.PortfolioId, SoldCoinCurrency = (short)x.SoldCoinCurrency, SoldPricePerUnit = x.SoldPricePerUnit, TotalSoldPricePaidUsd = x.TotalSoldPricePaidUSD, }).ToList(); db.AddRange(serviceCoins); await db.SaveChangesAsync(); } return(ResultsItem.Success("Successfully added all the coins to your portfolio.")); } catch (Exception ex) { Utilities.LogException(new[] { "InsertCoinsToUserPortfolioAsync", $"portfolioId:{coins.First().PortfolioId}" }, ex); return(ResultsItem.Error($"Unable to add all the coins to your portfolio. {ex.Message}")); } }