Ejemplo n.º 1
0
        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.")); 
        }
Ejemplo n.º 3
0
        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)));
        }
Ejemplo n.º 5
0
        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());
            }
        }
Ejemplo n.º 6
0
        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));
        }
Ejemplo n.º 7
0
 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);
 }
Ejemplo n.º 8
0
        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));
        }
Ejemplo n.º 9
0
        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));
        }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        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));
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
0
        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));
        }
Ejemplo n.º 15
0
        /// <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,
            });
        }
Ejemplo n.º 16
0
        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");
        }
Ejemplo n.º 17
0
        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());
        }
Ejemplo n.º 18
0
        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());
        }
Ejemplo n.º 19
0
        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));
        }
Ejemplo n.º 20
0
        /// <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;
                }
            }
        }
Ejemplo n.º 21
0
        public async Task <IActionResult> CreateAccount([FromBody] AccountCreateDto createDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            try
            {
                await _accountsService.CreateAccountAsync(createDto);

                return(Ok());
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Ejemplo n.º 22
0
        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));
        }
Ejemplo n.º 24
0
        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));
        }
Ejemplo n.º 25
0
        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);
        }
Ejemplo n.º 26
0
        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)));
        }
Ejemplo n.º 27
0
        /// <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;
                }
            }
        }
Ejemplo n.º 28
0
        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"));
            }
        }
Ejemplo n.º 30
0
        /// <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));
        }