public ActionResult Validate(AccountVm aVm) { var view = "pin"; object vm; try { var acc = Dal.Accounts.FirstOrDefault(x => x.cardNumber == aVm.Account.cardNumber); if (acc != null) { vm = aVm; } else { throw new Exception(Error.Invalid_Card_Number.ToString()); } } catch (Exception ex) { if (ex.Message == Error.Invalid_Card_Number.ToString()) { ErrorVm.ErrorId = (int)Error.Invalid_Card_Number; ErrorVm.ErrorMessage = Error.Invalid_Card_Number.ToString().Replace("_", " "); } else { UnControlledException(aVm.Account.cardNumber, ex); } view = "Error"; vm = ErrorVm; } return(View(view, vm)); }
public async void GetAccountByPhone_ExpectedFound() { //var json = new WebClient().DownloadString($"{EndPoints.BaseUrl}{EndPoints.Contacts}/{TestData4Contact.Id}"); var httpClient = new HttpClient(); HttpResponseMessage httpResponsePhone = await httpClient.GetAsync($"{EndPoints.BaseUrl}{EndPoints.Contacts}/byphone/{TestData4.AccountPhone}"); var strJson = await httpResponsePhone.Content.ReadAsStringAsync(); ContactVm contacvm = JsonConvert.DeserializeObject <ContactVm>(strJson); Assert.IsType <ContactVm>(contacvm); Assert.NotNull(contacvm.AccountId); Assert.IsType <Int64>(Int64.Parse(contacvm.NationalId)); var httpClient2 = new HttpClient(); var json2 = await httpClient2.GetAsync($"{EndPoints.BaseUrl}{EndPoints.Accounts}/{contacvm.AccountId}"); var strJson2 = await json2.Content.ReadAsStringAsync(); AccountVm accountVm = JsonConvert.DeserializeObject <AccountVm>(strJson2); Assert.IsType <AccountVm>(accountVm); Assert.NotNull(accountVm); }
public ActionResult Login(string returnUrl) { try { // We do not want to use any existing identity information EnsureLoggedOut(); if (TempData["Success"] != null) { TempData["Success"] = TempData["Success"]; } if (TempData["Error"] != null) { TempData["Error"] = TempData["Error"]; } var accountVm = new AccountVm { ReturnUrl = returnUrl }; return(View(accountVm)); } catch (Exception e) { TempData["Error"] = e.Message; throw; } }
public async Task<JsonResult> GetUserList([FromForm] AccountVm model) { var result = new SearchResult<List<UserSM>>(); var respositoryResult = await AccountRespository.GetUserList(model, UserToken); result.Status = ResultConfig.Ok; result.Info = ResultConfig.SuccessfulMessage; result.Rows = respositoryResult.Item2; result.Total = respositoryResult.Item1; return Json(result); }
public async Task <ActionResult> Register(AccountVm data) { try { using (_entities) { //Confirm that model is valid if (!ModelState.IsValid) { return(RedirectToAction("Login", "Home", data)); } //Initialise object of user master table var userMaster = _entities.UserMasters.FirstOrDefault(s => s.Email == data.Email.Trim()); //Check that details is not null if (userMaster != null) { TempData["Error"] = "This email already registered with us."; } else { //Create HASH & SALT var salt = Utilities.GenerateSalt(32); var hash = Utilities.GenerateHash(data.Password.Trim(), data.Email.Trim(), salt); //Create instance of table userMaster = new UserMaster(); userMaster.CopyProperties(data); userMaster.Hash = hash; userMaster.Salt = salt; userMaster.CreatedDate = DateTime.Now; userMaster.IsActive = true; userMaster.IsTermAccept = true; userMaster.RoleMasterId = (int)EnumList.Roles.Owner; //Todo: Email verification task userMaster.IsEmailVerified = true; _entities.UserMasters.Add(userMaster); await _entities.SaveChangesAsync(); //Create response message TempData["Success"] = "Registration done successfully"; } return(RedirectToAction("Login")); } } catch (Exception e) { TempData["Error"] = e.Message; throw; } }
public async ValueTask <IActionResult> SignUp([FromBody] AccountVm account) { if (account is null) { return(BadRequest("empty body")); } var users = db.Users.Where(u => u.UserName == account.UserName || u.Email == account.Email || u.MobileNumber == account.Mobile); if (users.Any()) { if (users.Any(u => u.UserName == account.UserName)) { ModelState.AddModelError("UserName", "UserName name had taken"); } if (users.Any(u => u.Email == account.Email)) { ModelState.AddModelError("Email", "Email had taken"); } if (users.Any(u => u.MobileNumber == account.Mobile)) { ModelState.AddModelError("Mobile", "Mobile had taken"); } } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = new User { UserName = account.UserName.ToLower(), Email = account.Email.ToLower(), MobileNumber = account.Mobile, PasswordHash = hasher.Hash(account.Password), IsPrivate = account.IsPrivate, IsActive = true, }; await db.AddAsync(users); await db.AddAsync(new Follow { Followed = user, Follower = user, Accepted = true, Time = DateTime.Now, }); db.SaveChanges(); logger.LogInformation($"user {user.UserName} signed up"); return(Ok()); }
public AccountVm GetAccountById(int id) { var account = _accountRepository.GetEntity(id); var accountVm = new AccountVm { Id = account.Account_Pk, Name = account.Name, Description = account.Description }; return(accountVm); }
public async Task <IActionResult> Account() { var user = await _userManager.GetUserAsync(User); var model = new AccountVm() { StreetAddress = user.StreetAddress, MobileNumber = user.PhoneNumber, Postcode = user.Postcode, Suburb = user.Suburb }; return(View(model)); }
private AccountVm GetUserVm() { var accountCount = _userManager.Users.Count(); var registerToday = (from u in _userManager.Users where DateTime.Now.Subtract(u.CreatedDate).Days <= 0 select u ).Count(); var accountVm = new AccountVm { Total = accountCount, RegisterToday = registerToday }; return(accountVm); }
public async void GetAccountById_ExpectedFound() { //var json = new WebClient().DownloadString($"{EndPoints.BaseUrl}{EndPoints.Contacts}/{TestData4Contact.Id}"); var httpClient = new HttpClient(); var json = await httpClient.GetAsync($"{EndPoints.BaseUrl}{EndPoints.Accounts}/{TestData4.AccountId}"); var strJson = await json.Content.ReadAsStringAsync(); AccountVm accountVm = JsonConvert.DeserializeObject <AccountVm>(strJson); Assert.IsType <AccountVm>(accountVm); Assert.NotNull(accountVm); Assert.IsType <Int64>(Int64.Parse(accountVm.NationalId)); }
public async Task <IActionResult> Account(AccountVm model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.GetUserAsync(User); user.StreetAddress = model.StreetAddress; user.Postcode = model.Postcode; user.Suburb = model.Suburb; user.PhoneNumber = model.MobileNumber; _context.SaveChanges(); var merchant = await _organiserService.GetMerchant(user.Id, _appSettings.Pinch.IsLive); if (merchant != null) { var response = await _organiserService.UpdateMerchant(user.Id, _appSettings.Pinch.IsLive, _appSettings.Pinch.MerchantId, _appSettings.Pinch.SecretKey); if (!response.Successful) { ModelState.AddModelError("", string.Join(" - ", response.ErrorMessages.Select(x => x.ErrorMessage))); return(View(model)); } } else { var response = await _organiserService.CreateMerchant(user.Id, _appSettings.Pinch.IsLive, _appSettings.Pinch.MerchantId, _appSettings.Pinch.SecretKey); if (!response.Successful) { ModelState.AddModelError("", string.Join(" - ", response.ErrorMessages.Select(x => x.ErrorMessage))); return(View(model)); } } return(RedirectToAction("Account")); }
public async void GetAccountByPhone_ExpectedStatusCode200() { //var json = new WebClient().DownloadString($"{EndPoints.BaseUrl}{EndPoints.Contacts}/{TestData4Contact.Id}"); var httpClient = new HttpClient(); var json = await httpClient.GetAsync($"{EndPoints.BaseUrl}{EndPoints.Accounts}/byphone/{TestData4.AccountPhone}"); var strJson = await json.Content.ReadAsStringAsync(); AccountVm accountVm = JsonConvert.DeserializeObject <AccountVm>(strJson); if (json.StatusCode == HttpStatusCode.OK) { Assert.True(true); } else { Assert.True(false); } }
public async void AddAccountWithoutDuplicateContactPhoneNumberExpextedGuid() { var httpClient = new HttpClient(); AccountAddVm accountAddVm = GetAccount("full"); //accountAddVm.PrimaryContactMobilePhone = "09126455464"; HttpResponseMessage httpResponsePhone = await httpClient.GetAsync($"{EndPoints.BaseUrl}{EndPoints.Contacts}/byphone/{accountAddVm.PrimaryContactMobilePhone}"); if (httpResponsePhone.StatusCode == HttpStatusCode.NotFound) { var jsonString = JsonConvert.SerializeObject(accountAddVm); var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); HttpResponseMessage httpResponseMessage = await httpClient.PostAsync($"{EndPoints.BaseUrl}{EndPoints.Accounts}", httpContent); var AccountId = await httpResponseMessage.Content.ReadAsStringAsync(); AccountId = AccountId.Substring(1, AccountId.Length - 2); HttpStatusCode httpStatusCode = httpResponseMessage.StatusCode; Assert.Equal(HttpStatusCode.OK, httpStatusCode); var json = await httpClient.GetAsync($"{EndPoints.BaseUrl}{EndPoints.Accounts}/{AccountId}"); var strJson = await json.Content.ReadAsStringAsync(); AccountVm AccountvmByID = JsonConvert.DeserializeObject <AccountVm>(strJson); Assert.IsType <AccountVm>(AccountvmByID); Assert.NotNull(AccountvmByID); Assert.Equal(AccountvmByID.AccountName, accountAddVm.AccountName); } else { throw new ArgumentException(); } }
public async ValueTask <IActionResult> SignIn([FromBody] AccountVm account) { ModelState.Remove(nameof(AccountVm.PasswordConf)); if (!string.IsNullOrEmpty(account?.Email)) { ModelState.Remove(nameof(AccountVm.Email)); } var user = await db.Users.FirstOrDefaultAsync(u => u.UserName == account.UserName || u.Email == account.Email || u.MobileNumber == account.Mobile); if (user is null) { logger.LogInformation("login request for not existing user"); ModelState.AddModelError(nameof(AccountVm.UserName), "User Not Found"); } else { var isPass = user.PasswordHash == hasher.Hash(account.Password); if (!isPass) { logger.LogInformation("login request failed because of UserName or password mismatch"); ModelState.AddModelError(nameof(AccountVm.Password), "UserName or Password mismatch"); } if (!user.IsActive) { ModelState.AddModelError(nameof(AccountVm.UserName), "user is deactivated"); } } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var jwt = await authManager.CreateJwtTokenAsync(user, user.UserName); logger.LogInformation("user signed in"); return(Ok(jwt)); }
public ActionResult Account(AccountVm aVm) { return(View(aVm)); }
public ActionResult Pin(AccountVm account) { //mov.Movements = dal.Movements.ToList().Where(x => x.cardNumber == mov.Movement.cardNumber).ToList(); return(View(account)); }
/// <summary> /// 获取用户列表 /// </summary> /// <param name="model"></param> /// <param name="user"></param> /// <returns></returns> public async Task <Tuple <long, List <UserSM> > > GetUserList(AccountVm model, Token user) { if (model == null) { return(new Tuple <long, List <UserSM> >(0, new List <UserSM>())); } var totalQuery = this.Entity.Where(r => r.IsActive); var listQuery = this.Entity.Where(r => r.IsActive); if (!string.IsNullOrEmpty(model.UserName)) { totalQuery = totalQuery.Where(r => r.UserName.Contains(model.UserName)); listQuery = listQuery.Where(r => r.UserName.Contains(model.UserName)); } if (!string.IsNullOrEmpty(model.Eid)) { totalQuery = totalQuery.Where(r => r.Eid.Contains(model.Eid)); listQuery = listQuery.Where(r => r.Eid.Contains(model.Eid)); } if (model.RoleTid > 0) { totalQuery = totalQuery.Where(r => r.RoleTid.Equals(model.RoleTid)); listQuery = listQuery.Where(r => r.RoleTid.Equals(model.RoleTid)); } var total = totalQuery.CountAsync(); if (!GlobalSetting.GoldList.Contains(user.Eid)) { //超级管理员可以查看所有 //只能查看自己创建角色的所有用户 listQuery = listQuery.Where(r => r.CreateRoleName.Contains("," + user.RoleTid + ",") || r.RoleTid.Equals(user.RoleTid)); } var userList = await (from u in listQuery from role in this.Entitys.SystemRole.Where(r => r.Tid.Equals(u.RoleTid)).DefaultIfEmpty() select new UserSM { Tid = u.Tid, IsActive = u.IsActive, Eid = u.Eid, UserName = u.UserName, LoginIp = u.LoginIp, RoleTid = u.RoleTid, LastLoginTime = u.LastLoginTime, UserAgent = u.UserAgent, DataChangeLastTime = u.DataChangeLastTime, RoleName = role.RoleName, RoleDesc = role.Description, Phone = u.Phone, CreateUser = u.CreateUser }) .DynamicOrderBy(string.IsNullOrEmpty(model.OrderBy) ? "DataChangeLastTime" : model.OrderBy, model.OrderSequence) .Skip((model.PageIndex - 1) * model.PageSize) .Take(model.PageSize) .ToListAsync(); return(new Tuple <long, List <UserSM> >(await total, userList)); }
public ActionResult Login(AccountVm data) { try { using (_entities) { // Ensure we have a valid viewModel to work with if (!ModelState.IsValid) { return(View(data)); } //Initialise object of usermaster table var userMaster = _entities.UserMasters.FirstOrDefault(s => s.Email == data.EmailLogin.Trim()); //Check that details is not null if (userMaster != null) { var oldHashValue = userMaster.Hash; var salt = userMaster.Salt; var isLogin = Utilities.CompareHashValue(data.PasswordLogin.Trim(), userMaster.Email, oldHashValue, salt); if (isLogin) { //Login Success //For Set Authentication in Cookie (Remeber ME Option) SignInRemember(data.Email, data.IsRemember); //Set A Unique ID in session CookieHelper.SetCookie(CookieName.UserMasterId, userMaster.UserMasterId.ToString(), 36); CookieHelper.SetCookie(CookieName.Name, userMaster.Name, 36); CookieHelper.SetCookie(CookieName.RoleMasterId, userMaster.RoleMasterId.ToString(), 36); string profileImage; if (!string.IsNullOrWhiteSpace(userMaster.Profile)) { profileImage = BasicProperty.ProfilePath + userMaster.Profile; } else { profileImage = "/Content/img/userIcon.jpg"; } CookieHelper.SetCookie(CookieName.ProfileImage, profileImage, 36); //Set Menu in session var menu = RoleManagement.GetMenu(userMaster.RoleMasterId); Session["Menu"] = menu; TempData["Success"] = "Welcome to DevTracker"; // If we got this far, something failed, redisplay form // return RedirectToAction("Index", "Dashboard"); return(RedirectToLocal(data.ReturnUrl)); } TempData["Error"] = "Access Denied! You enter wrong credentials!"; } else { TempData["Error"] = "Access Denied! You enter wrong credentials!"; } } return(RedirectToAction("Login")); } catch (Exception e) { TempData["Error"] = e.Message; throw; } }
public async ValueTask <IActionResult> Edit([FromBody] AccountVm account) { if (account is null) { return(BadRequest("empty body")); } var currentUser = await db.Users.FirstOrDefaultAsync(u => u.UserName == User.FindFirstValue(ClaimTypes.NameIdentifier)); var users = db.Users.Where(u => (u.UserName == account.UserName || u.Email == account.Email || u.MobileNumber == account.Mobile) && u != currentUser); if (users.Any()) { if (users.Any(u => u.UserName == account.UserName)) { ModelState.AddModelError("UserName", "UserName name had taken"); } if (users.Any(u => u.Email == account.Email)) { ModelState.AddModelError("Email", "Email had taken"); } if (users.Any(u => u.MobileNumber == account.Mobile)) { ModelState.AddModelError("Mobile", "Mobile had taken"); } } if (!string.IsNullOrEmpty(account.OldPassword)) { if (hasher.Hash(account.OldPassword) != currentUser.PasswordHash) { ModelState.AddModelError("OldPassword", "Old Password mismatch"); } if (ModelState.IsValid) { currentUser.PasswordHash = hasher.Hash(account.Password); } } else { ModelState.Remove(nameof(AccountVm.OldPassword)); ModelState.Remove(nameof(AccountVm.Password)); ModelState.Remove(nameof(AccountVm.PasswordConf)); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } currentUser.Email = account.Email; currentUser.MobileNumber = account.Mobile; currentUser.IsPrivate = account.IsPrivate; db.Update(currentUser); await db.SaveChangesAsync(); return(Ok()); }