public async Task <IActionResult> Register(AccountVM vm) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = vm.Email, Email = vm.Email }; var result = await _userManager.CreateAsync(user, vm.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return(RedirectToAction("Index", "Main")); } else { foreach (var error in result.Errors) { ModelState.TryAddModelError("", error.Description); } } } return(View(vm)); }
public void OnAccountSelected(AccountVM accountVm) { string viewName = accountVm.InvestorId; var existingPane = RegionManager.GetExistingPane <PortfolioContentPane>(viewName); if (existingPane != null) { existingPane.Activate(); } else { PortfolioContentPane pane = new PortfolioContentPane(); pane.ViewName = viewName; var portfoliosView = ServiceLocator.Current.GetInstance <PortfoliosView>(); portfoliosView.SetAccount(accountVm); pane.Content = portfoliosView; //pane.CloseAction = Infragistics.Windows.DockManager.PaneCloseAction.RemovePane; pane.Closed += new EventHandler <Infragistics.Windows.DockManager.Events.PaneClosedEventArgs>(pane_Closed); pane.Loaded += (s, e) => portfoliosView.OnViewSelected(); RegionManager.RegisterViewWithRegion(RegionNames.PortfolioViewRegion, () => pane); pane.Activate(); } }
public ActionResult Details(int id) { AccountVM vm = new AccountVM(); Account u = vm.Find(id); return(View(u)); }
//атутентификация пользователя и получение ролей public AccountVM Authenticate(string username, string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { throw new AppException("Не все поля заполнены"); } //получаем сущность юзера из бд var user = accountRepository.FindAll().SingleOrDefault(x => x.Username == username); //проверка на существующий логин if (user == null) { throw new AppException("Пользователя не существует"); } AccountVM userVM = new AccountVM() { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, Username = user.Username, Roles = AccountRole(user), }; //проверка на правильный пароль if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt)) { throw new AppException("Пароль не корректен"); } // authentication successful return(userVM); }
public async Task <IActionResult> Account(string returnUrl = "/") { var rqf = Request.HttpContext.Features.Get <IRequestCultureFeature>(); var culture = rqf.RequestCulture.Culture; var cookieValue = Request.Cookies["Token"]; if (cookieValue == null) { return(Redirect((!string.IsNullOrEmpty(Request.Headers["Referer"]) ? Request.Headers["Referer"].ToString() : returnUrl))); } UserClient user = await _db.UserClients.FirstOrDefaultAsync(a => a.Token == cookieValue); if (user == null) { return(Redirect((!string.IsNullOrEmpty(Request.Headers["Referer"]) ? Request.Headers["Referer"].ToString() : returnUrl))); } AccountVM model = new AccountVM { Breadcrumb = new Breadcrumb { Path = new Dictionary <string, string> { { "Home", Url.Action("Index", "Home") }, { "Account", null } }, Page = Page.Account }, User = user, LanguageId = _db.Languages.FirstOrDefault(x => x.LanguageCode == culture.ToString()).Id, OrderProducts = await _db.OrderProducts.Include("Product").Include("Color").Where(x => x.Status == true && x.UserClientId == user.Id).OrderByDescending(x => x.Complete).ThenByDescending(x => x.CreatedAt).ToListAsync() }; return(View(model)); }
public AccountVM GetAccount() { AccountVM a = new AccountVM(_db); a.GetAvailableFunds(); return(a); }
public ActionResult GetAccountById(int id, [FromQuery] bool withRateScore) { IQueryable <Account> accountList = _accountService.GetAll( s => s.Services, s => s.Gallery.Images, _ => _.Addresses); Account account = accountList.FirstOrDefault(s => s.Id == id); AccountVM returnAccount = null; if (account != null) { returnAccount = _mapper.Map <AccountVM>(account); if (withRateScore) { var rating = _feedBackService.GetRateScoreByAccount(returnAccount.Id); returnAccount.RateScore = rating[0]; returnAccount.TotalFeedback = (int)rating[1]; } foreach (ServiceVM srv in returnAccount.Services) { if (srv.Status == "Hủy") { returnAccount.Services.Remove(srv); } } return(Ok(returnAccount)); } else { return(NotFound(returnAccount)); } }
public async Task <ActionResult <AccountVM> > Create([FromBody] AccountVM accountVM) { // Validation if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Mapping Account account = this.mapper.Map <AccountVM, Account>(accountVM); // BLL User currentUser = await userManager.GetUserAsync(User); AccountBLL bll = new AccountBLL(this.unitOfWork, currentUser); // Create Account newAccount; try { newAccount = await bll.CreateAccount(account); } catch (CrmException ex) { return(BadRequest(this.mapper.Map <CrmException, CrmExceptionVM>(ex))); } // Mapping return(CreatedAtAction("GetById", new { id = newAccount.Id }, this.mapper.Map <Account, AccountVM>(newAccount))); }
public async Task <ActionResult <AccountVM> > Update(Guid id, [FromBody] AccountVM accountVM) { // Validation if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != accountVM.Id) { return(BadRequest()); } if (!this.unitOfWork.context.Accounts.Any(a => a.Id == id)) { return(NotFound()); } // Mapping Account account = this.mapper.Map <AccountVM, Account>(accountVM); // BLL User currentUser = await userManager.GetUserAsync(User); AccountBLL bll = new AccountBLL(this.unitOfWork, currentUser); // Update Account updatedAccount = await bll.UpdateAccount(account); // Mapping return(Ok(this.mapper.Map <Account, AccountVM>(updatedAccount))); }
public async Task <string> AddUpdateUser(AccountVM accountVM) { AccountDomainModel accountDM = new AccountDomainModel(); AutoMapper.Mapper.Map(accountVM, accountDM); return(await accountBusiness.AddUpdateAccount(accountDM)); }
/// <summary> /// Create a new account for a employee /// </summary> /// <param name="accountVM">Account VM</param> /// <param name="currentUserId">Current user id</param> /// <returns>A void task</returns> public async Task <Account> CreateAccount(AccountVM accountVM, int currentUserId) { var employee = await this.employeeRepository.GetEmployeeByCode(accountVM.Ma_NhanVien); if (employee == null) { throw new Exception("Nhân viên không tồn tại"); } var account = new Account { Id_NhanVien = employee.Id_NhanVien, UserName = accountVM.UserName, MatKhau = Common.MD5Hash(accountVM.MatKhau), Id_NV_KhoiTao = currentUserId, Ngay_KhoiTao = DateTime.Now, Ma_NguoiDung = "U" + DateTime.Now.ToString("yyyyMMddHHmmss"), Tinh_Trang = 1, Quan_Tri = 0, Id_VaiTro = 3, Ngay_CapNhat = DateTime.Now }; await this.accountRepository.AddAsync(account); await this.PublishCreatingAccount(account); return(account); }
public void OnInitialized(IContainerProvider containerProvider) { if (AccountVM.TestService()) { IRegionManager regionManager = containerProvider.Resolve <IRegionManager>(); // IRegion region = regionManager.Regions["WorkspaceRegion"]; // region.RemoveAll(); //We get from the container an instance of AccountGrid. AccountGrid view = containerProvider.Resolve <AccountGrid>(); //We get from the region manager our target region. IRegion region = regionManager.Regions["WorkspaceRegion"]; //We inject the view into the region. region.Add(view); // regionManager.RegisterViewWithRegion("WorkspaceRegion", typeof(AccountGrid)); } else { throw new ModularityException(); } }
public IActionResult Transfer(TransferVM model) { var repo = BankRepository.Instance(); if (ModelState.IsValid) { try { var fromAccount = repo.GetAccount(model.fromAccountNumber); var recievingAccount = repo.GetAccount(model.recievingAccountNumber); repo.Transfer(fromAccount, recievingAccount, model.Amount); var transferVM = new TransferVM(); transferVM.FromAccount = AccountVM.Create(fromAccount); transferVM.RecievingAccount = AccountVM.Create(recievingAccount); return(View("TransferSuccess", transferVM)); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } return(View("Index", model)); }
public async Task <IActionResult> ResetPassword(AccountVM reset) { AppUser user = await _userManager.FindByEmailAsync(reset.AppUser.Email); AccountVM model = new AccountVM { AppUser = user }; if (user == null) { ModelState.AddModelError("", "Email is incorrect"); return(View(model)); } IdentityResult result = await _userManager.ResetPasswordAsync(user, reset.Token, reset.Password); if (!result.Succeeded) { return(BadRequest()); } await _signInManager.PasswordSignInAsync(user, reset.Password, false, true); return(RedirectToAction("Index", "Home")); }
public async Task <IActionResult> Tagged(string username) { if (string.IsNullOrEmpty(username)) { return(NotFound()); } User user = await _userManager.FindByNameAsync(username); User currentUser = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound()); } List <PostTaggedUser> postTagged = _db.PostTaggedUsers.Where(p => p.UserId == user.Id).ToList(); List <Post> posts = new List <Post>(); List <User> friends = new List <User>(); foreach (Friend item in _db.Friends.Include(f => f.FriendTo).Include(f => f.FriendFrom).Where(f => f.Accepted && !f.FriendFrom.Deleted && !f.FriendTo.Deleted)) { if (item.FriendFrom == user) { friends.Add(item.FriendTo); } else if (item.FriendTo == user) { friends.Add(item.FriendFrom); } } bool isFriend = false; foreach (User f in friends) { if (currentUser == f) { isFriend = true; } } if ((await _userManager.GetRolesAsync(currentUser))[0] == "Admin" || (await _userManager.GetRolesAsync(currentUser))[0] == "Moderator") { isFriend = true; } if (user.Private && !isFriend && user != currentUser) { return(NotFound()); } foreach (PostTaggedUser item in postTagged) { posts.Add(_db.Posts.Include(p => p.User).Include(p => p.PostTaggedUsers).Include(p => p.PostLikes).Include(p => p.PostImages).Include(p => p.SavedPosts).Include(p => p.Comments).FirstOrDefault(p => p.Id == item.PostId)); } AccountVM model = new AccountVM() { User = user, Posts = posts.OrderByDescending(p => p.Date), PostTaggedUsers = _db.PostTaggedUsers.Include(p => p.User), CurrentUserRole = (await _userManager.GetRolesAsync(currentUser))[0] }; return(View(model)); }
public AccountVM CheckCookie() { AccountVM account = null; HttpCookie cookie = null; string username = string.Empty; string password = string.Empty; if (HttpContext.Request.Cookies["Cookie"] != null) { cookie = Request.Cookies["Cookie"]; } username = cookie["username"]; password = cookie["password"]; if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { account = new AccountVM { UserName = username, Password = password } } ; return(account); }
public async Task <IActionResult> Saved() { User user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound()); } List <Post> posts = new List <Post>(); List <SavedPost> savedPosts = _db.SavedPosts.Where(p => p.UserId == user.Id).ToList(); foreach (SavedPost item in savedPosts) { posts.Add(_db.Posts.Include(p => p.User).Include(p => p.PostTaggedUsers).Include(p => p.PostLikes).Include(p => p.PostImages).Include(p => p.SavedPosts).Include(p => p.Comments).FirstOrDefault(p => p.Id == item.PostId)); } AccountVM model = new AccountVM() { User = user, Posts = posts.OrderByDescending(p => p.Date), PostTaggedUsers = _db.PostTaggedUsers.Include(p => p.User), CurrentUserRole = (await _userManager.GetRolesAsync(user))[0] }; return(View(model)); }
public ActionResult Me(string tab) { var account = new AccountVM { Tab = tab ?? "feeds", User = CurrentUser }; switch (account.Tab) { case "feeds": account.Feeds = FeedService.GetSubmitedFeeds(CurrentUser.Id); break; case "tagged": account.TaggedArticles = FeedService.GetTaggedArticles(CurrentUser.Id); account.UserTags = FeedService.GetTaggedArticlesStatuses(CurrentUser.Id); account.Tags = FeedService.GetTags(account.UserTags.Select(t => t.TagId).ToList()); break; case "ignored": account.IgnoredArticles = FeedService.GetIgnoredArticles(CurrentUser.Id); break; } return(View(account)); }
public async Task <IActionResult> Login(AccountVM vm) { var user = await _userManager.FindByEmailAsync(vm.Email); if (user != null && await _userManager.CheckPasswordAsync(user, vm.Password)) { // Getting the user role var role = await _userManager.GetRolesAsync(user); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAuthenticationOptions.SecurityKey)); var tokenDescriptor = new SecurityTokenDescriptor(); tokenDescriptor.Subject = new ClaimsIdentity(new Claim[] { //new Claim("UserId", user.Id), new Claim(_identityOptions.ClaimsIdentity.UserIdClaimType, user.Id), new Claim(_identityOptions.ClaimsIdentity.RoleClaimType, role.FirstOrDefault() ?? "User") }); tokenDescriptor.Expires = DateTime.UtcNow.AddHours(_jwtAuthenticationOptions.TokenExpiration); tokenDescriptor.SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(securityToken); return(AppOkRequest("", token)); } else { return(AppFailedRequest("Login credientials are not correct.")); } }
public ActionResult CashBookReport(FormCollection frm) { AccountVM viewModel = new AccountVM(); if (frm["FromDate"] != null && !string.IsNullOrEmpty(frm["FromDate"])) { viewModel.FromDate = Convert.ToDateTime(frm["FromDate"]); } if (frm["ToDate"] != null && !string.IsNullOrEmpty(frm["ToDate"])) { viewModel.ToDate = Convert.ToDateTime(frm["ToDate"]); } if (ModelState.IsValid) { PresentationLayer.Helpers.SessionHelper.ReportIndex = 7; PresentationLayer.Helpers.SessionHelper.fromDate = viewModel.FromDate; PresentationLayer.Helpers.SessionHelper.toDate = viewModel.ToDate; return(Redirect(@"~\Report.aspx")); } else { return(View(viewModel)); } }
public async Task <IActionResult> BlockAccount(int id, AccountVM account) { if (id != account.Id) { return(BadRequest()); } var accountInDB = _context.Accounts.Where(a => a.Id == id && a.IsDeleted == false).FirstOrDefault(); accountInDB.LockoutEnabled = !account.IsActive; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AccountExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> Details(int?id) { if (id == null) { return(NotFound()); } var account = await _repo.Get(id); if (account == null) { return(NotFound()); } AccountVM bavm = new AccountVM { Account = account, Transactions = (await _repo.GetTransactions()) .Where(acct => acct.AccountID == id) .Reverse() .Take(10) .ToList(), AccountUserId = account.AppUserId }; return(View(bavm)); }
public ActionResult AddAccount(AccountVM model) { if (!checkSession()) { return(RedirectToAction("Index", "Index")); } Random random = new Random(); int newAccNo1 = random.Next(1000, 9999); int newAccNo2 = random.Next(10, 99); int newAccNo3 = random.Next(10000, 99999); if (ModelState.IsValid) { Account account = new Account() { AccountNo = "" + newAccNo1 + newAccNo2 + newAccNo3, Balance = 5000, OwnerBirthNo = model.OwnerBirthNo, Type = model.Type }; _adminService.addAccount(account); return(Json(new { success = true })); } // else return(PartialView("_CreateAccountPartial", model)); }
private void LoadSettings() { Windows.UI.Popups.MessageDialog md = new Windows.UI.Popups.MessageDialog("Could not load settings"); string connStr = "Server=den1.mysql3.gear.host;Database=plutos;Uid=plutos;Pwd=Ez7L!3P93e_S;SslMode=None"; MySqlConnection conn = new MySqlConnection(connStr); conn.Open(); List <string> accountNames = AccountVM.GetNames(conn); CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (accountNames != null) { Income_Account_ComboBox.ItemsSource = accountNames; } List <string> customerNames = Customer.GetNames(conn); if (customerNames != null) { customerBox.ItemsSource = customerNames; } conn.Close(); incomeTypeCB.ItemsSource = new List <string> { "Sale", "Invoice", "Subscription" }; }); }
public AccountVM Authenticate(string username, string password) { var accountInDb = _db.Accounts.FirstOrDefault(a => a.Email == username.ToLower()); AccountVM accountVM = null; var hasher = new PasswordHasher(); if (accountInDb != null) { // hash password. var correctPassword = hasher.VerifyHashedPassword(accountInDb.Password, password); if (correctPassword == Microsoft.AspNet.Identity.PasswordVerificationResult.Success || correctPassword == Microsoft.AspNet.Identity.PasswordVerificationResult.SuccessRehashNeeded) { accountVM = _mapper.Map <AccountVM>(accountInDb); // find permissions accountVM.Permissions = _db.AccountPermissions .Where(ap => ap.AccountId == accountVM.AccountId) .Select(s => new PermissionVM { PermissionId = s.PermissionId, Name = s.Permission.Name, Description = s.Permission.Description }).ToList(); var xx = 1; } } else { //login failed, no account exists } return(accountVM); }
public ActionResult Edit([Bind(Prefix = "Account")] Account account, [Bind(Include = "Users")] List <Guid> users) { if (ModelState.IsValid) { Account dbAccount = UOW.Accounts.GetById(account.Id); if (dbAccount != null) { dbAccount.Name = account.Name; dbAccount.ClientSinceDate = account.ClientSinceDate; dbAccount.IndustryType = account.IndustryType; dbAccount.IsActive = account.IsActive; if (users != null) { dbAccount.SkyberryUsers = UOW.SkyberryUsers.GetSetByIds(users); } UOW.Commit(); account = dbAccount; } else { return(HttpNotFound()); } } AccountVM vm = new AccountVM { Account = account, Users = UOW.SkyberryUsers.GetAll() }; return(View(vm)); }
// GET: Account public ActionResult Index() { AccountVM userBL = new AccountVM(); List <Account> list = userBL.Get_list(); return(View(list)); }
public ActionResult Create([Bind(Prefix = "Account")] Account account, [Bind(Include = "Users")] List <Guid> users) { if (ModelState.IsValid) { Account newAccount = new Account(); newAccount.Id = Guid.NewGuid(); newAccount.Name = account.Name; newAccount.ClientSinceDate = account.ClientSinceDate; newAccount.CreatedDate = DateTime.Now; newAccount.IndustryType = account.IndustryType; newAccount.IsActive = account.IsActive; Counter dbCounter = UOW.Counters.GetByName("Account_Number"); int nextNumber = dbCounter.CurrentNumber = dbCounter.CurrentNumber + 1; newAccount.Number = nextNumber.ToString(); if (users != null) { newAccount.SkyberryUsers = UOW.SkyberryUsers.GetSetByIds(users); } UOW.Accounts.Add(newAccount); UOW.Commit(); account = newAccount; } AccountVM vm = new AccountVM { Account = account, Users = UOW.SkyberryUsers.GetAll() }; return(View("Edit", vm)); }
public ActionResult Delete(int id) //dodać w widoku edit { AccountVM vm = new AccountVM(); vm.Delete(id); return(RedirectToAction("Index")); }
public async Task <ActionResult> Login(AccountVM model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: logger.Info("Logowanie udane | " + model.Email); return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("loginerror", "Nieudana próba logowania."); logger.Info("Logowanie nieudane | " + model.Email); return(View(model)); } }