public async Task <Guid> RegisterAccountAsync(AccountCreateDto account) { var emailAccount = await GetAccountAccordingToEmailAsync(account.Email); var usernameAccount = await GetAccountAccordingToUsernameAsync(account.Username); if (usernameAccount != null) { throw new ArgumentException("", "Username"); } if (emailAccount != null) { throw new ArgumentException("", "Email"); } var password = CreateHash(account.Password); var newAccount = new AccountDto() { Username = account.Username, Email = account.Email, PasswordHash = password.Item1, PasswordSalt = password.Item2 }; return(Create(newAccount)); }
public async Task<ActionResult<AccountReadDto>> Post(int userid, AccountCreateDto accountCreateDto) { if(!ModelState.IsValid) { return BadRequest(new ApiBadRequestResponse(ModelState)); } var item = await _repository.GetUserByIdAsync(userid); if(item == null) { return NotFound(new ApiResponse(404,"User not found.")); } var itemAcc = await _repository.GetAccountByIdAsync(userid); if(itemAcc != null) { return BadRequest(new ApiResponse(400,"Account already created.")); } if(ValidateUser(item)) { return BadRequest(new ApiResponse(400,$"Account could not be create as saving is less then ${Constant.CREDITLIMIT}")); } var model = _mapper.Map<Account>(accountCreateDto); _repository.CreateAsync<Account>(model); if(await _repository.SaveChangesAsync()) { var accountReadDto = _mapper.Map<AccountReadDto>(model); return Ok(new ApiResponse(201,"Account created sucessfully.")); } return BadRequest(new ApiResponse(400, "Failed to save Account.")); }
public async Task <ActionResult <AccountReadDto> > ValidateAccountAsync(AccountCreateDto accountCreateDto) { var accountModel = _mapper.Map <Taikhoan>(accountCreateDto); var account = await _accountService.ValidateAccountAsync(accountModel); return(Ok(_mapper.Map <AccountReadDto>(account))); }
public ActionResult <AccountReadDto> Create([FromBody] AccountCreateDto accountCreateDto) { var user = _userRepository.Get(accountCreateDto.UserId); if (user == null) { return(BadRequest("User with that id doesn't exist.")); } Account account = _mapper.Map <Account>(accountCreateDto); account.CreatedAt = DateTime.UtcNow; Currency currency = _currencyRepository.Get(account.CurrencyId); if (currency == null) { return(BadRequest("Currency with that id doesn't exist.")); } _accountRepository.Create(account); _logger.Log("Create Account"); return(Ok(_mapper.Map <AccountReadDto>(account))); }
public async Task <ActionResult> Register(AccountCreateDto accountCreateDto) { if (!ModelState.IsValid) { return(View()); } try { var id = await AccountFacade.RegisterAccount(accountCreateDto); var authTicket = new FormsAuthenticationTicket(1, id.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), false, ""); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); HttpContext.Response.Cookies.Add(authCookie); return(RedirectToAction("Create", "Character")); } catch (ArgumentException e) { ModelState.AddModelError(e.ParamName, "Účet s daným menom alebo emailom už existuje!"); return(View()); } catch { return(View()); } }
public async Task <ActionResult <AccountReadDto> > CreateAccountAsync(AccountCreateDto account, byte role) { Taikhoan accountModel = _mapper.Map <Taikhoan>(account); await _accountService.CreateAccountAsync(accountModel, role); AccountReadDto accountDto = _mapper.Map <AccountReadDto>(accountModel); return(CreatedAtRoute(nameof(GetAccountByIdAsync), new { id = accountModel.MaTk }, accountDto)); }
public async Task CreateAccountAsync(AccountCreateDto createDto) { // TODO - Map. (add a mappper) var account = new Account { Name = createDto.Name, Description = createDto.Description, IsIsa = createDto.IsIsa }; await _accountsRepository.InsertAndSaveAsync(account); }
public ActionResult <AccountReadDto> CreateAccount(AccountCreateDto acc) { var accModel = _mapper.Map <Account>(acc); _repository.Add(accModel); _repository.Save(); var readDto = _mapper.Map <AccountReadDto>(accModel); return(CreatedAtRoute(nameof(GetAccountById), new { id = accModel.ID }, readDto)); }
public ActionResult <AccountReadDto> CreateAccount(AccountCreateDto accountCreateDto) { var accountModel = _mapper.Map <Account>(accountCreateDto); _repository.CreateAccount(accountModel); _repository.SaveChanges(); var accountReadDto = _mapper.Map <AccountReadDto>(accountModel); return(CreatedAtRoute(nameof(GetAccountById), new { ID = accountReadDto.ID }, accountReadDto)); }
public void CreateAccount_Empty_Name_UserFriendlyException() { // Arrange var input = new AccountCreateDto { Descriptions = "Descriptions" }; // Assert var ex = Assert.Throws <AbpValidationException>(() => this.accoutService.Create(input).Result); ex.ValidationErrors.Count().ShouldBe <int>(1); }
public async Task CreateAccount_Empty_Description_UserFriendlyException() { // Arrange var input = new AccountCreateDto { AccountName = "Account" }; var ex = Assert.Throws <AbpValidationException>(() => this.accoutService.Create(input).Result); ex.ValidationErrors.Count().ShouldBe <int>(1); }
public async Task <ActionResult> Edit() { var account = await AccountFacade.GetAccountAsync(Guid.Parse(User.Identity.Name)); var accountCreateDto = new AccountCreateDto { Username = account.Username, Email = account.Email, Password = "", Roles = account.Roles }; return(View(accountCreateDto)); }
public async Task RegisterAccount() { AccountCreateDto accountToRegister = new AccountCreateDto { Email = "*****@*****.**", Password = "******", Username = "******", }; var registered = await accountFacade.RegisterAccount(accountToRegister); var result = accountFacade.GetAccountAccordingToEmailAsync(accountToRegister.Email).Result; Assert.AreEqual(result.Id, registered); }
public async Task <ActionResult> Edit(Guid id) { var account = await AccountFacade.GetAccountAsync(id); var accountCreateDto = new AccountCreateDto { Id = id, Username = account.Username, Email = account.Email, Roles = account.Roles, Password = "" }; return(View(accountCreateDto)); }
/// <inheritdoc/> public Account RecreateAccountAndPerson(AccountCreateDto dto) { var now = DateUtil.Now; var personId = Guid.NewGuid(); var personCode = personId.ToString("N").Substring(0, 20); while (_personQueryService.ExistsPersonCode(personCode)) { personCode = Guid.NewGuid().ToString("N").Substring(0, 20); } var account = _accountRepository.Read(new AccountTableEntity { AccountId = dto.AccountId }); account.PersonId = personId; account.LastLoginTime = now; var person = new PersonTableEntity { PersonId = personId, PersonCode = personCode, LoginId = dto.LoginId, Name = dto.Name, Title = string.Empty, Description = string.Empty, Status = PersonStatus.NORMAL.ToString(), SortNo = int.MaxValue, CreateTime = now, UpdateTime = now, }; using (var tran = new TransactionScope()) { _accountRepository.Update(account); _personRepository.Create(person); tran.Complete(); } return(new Account { AccountId = account.AccountId, Person = _personQueryService.GetPerson(personId), Roles = JsonUtil.Deserialize <List <string> >(account.Roles), CreateTime = account.CreateTime, LastLoginTime = account.LastLoginTime, }); }
public void CreateAccount_NewUser_Success() { // Arrange var input = new AccountCreateDto { AccountName = "Account", Descriptions = "Description" }; // Act var result = this.accoutService.Create(input).Result; // Assert result.ShouldBeOfType <AccountDto>().ShouldNotBeNull(); result.AccountName.ShouldBe <string>("Account"); }
public async Task <ActionResult> Edit(AccountCreateDto account) { if (ModelState.IsValidField(nameof(AccountCreateDto.Email)) && ModelState.IsValidField(nameof(AccountCreateDto.Username))) { try { await AccountFacade.EditAccountAsync(account.Id, account); return(RedirectToAction("Index")); } catch { return(View()); } } return(View()); }
public async Task <ActionResult> Edit(AccountCreateDto account) { if (ModelState.IsValidField(nameof(AccountCreateDto.Email)) && ModelState.IsValidField(nameof(AccountCreateDto.Username)) && (ModelState.IsValidField(nameof(AccountCreateDto.Password)) || account.Password.IsNullOrEmpty())) { try { await AccountFacade.EditAccountAsync(Guid.Parse(User.Identity.Name), account); return(RedirectToAction("Index")); } catch { return(View()); } } return(View()); }
public ActionResult <AccountReadDto> CreateAccount(AccountCreateDto accountCreateDto) { var accountModel = _mapper.Map <Account>(accountCreateDto); try { _repository.CreateAccount(accountModel); } catch (ArgumentException e) { return(BadRequest(e.Message)); } _repository.SaveChanges(); var accountReadDto = _mapper.Map <AccountReadDto>(accountModel); return(CreatedAtRoute(nameof(GetAccount), new { Id = accountReadDto.Id }, accountReadDto)); }
/// <summary> /// Performs account registration /// </summary> /// <param name="registrationDto">Account registration details</param> /// <returns>Registered account ID</returns> public async Task <Guid> RegisterAccount(AccountCreateDto registrationDto) { using (var uow = UnitOfWorkProvider.Create()) { try { var id = await _accountService.RegisterAccountAsync(registrationDto); await uow.Commit(); return(id); } catch (ArgumentException) { throw; } } }
public async Task <IActionResult> CreateAccount([FromBody] AccountCreateDto createDto) { if (!ModelState.IsValid) { return(BadRequest()); } try { await _accountsService.CreateAccountAsync(createDto); return(Ok()); } catch (Exception) { return(BadRequest()); } }
public async Task CreateAccount_DuplicateUser_UserFriendlyException() { // Arrange var input = new AccountCreateDto { AccountName = "Account", Descriptions = "Description" }; // Act this.accoutService.Create(input); // Assert var ex = Assert.ThrowsAsync <UserFriendlyException>(async() => await this.accoutService.Create(input)); Assert.True(ex.Result.Message == "Account already exists."); }
public async Task <ActionResult <AccountCreateDto> > CreateAccount(AccountCreateDto accountCreateDto) { string genPassword = KeyGenerator.GetUniqueKey(8); var response = new AccountCreateStatusDto() { success = "true", description = "Your account is opened.", password = genPassword }; // Check if account already exists if (await _repository.AccountExists(accountCreateDto.AccountId)) { response.success = "false"; response.description = "Account with the same name already exists."; response.password = null; return(Conflict(response)); } var acc = new Account { UserName = accountCreateDto.AccountId, Password = SecurePasswordHasher.Hash(genPassword) }; try { await _repository.CreateAccount(acc); await _repository.SaveChanges(); } catch (System.Exception) { // Other unexpected server errors response.success = "false"; response.description = "Unexpected server error has occured."; response.password = null; return(StatusCode(500, response)); } return(Ok(response)); }
public ActionResult <AccountReadDto> CreateAccount([FromBody] AccountCreateDto accountCreateDto) { var accountModel = _mapper.Map <Accounts>(accountCreateDto); accountModel.ApiKey = KeyGenerator.GetUniqueKey(128); accountModel.CreateDate = DateTime.Now; while (!_repository.ValidateNewKey(accountModel.ApiKey)) { accountModel.ApiKey = KeyGenerator.GetUniqueKey(128); } _repository.CreateAccount(accountModel); _repository.SaveChanges(); var accountReadDto = _mapper.Map <AccountReadDto>(accountModel); return(CreatedAtAction(nameof(CreateAccount), accountReadDto)); }
public async Task RemoveAccount() { AccountCreateDto accountToRegister = new AccountCreateDto { Email = "*****@*****.**", Password = "******", Username = "******", }; var registered = await accountFacade.RegisterAccount(accountToRegister); var afterReg = await accountFacade.GetAccountAccordingToEmailAsync(accountToRegister.Email); var result = await accountFacade.RemoveAccountAsync(registered); var res = await accountFacade.GetAccountAccordingToEmailAsync(accountToRegister.Email); Assert.AreEqual(result, true); Assert.AreEqual(afterReg.Username, accountToRegister.Username); Assert.AreEqual(res, null); }
public ActionResult <AccountDto> AddAccount(ApiVersion version, [FromBody] AccountCreateDto accountCreateDto) { if (accountCreateDto == null) { return(BadRequest()); } AccountEntity toAdd = _mapper.Map <AccountEntity>(accountCreateDto); _accountRepository.Add(toAdd); if (!_accountRepository.Save()) { throw new Exception("Creating a accountitem failed on save."); } AccountEntity newAccountItem = _accountRepository.GetSingle(toAdd.Id); return(CreatedAtRoute(nameof(GetSingleAccount), new { version = version.ToString(), id = newAccountItem.Id }, _mapper.Map <AccountDto>(newAccountItem))); }
/// <summary> /// Change username of given acc id /// </summary> /// <param name="id"></param> /// <param name="username"></param> public async Task EditAccountAsync(Guid id, AccountCreateDto updatedAccount) { using (var uow = UnitOfWorkProvider.Create()) { try { var acc = await _accountService.GetAsync(id); acc.Username = updatedAccount.Username; acc.Email = updatedAccount.Email; acc.Roles = updatedAccount.Roles; await _accountService.UpdateAccount(acc, updatedAccount.Password); await uow.Commit(); } catch (NullReferenceException) { throw; } } }
public IActionResult AddAccount(int customerId, [FromBody] AccountCreateDto accountCreateDto) { Customer customer = NGContext.Customers.Include(c => c.Accounts).FirstOrDefault(c => c.Id == customerId); if (customer == null) { return(NotFound()); } if (accountCreateDto == null) { return(BadRequest()); } Account account = AutoMapper.Mapper.Map <Account>(accountCreateDto); account.CustomerId = customerId; NGContext.Accounts.Add(account); NGContext.SaveChanges(); return(GetCustomer(customerId)); }
public IActionResult CreateAccount([FromBody] AccountCreateDto accountCreateDto) { try { if (accountCreateDto == null) { return(BadRequest("Account is null")); } if (!ModelState.IsValid) { return(BadRequest("Invalid account")); } var account = _mapper.Map <Account>(accountCreateDto); _repository.Account.CreateAccount(account); _repository.Commit(); var accountViewModel = _mapper.Map <AccountViewModel>(account); return(CreatedAtRoute("GetAccount", new { id = account.Id }, accountViewModel)); } catch (Exception) { return(StatusCode(500, "Internal Server Error")); } }
/// <summary> /// ログインページ。 /// </summary> /// <param name="clientId">クライアントID</param> /// <param name="redirectUri">リダイレクトURI</param> /// <returns><see cref="IActionResult"/></returns> public IActionResult Login(string clientId = "clientapp", string redirectUri = null) { if (string.IsNullOrEmpty(clientId)) { return(View("LoginClientError")); } var application = _authorizetService.GetApplication(clientId); if (application == null || application.Status != ApplicationStatus.NORMAL) { return(View("LoginClientError")); } if (!application.GrantTypes.Contains(GrantTypes.AuthorizationCode)) { return(View("LoginGrantTypeError")); } if (application.RedirectUris.Count == 0 || (redirectUri != null && !application.RedirectUris.Exists(e => e.ToLower() == redirectUri.ToLower()))) { return(View("LoginRedirectError")); } var accountId = Guid.Parse(User.GetObjectId()); var account = _accountService.GetAccount(accountId); var accountCreateDto = new AccountCreateDto { AccountId = accountId, LoginId = User.Identity.Name, Name = User.Claims.ToList().Find(e => e.Type == "name").Value, Roles = new List <string>(), }; if (_accountService.IsFirstAccount()) { accountCreateDto.Roles.Add(Roles.Owner); accountCreateDto.Roles.Add(Roles.User); } else { accountCreateDto.Roles.Add(Roles.User); } if (account != null && account.Person != null) { _accountService.UpdateLastLoginTime(accountId); } else if (account != null && account.Person == null) { _accountService.RecreateAccountAndPerson(accountCreateDto); account = _accountService.GetAccount(accountId); } else { _accountService.CreateAccountAndPerson(accountCreateDto); account = _accountService.GetAccount(accountId); } if (account.Person.Status != PersonStatus.NORMAL) { return(View("LoginPersonError")); } var authorizationCode = _authorizetService.CreateAuthorizationCode(application.ApplicationId, accountId); string url = redirectUri ?? application.RedirectUris[0]; var uriBuilder = new UriBuilder(url); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query["code"] = authorizationCode.CodeId; uriBuilder.Query = query.ToString(); url = uriBuilder.Uri.ToString(); return(Redirect(url)); }