public static ResultsPair <LocalCoins.Portfolio> UpdatePortfolio(int portfolioId, string portfolioName, Types.PortfolioDisplayType displayType, bool isDefault) { try { using (PegasunDBContext db = new PegasunDBContext()) { Portfolios portfolio = db.Portfolios.FirstOrDefault(x => x.PortfolioId == portfolioId); if (portfolio != null) { portfolio.Name = portfolioName.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }); portfolio.DisplayType = (short)displayType; portfolio.IsDefault = isDefault; db.Update(portfolio); db.SaveChanges(); } return(ResultsPair.Create(ResultsItem.Success("Successfully updated portfolio name."), portfolio.Adapt <LocalCoins.Portfolio>())); } } catch (Exception ex) { Utilities.LogException(new[] { "UpdatePortfolio", $"portfolioId:{portfolioId},portfolioName:{portfolioName}" }, ex); return(ResultsPair.CreateError <LocalCoins.Portfolio>($"Unable to update portfolio. {ex.Message}")); } }
public static async Task <ResultsPair <LocalCoins.Portfolio> > ResetAllUserTrades(PegaUser user) { ResultsPair <LocalCoins.Portfolio> generateError(string error) { return(ResultsPair.CreateError <LocalCoins.Portfolio>(error)); } try { using (PegasunDBContext db = new PegasunDBContext()) { var portfolios = db.Portfolios.Where(x => user.Portfolios.Any(p => p.PortfolioId == x.PortfolioId)); db.Portfolios.RemoveRange(portfolios); await db.SaveChangesAsync(); var insertPortfolioResult = await InsertNewPortfolio(user.UserId, "Default", Types.PortfolioDisplayType.Public, true); if (insertPortfolioResult.Result.IsSuccess) { insertPortfolioResult.Result.Message = "Successfully reset all of your trades."; return(insertPortfolioResult); } return(generateError("An error occured during the reset process. Please re-login and try again.")); } } catch (Exception ex) { return(generateError($"An error occured during the reset process. Please re-login and try again. Error: {ex.Message}")); } }
public static async Task <ResultsPair <LocalCoins.Portfolio> > InsertNewPortfolio(int userId, string portfolioName, Types.PortfolioDisplayType displayType, bool isDefault) { try { using (PegasunDBContext db = new PegasunDBContext()) { Portfolios portfolio = new Portfolios { UserId = userId, Name = portfolioName.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }), DisplayType = (short)displayType, IsDefault = isDefault }; db.Portfolios.Add(portfolio); await db.SaveChangesAsync(); return(ResultsPair.Create(ResultsItem.Success("Successfully created a new portfolio."), portfolio.Adapt <LocalCoins.Portfolio>())); } } catch (Exception ex) { return(ResultsPair.CreateError <LocalCoins.Portfolio>($"Unable to create a new portfolio. {ex.Message}")); } }
private static async Task <ResultsPair <LocalAccount.PTUserInfo> > CreateNewPTUserInfo(LocalAccount.PegaUser user) { try { using (PegasunDBContext db = new PegasunDBContext()) { PTUserInfo ptUserInfo = new PTUserInfo { UserId = user.UserId, SubscriptionLevel = (byte)SubscriptionLevel.Free, SubscriptionExpireDate = null }; db.PTUserInfo.Add(ptUserInfo); await db.SaveChangesAsync(); LocalAccount.PTUserInfo localSubscription = ptUserInfo.Adapt <LocalAccount.PTUserInfo>(); return(ResultsPair.Create(ResultsItem.Success("Successfully created a new subscription."), localSubscription)); } } catch (Exception ex) { return(ResultsPair.CreateError <LocalAccount.PTUserInfo>($"Unable to create a new PTUserInfo: {ex.Message}")); } }
public static ResultsPair <LocalAccount.ViewUser> AuthorizeViewUser(string username, string portfolioName) { using (PegasunDBContext db = new PegasunDBContext()) { var user = db.Users.FirstOrDefault(x => x.Username == username); if (user == null) { return(ResultsPair.CreateError <LocalAccount.ViewUser>($"Could not find the user {username}.")); } var portfolios = db.Portfolios.Where(x => x.UserId == user.UserId && x.DisplayType == 3).ToList(); if (portfolios.IsNullOrEmpty() || !portfolios.Any(x => Utilities.FormatPortfolioName(x.Name).EqualsTo(portfolioName))) { return(ResultsPair.CreateError <LocalAccount.ViewUser>($"Could not find the portfolio {portfolioName}")); } return(ResultsPair.CreateSuccess(new LocalAccount.ViewUser { PortfolioName = portfolioName, SelectedPortfolioID = portfolios.First(x => Utilities.FormatPortfolioName(x.Name).EqualsTo(portfolioName)).PortfolioId, Portfolios = portfolios.Adapt <List <LocalCoins.Portfolio> >(), Username = user.Username })); } }
public static ResultsPair <Portfolio> UpdatePortfolio(int portfolioId, string portfolioName, Types.PortfolioDisplayType displayType, bool isDefault, PegaUser user) { if (!IsValidDBRequest(user, portfolioId, validatePortfolio: true).IsSuccess) { return(ResultsPair.CreateError <Portfolio>(Lang.PortfolioNotFound)); } return(CryptoRepository.UpdatePortfolio(portfolioId, portfolioName, displayType, isDefault)); }
public static async Task <ResultsPair <Portfolio> > InsertNewPortfolio(PegaUser user, string portfolioName, Types.PortfolioDisplayType displayType, bool isDefault) { var validateRequest = IsValidDBRequest(user, 0); if (!validateRequest.IsSuccess) { return(ResultsPair.CreateError <Portfolio>(validateRequest.Message)); } return(await CryptoRepository.InsertNewPortfolio(user.UserId, portfolioName, displayType, isDefault)); }
public async Task <ActionResult> Demo() { ResultsPair <PegaUser> pair = await AuthorizationLogic.AuthorizeUser("DemoUser", "49SPtrkuKDAtU27ifROw"); if (pair.Result.IsSuccess) { SetSession(Constant.Session.SessionCurrentUser, pair.Value); return(RedirectToAction("Index", "Crypto")); } return(RedirectToAction("Index", "Home")); }
public void CreateUserTest() { ResultsItem deleteResult = AuthorizationLogic.DeletePegaUser("Test1234").Result; PegaUser user = new PegaUser { Username = "******", Password = "******", Email = "*****@*****.**", IsSubscribeNewsLetter = true }; ResultsPair <PegaUser> result = AuthorizationLogic.CreateNewUser(user).Result; Assert.IsTrue(result.Result.ResultType == Types.ResultsType.Successful); }
public static async Task <ResultsPair <LocalAccount.PegaUser> > AuthorizeUser(string username, string password) { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync($"{baseUrl}/v1/Account/Authenticate?username={username}&password={password}"); if (response.IsSuccessStatusCode) { string jsonString = await response.Content.ReadAsStringAsync(); PegasunAPIAuthorization apiUser = NetJSON.NetJSON.Deserialize <PegasunAPIAuthorization>(jsonString); if (apiUser != null && apiUser.result.resultType == 0) { // Todo: Move this out? make less calls var portfolioTask = CryptoLogic.GetAllUserPortfolioAsync(new LocalAccount.PegaUser { UserId = apiUser.userId, Username = apiUser.username }); var apiResultsTask = CryptoLogic.GetAllUserExchangeAPIAsync(apiUser.userId); var ptUserInfoTask = GetPTUserInfo(apiUser.userId); var portfolios = await portfolioTask; var apiList = await apiResultsTask; var ptUserInfo = await ptUserInfoTask; return(ResultsPair.CreateSuccess(new LocalAccount.PegaUser { UserId = apiUser.userId, Username = apiUser.username, Email = apiUser.email, FullName = apiUser.fullName, Portfolios = portfolios, ExchangeApiList = apiList, PTUserInfo = ptUserInfo, EmailConfirmed = apiUser.emailConfirmed })); } return(ResultsPair.CreateError <LocalAccount.PegaUser>(apiUser?.result.message ?? "An unknown error occured.")); } } return(ResultsPair.CreateError <LocalAccount.PegaUser>(Lang.ServerConnectionError)); }
public static ResultsPair <LocalAccount.PegaUser> ViewUserProfile(string username) { using (PegasunDBContext db = new PegasunDBContext()) { var user = db.Users.FirstOrDefault(x => x.Username == username); if (user == null) { return(ResultsPair.CreateError <LocalAccount.PegaUser>($"Could not find the user {username}.")); } var portfolios = db.Portfolios.Where(x => x.UserId == user.UserId && x.DisplayType == 3).ToList(); LocalAccount.PegaUser localUser = user.Adapt <LocalAccount.PegaUser>(); localUser.Portfolios = portfolios.Adapt <List <LocalCoins.Portfolio> >(); localUser.TotalCreatedThreads = db.BBThreads.Count(x => x.UserId == user.UserId); localUser.TotalCreatedComments = db.BBComments.Count(x => x.UserId == user.UserId); return(ResultsPair.CreateSuccess(localUser)); } }
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))); }
// Creates a new user and then redirects them to the login page. public static async Task <ResultsPair <LocalAccount.PegaUser> > CreateNewUser(LocalAccount.PegaUser user) { using (HttpClient client = new HttpClient()) { var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Username", user.Username), new KeyValuePair <string, string>("Password", user.Password), new KeyValuePair <string, string>("Email", user.Email), new KeyValuePair <string, string>("EmailSubscribePreferenceCode", ((int)EmailPreferences.Default).ToString()), new KeyValuePair <string, string>("platform", ((int)Platform.PegaTrade).ToString()) }); HttpResponseMessage response = await client.PostAsync($"{baseUrl}/v1/Account/Create", content); if (response.IsSuccessStatusCode) { string jsonString = await response.Content.ReadAsStringAsync(); ResultsItem createUserResult = NetJSON.NetJSON.Deserialize <PegasunAPIResult>(jsonString).ConvertToResultsItem(); if (createUserResult.ResultType == ResultsType.Successful) { var getUserResult = await AuthorizeUser(user.Username, user.Password); if (!getUserResult.Result.IsSuccess) { return(getUserResult); } return(ResultsPair.Create(createUserResult, getUserResult.Value)); } return(ResultsPair.CreateError <LocalAccount.PegaUser>(createUserResult.Message)); } } return(ResultsPair.CreateError <LocalAccount.PegaUser>(Lang.ServerConnectionError)); }
public async Task <PartialViewResult> LoadPortfolioViewMode(PortfolioRequest request, string username, string portfolioName, bool coinsOnly = false) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(portfolioName)) { return(null); } request.ViewUser = new ViewUser { Username = username, PortfolioName = portfolioName, }; request.ViewUser.PortfolioName = Utilities.FormatPortfolioName(request.ViewUser.PortfolioName); request.ViewOtherUser = true; ResultsPair <ViewUser> viewUserResult = AuthorizationLogic.AuthorizeViewUser(request.ViewUser.Username, request.ViewUser.PortfolioName); if (!viewUserResult.Result.IsSuccess) { return(GeneratePartialViewError(viewUserResult.Result.Message)); } request.ViewUser = viewUserResult.Value; if (coinsOnly) { request.PortfolioID = request.ViewUser.SelectedPortfolioID; CoinsVM coinsVM = await GenerateCoinsVM(request); return(PartialView("_FullCoins", coinsVM)); } PortfolioVM vm = await GeneratePortfolioVM(request); return(PartialView("_Portfolio", vm)); }
public static async Task <ResultsPair <List <LocalCoins.CryptoCoin> > > ApiImport_EtherAddress(List <LocalCoins.MarketCoin> marketCoins, string etherAddress, int portfolioId, LocalAccount.PegaUser user) { ResultsPair <List <LocalCoins.CryptoCoin> > generateError(string errorMessage) => ResultsPair.CreateError <List <LocalCoins.CryptoCoin> >(errorMessage); LocalCoins.CryptoCoin generateCoin(string symbol, decimal shares, decimal pricePerUnit) { return(new LocalCoins.CryptoCoin { CoinCurrency = Types.CoinCurrency.USD, Exchange = Types.Exchanges.EtherAddressLookup, OrderDate = DateTime.Now, OrderType = Types.OrderType.Buy, PortfolioId = portfolioId, Shares = shares, TotalPricePaidUSD = shares * pricePerUnit, PricePerUnit = pricePerUnit, Symbol = symbol }); } if (etherAddress.Length != 42) { return(generateError("This ethereum address is not valid.")); } string url = $"https://api.ethplorer.io/getAddressInfo/{etherAddress}?apiKey=freekey"; using (HttpClient client = new HttpClient()) { string jsonResult = await client.GetStringAsync(url); if (string.IsNullOrEmpty(jsonResult)) { return(generateError("An error has occured while calling the API endpoint")); } API_EthplorerAddressLookup result = Newtonsoft.Json.JsonConvert.DeserializeObject <API_EthplorerAddressLookup>(jsonResult); if (result != null) { List <LocalCoins.CryptoCoin> coins = new List <LocalCoins.CryptoCoin>(); if (result.Eth.Balance > 0) { coins.Add(generateCoin("USD-ETH", (decimal)result.Eth.Balance, marketCoins.First(x => x.Symbol == "ETH").CurrentSymbolPriceUSD)); if (!result.Tokens.IsNullOrEmpty()) { foreach (var x in result.Tokens.Where(x => x.TokenInfo != null && x.Balance > 0)) { try { LocalCoins.MarketCoin marketCoin = marketCoins.FirstOrDefault(m => m.Name.ToUpper() == x.TokenInfo.Name.ToUpper()); if (marketCoin == null) { marketCoin = marketCoins.FirstOrDefault(m => m.Symbol.ToUpper() == x.TokenInfo.Symbol.ToUpper()); } if (marketCoin == null) { continue; } double tokenDecimals = x.TokenInfo.Decimals; decimal shares = tokenDecimals <= 0 ? (decimal)x.Balance : (decimal)(x.Balance / Math.Pow(10, x.TokenInfo.Decimals)); coins.Add(generateCoin($"USD-{x.TokenInfo.Symbol}", shares, marketCoin.CurrentSymbolPriceUSD)); } catch { } } ; } } return(ResultsPair.CreateSuccess(coins)); } return(generateError("Something went wrong, or you may not have any coins to import")); } }