public IActionResult GetPortfolio(int IdUser) { if (IdUser != 0) { var portfolioUser = new List <PortfolioUser>(); using (var db = new BrokerContext()) { var portfolio = db.Portfolios.FirstOrDefault(x => x.UserId == IdUser); if (portfolio != null) { var sharesPortfolio = db.PortfolioShares.Where(x => x.PortfolioId == portfolio.Id).Include(x => x.Share).ToList(); foreach (var item in sharesPortfolio) { var portf = new PortfolioUser(); var share = db.Shares.FirstOrDefault(x => x.Id == item.ShareId); portf.Id = item.Id; portf.CompanyName = item.Share.CompanyName; portf.ShareId = item.Share.Id; portf.Profitability = share.CurrentPrice - item.BuyPrice; portf.ImgSrc = share.ImgSrc; portfolioUser.Add(portf); } } } if (portfolioUser.Count > 0) { return(Ok(portfolioUser)); } else { return(Ok()); } } return(BadRequest()); }
public void AddTransaction(Transaction transaction, PortfolioUser user) { var blobClient = _storageAccount.CreateCloudBlobClient(); var container = blobClient.GetContainerReference("portfolio"); var blob = container.GetBlockBlobReference(user.UserEmail); //container.CreateIfNotExistsAsync }
public static PortfolioUserDao ToDao(this PortfolioUser user) { return(new PortfolioUserDao { HashedPassword = user.Password, UserName = user.UserEmail, Role = user.Role, State = user.State }); }
// based on: https://stackoverflow.com/questions/42471866/how-to-create-roles-in-asp-net-core-and-assign-them-to-users // todo: add proper identity seed public static void CreateRoles(IServiceProvider serviceProvider) { var RoleManager = serviceProvider.GetRequiredService <RoleManager <PortfolioRole> >(); var UserManager = serviceProvider.GetRequiredService <UserManager <PortfolioUser> >(); string adminRole = "Administrator"; var roleExist = RoleManager.RoleExistsAsync(adminRole); roleExist.Wait(); if (!roleExist.Result) { RoleManager.CreateAsync(new PortfolioRole() { Name = adminRole }).Wait(); } string userRole = "User"; roleExist = RoleManager.RoleExistsAsync(userRole); roleExist.Wait(); if (!roleExist.Result) { RoleManager.CreateAsync(new PortfolioRole() { Name = userRole }).Wait(); } // creating a super admin user var superuser = new PortfolioUser { UserName = "******", Name = "Admin Endre", Active = true, Description = "Your friendly neightborhood admin" }; string userPWD = "Admin123?"; var _user = UserManager.FindByNameAsync(superuser.UserName); _user.Wait(); if (_user.Result == null) { var createResult = UserManager.CreateAsync(superuser, userPWD); createResult.Wait(); if (createResult.Result.Succeeded) { UserManager.AddToRoleAsync(superuser, "Administrator").Wait(); } } }
private UserViewModel CreateLoggedInUserResponse(PortfolioUser user, string token) { // this is a bit more easy on the eyes return(new UserViewModel() { Description = user.Description, Id = user.Id, Name = user.Name, Username = user.UserName, Token = token }); }
public async Task <Uri> AddUser(PortfolioUser user) { var userContainer = await GetPortfolioContainer(); var userDao = user.ToDao(); userDao.Id = Guid.NewGuid(); var userBlob = userContainer.GetBlockBlobReference(user.UserEmail); var stringContent = JsonConvert.SerializeObject(userDao); await userBlob.UploadTextAsync(stringContent); return(userBlob.Uri); }
private async Task LoadAsync(PortfolioUser user) { var email = await _userManager.GetEmailAsync(user); Email = email; Input = new InputModel { NewEmail = email, }; IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user); }
public async Task <IActionResult> DeleteRoleForUser(string UserName, string RoleName) { PortfolioUser user = _db.Users.Where(u => u.UserName == UserName).FirstOrDefault(); if (await _userManager.IsInRoleAsync(user, RoleName)) { await _userManager.RemoveFromRoleAsync(user, RoleName); } ViewBag.RoleList = new SelectList(_db.Roles, "Name", "Name"); return(View("ManageUserRoles")); }
private async Task LoadAsync(PortfolioUser user) { var userName = await _userManager.GetUserNameAsync(user); var phoneNumber = await _userManager.GetPhoneNumberAsync(user); Username = userName; Input = new InputModel { PhoneNumber = phoneNumber }; }
public async Task <IActionResult> GetRoles(string UserName) { if (!string.IsNullOrWhiteSpace(UserName)) { PortfolioUser user = _db.Users.Where(u => u.UserName == UserName).FirstOrDefault(); ViewBag.RolesForThisUser = await _userManager.GetRolesAsync(user); ViewBag.RoleList = new SelectList(_db.Roles, "Name", "Name"); } return(View("ManageUserRoles")); }
public static void SeedUsers (UserManager <PortfolioUser> userManager) { if (userManager.FindByNameAsync("Admin").Result == null) { PortfolioUser user = new PortfolioUser(); user.UserName = "******"; IdentityResult result = userManager.CreateAsync(user, "epicodus").Result; if (result.Succeeded) { userManager.AddToRoleAsync(user, "Administrator").Wait(); } } }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new PortfolioUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
private async Task LoadSharedKeyAndQrCodeUriAsync(PortfolioUser user) { // Load the authenticator key & QR code URI to display on the form var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } SharedKey = FormatKey(unformattedKey); var email = await _userManager.GetEmailAsync(user); AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey); }
public async Task <IActionResult> Register(RegisterViewModel model) { var user = new PortfolioUser { UserName = model.UserName, Email = model.Email }; IdentityResult result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "User"); return(RedirectToAction("Index", "Home", null)); } else { return(View()); } }
public async Task <IdentityResult> CreateUserAsync(PortfolioUser user) { var result = new IdentityResult(); try { await _userRepository.AddUser(user); result.Succeeded = true; // TODO: send confimation email } catch (Exception ex) { result.Succeeded = false; result.Errors = new List <string> { ex.Message }; } return(result); }
public async Task <IActionResult> Register([FromBody] RegisterViewModel viewModel) { try { PortfolioUser user = await _userManager.FindByNameAsync(viewModel.Username); if (user != null) { return(Conflict("The specified user alreaedy exist")); } user = new PortfolioUser(); // a more approriate way would be to configure a mapping in Automapper user.Name = viewModel.Name; user.UserName = viewModel.Username; user.Description = viewModel.Description; var result = await _userManager.CreateAsync(user, viewModel.Password); if (!result.Succeeded) { return(Unauthorized(result.Errors.Select(err => err.Description).ToList())); } await _signInManager.PasswordSignInAsync(user, viewModel.Password, false, false); // only simple users can be added through simple registration // admin users only by db or in-app setup, for reasons of simplicity await _userManager.AddToRoleAsync(user, Constants.USER_ROLE); var userRoleId = await _roleManager.FindByNameAsync(Constants.USER_ROLE); // we add the id of the user role only so that no meaningful info is sent out to the client return(Ok(CreateLoggedInUserResponse(user, _tokenService.GenerateToken(user.Id, userRoleId.Id.ToString())))); } catch { return(StatusCode(StatusCodes.Status500InternalServerError, $"Could not register user {viewModel.Username}")); } }
public IEnumerable <Transaction> GetTransactions(PortfolioUser user) { throw new NotImplementedException(); }
public Task UpdateUserPassword(PortfolioUser user) { throw new System.NotImplementedException(); }
public Task <IdentityResult> DeleteUserAsync(PortfolioUser user) { throw new NotImplementedException(); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new PortfolioUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); // If account confirmation is required, we need to show the link if we don't have a real email sender if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email })); } await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } ProviderDisplayName = info.ProviderDisplayName; ReturnUrl = returnUrl; return(Page()); }
public async Task Seed() { _ctx.Database.EnsureCreated(); var user = await _userManager.FindByEmailAsync("*****@*****.**"); if (user == null) { user = new PortfolioUser() { FirstName = "Tom", LastName = "Biagioni", UserName = "******", Email = "*****@*****.**" }; var result = await _userManager.CreateAsync(user, "P@ssw0rd!"); if (result != IdentityResult.Success) { throw new InvalidOperationException("Failed Creating User"); } } if (_ctx.Products.Any()) { return; } //Create Sample Data var filepath = Path.Combine(_hosting.ContentRootPath, "Data/art.json"); var json = File.ReadAllText(filepath); var products = JsonConvert.DeserializeObject <IEnumerable <Product> >(json); _ctx.Products.AddRange(products); var order = new Order() { OrderDate = DateTime.Now, OrderNumber = "12345", User = user, Items = new List <OrderItem>() { new OrderItem() { Product = products.First(), Quantity = 5, UnitPrice = products.First().Price } } }; List <Camp> _sample = new List <Camp> { new Camp() { Name = "Your First Code Camp", Moniker = "ATL2016", EventDate = DateTime.Today.AddDays(45), Length = 1, Description = "This is the first code camp", Location = new Location() { Address1 = "123 Main Street", CityTown = "Atlanta", StateProvince = "GA", PostalCode = "30303", Country = "USA" }, Speakers = new List <Speaker> { new Speaker() { Name = "Shawn Wildermuth", Bio = "I'm a speaker", CompanyName = "Wilder Minds LLC", GitHubName = "shawnwildermuth", TwitterName = "shawnwildermuth", PhoneNumber = "555-1212", HeadShotUrl = "http://wilderminds.com/images/minds/shawnwildermuth.jpg", WebsiteUrl = "http://wildermuth.com", Talks = new List <Talk>() { new Talk() { Title = "How to do ASP.NET Core", Abstract = "How to do ASP.NET Core", Category = "Web Development", Level = "100", Prerequisites = "C# Experience", Room = "245", StartingTime = DateTime.Parse("14:30") }, new Talk() { Title = "How to do Bootstrap 4", Abstract = "How to do Bootstrap 4", Category = "Web Development", Level = "100", Prerequisites = "CSS Experience", Room = "246", StartingTime = DateTime.Parse("13:00") }, } }, new Speaker() { Name = "Resa Wildermuth", Bio = "I'm a speaker", CompanyName = "Wilder Minds LLC", GitHubName = "resawildermuth", TwitterName = "resawildermuth", PhoneNumber = "555-1212", HeadShotUrl = "http://wilderminds.com/images/minds/resawildermuth.jpg", WebsiteUrl = "http://wildermuth.com", Talks = new List <Talk>() { new Talk() { Title = "Managing a Consulting Business", Abstract = "Managing a Consulting Business", Category = "Soft Skills", Level = "100", Room = "230", StartingTime = DateTime.Parse("10:30") } } } } } }; _ctx.Orders.Add(order); _ctx.AddRange(_sample); _ctx.SaveChanges(); }
public Task RemoveUser(PortfolioUser user) { throw new System.NotImplementedException(); }
public Transaction GetTransaction(Guid Id, PortfolioUser user) { throw new NotImplementedException(); }