Example #1
0
        public async Task <ActionResult> RegisterAccount([FromForm] AccountFormDataCM account)
        {
            if (string.IsNullOrEmpty(account.Email))
            {
                return(BadRequest());
            }

            Account accountCreated = _accountService.GetByEmail(account.Email);

            if (accountCreated != null)
            {
                return(BadRequest("Email exists"));
            }

            accountCreated = _mapper.Map <Account>(account);
            List <Image> listImgAvatar       = new List <Image>();
            List <Image> listImgCertificates = new List <Image>();

            if (account.ImagesAvatar != null)
            {
                foreach (IFormFile file in account.ImagesAvatar)
                {
                    string avatar = await _uploadFileService.UploadFile("token", file, "customer", "avatar");

                    Image image = new Image();
                    image.ImageUrl    = avatar;
                    image.Description = "customer-avatar";
                    listImgAvatar.Add(image);
                }
            }
            if (account.ImagesCertificates != null)
            {
                foreach (IFormFile file in account.ImagesAvatar)
                {
                    string certificate = await _uploadFileService.UploadFile("token", file, "customer", "certificates");

                    Image image = new Image();
                    image.ImageUrl    = certificate;
                    image.Description = "customer-certificates";
                    listImgAvatar.Add(image);
                }
            }
            listImgAvatar.AddRange(listImgCertificates);
            accountCreated.Gallery = new Gallery()
            {
                Images      = listImgAvatar,
                Description = accountCreated.DisplayName + "_Info",
                Name        = "Ảnh cá nhân"
            };

            accountCreated.Status         = "NEW";
            accountCreated.Role           = "WORKER";
            accountCreated.IsBeautyArtist = true;

            await _accountService.AddAsync(accountCreated);

            await _accountService.Save();

            return(Ok("Đăng ký tài khoản thành công"));
        }
Example #2
0
        public async Task <ActionResult> Register(RegisterDto registerModel)
        {
            var user = _mapper.Map <User>(registerModel);
            await _accountService.AddAsync(user);

            return(RedirectToAction("Login", "Account"));
        }
Example #3
0
        public async Task <Account> CreatePersonalAccountAsync(AccountAddModel personalAccount)
        {
            if (personalAccount == null)
            {
                throw new ArgumentNullException(nameof(personalAccount));
            }

            _dataProtectionService.Validate();

            var account = new Account()
            {
                Id                      = Guid.NewGuid().ToString(),
                Name                    = personalAccount.Name,
                Urls                    = Validation.VerifyUrls(personalAccount.Urls),
                Apps                    = personalAccount.Apps,
                Login                   = await ValidateAccountNameAndLoginAsync(personalAccount.EmployeeId, personalAccount.Name, personalAccount.GetLogin()),
                AccountType             = AccountType.Personal,
                LoginType               = personalAccount.LoginType,
                CreatedAt               = DateTime.UtcNow,
                PasswordUpdatedAt       = DateTime.UtcNow,
                OtpUpdatedAt            = Validation.VerifyOtpSecret(personalAccount.OtpSecret) != null ? new DateTime?(DateTime.UtcNow) : null,
                Password                = _dataProtectionService.Encrypt(personalAccount.Password),
                OtpSecret               = _dataProtectionService.Encrypt(personalAccount.OtpSecret),
                UpdateInActiveDirectory = personalAccount.UpdateInActiveDirectory,
                EmployeeId              = personalAccount.EmployeeId,
                StorageId               = new StorageId().Data
            };

            Employee employee = await GetEmployeeByIdAsync(personalAccount.EmployeeId);

            List <HardwareVaultTask> tasks = new List <HardwareVaultTask>();

            foreach (var vault in employee.HardwareVaults)
            {
                tasks.Add(_hardwareVaultTaskService.GetAccountCreateTask(vault.Id, account.Id, account.Password, account.OtpSecret));
            }

            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await _accountService.AddAsync(account);
                await SetAsPrimaryAccountIfEmptyAsync(account.EmployeeId, account.Id);

                if (tasks.Count > 0)
                {
                    await _hardwareVaultTaskService.AddRangeTasksAsync(tasks);

                    await _hardwareVaultService.UpdateNeedSyncAsync(employee.HardwareVaults, true);
                }

                transactionScope.Complete();
            }

            return(account);
        }
Example #4
0
        public void Add()
        {
            var username   = _randomMaker.NewNumber();
            var duplicated = _accountService.FirstAsync(new AccountGetFirstSchema {
                Username = username
            }).GetAwaiter().GetResult();

            while (duplicated != null)
            {
                username   = _randomMaker.NewNumber();
                duplicated = _accountService.FirstAsync(new AccountGetFirstSchema {
                    Username = username
                }).GetAwaiter().GetResult();
            }

            var account = new AccountAddSchema {
                Password   = _cryptograph.RNG("1234"),
                ProviderId = AccountProvider.Clipboardy.ToInt(),
                Username   = username,
                CreatedAt  = DateTime.Now,
                StatusId   = Status.Active.ToInt()
            };
            var accountId = _accountService.AddAsync(account).GetAwaiter().GetResult();

            Assert.IsTrue(account.StatusCode == 200);
            Assert.IsTrue(accountId > 0);
        }
        public async Task <ActionResult <AccountFullResponseDTO> > PostAccount(AccountPostDTO accountPostDTO)
        {
            AccountPostDtoValidator validator = new AccountPostDtoValidator();
            ValidationResult        results   = validator.Validate(accountPostDTO);

            if (!results.IsValid)
            {
                return(BadRequest(results.ToString()));
            }

            Account accountResponse;

            try
            {
                accountResponse = await _accountService.AddAsync(mapper.Map <Account>(accountPostDTO), accountPostDTO.Password, accountPostDTO.RoleId.ToString());
            }
            catch (AutoMapperMappingException ex)
            {
                return(BadRequest(ex.ToString()));
            }
            catch (BadRequestException ex)
            {
                return(BadRequest(ex.ErrorMessage));
            }
            catch (ConflictException ex)
            {
                return(Conflict(ex.ErrorMessage));
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            return(CreatedAtAction("GetRole", new { id = accountResponse.Id }, mapper.Map <AccountFullResponseDTO>(accountResponse)));
        }
        public async Task <IActionResult> SignUp([FromBody] RegisterView model)
        {
            await _service.AddAsync(model);

            var jwt = _service.GetToken(model);
            var str = _service.GetTokenString(jwt);

            return(Ok(str));
        }
Example #7
0
        public async Task <IActionResult> Register(RegisterInput model)
        {
            var adminmodel = _mapper.Map <AdminInfo>(model);
            var optresult  = await _accountService.AddAsync(adminmodel);

            var result = ApiResultBase.GetInstance(optresult ? ResultCode.Access : ResultCode.Fail, result: optresult);

            return(Ok(result));
        }
Example #8
0
        public async Task <IActionResult> AddAsync(AccountDto account)
        {
            if (account.UserId != GetUser() && GetRole() == Roles.User)
            {
                return(Forbid());
            }
            var result = await _accountService.AddAsync(account);

            return(result != null ? (IActionResult)Ok(result) : Conflict());
        }
Example #9
0
        public async Task <IActionResult> AddAccount([FromBody] AccountDTO account)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest() as IActionResult);
            }
            var info = await service.AddAsync(account);

            return(info ? Ok() : StatusCode(400));
        }
Example #10
0
 public async Task <ServiceResult> SubmitAsync([FromBody] AccountInput input)
 {
     if (!string.IsNullOrWhiteSpace(input.Id))
     {
         return(await _accountService.UpdateAsync(input.Id, input));
     }
     else
     {
         return(await _accountService.AddAsync(input));
     }
 }
        public async Task <ActionResult> CreateAccount([FromBody] AccountCM accountCM)
        {
            Account account = _mapper.Map <Account>(accountCM);

            try
            {
                account.IsBeautyArtist = false;
                await _accountService.AddAsync(account);

                await _accountService.Save();
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            Account createAccount = await _accountService.AddAsync(account);

            await _accountService.Save();

            return(CreatedAtAction("GetAccountById", createAccount));
        }
        public async Task <Account> Handle(CreateAccount request, CancellationToken cancellationToken = default)
        {
            var accountToAdd = new Account
            {
                UserId      = request.UserId,
                AccountType = request.AccountType,
                DateCreated = _dateTimeProvider.UtcNow
            };
            var newAccount = await _accountService.AddAsync(request.CorrelationId, accountToAdd, cancellationToken);

            return(newAccount);
        }
        protected override async Task <GetAccountDto> ExecuteAsync(CreateAccountCommand request, CancellationToken ct)
        {
            CreateAccountDto createAccountDto = _mapper.Map <CreateAccountDto>(request);

            GetAccountDto accountDto = await _accountService.AddAsync(createAccountDto, ct);

            AccountCreatedMessage accountCreatedMessage = _mapper.Map <AccountCreatedMessage>(accountDto);

            await _serviceBusClient.PublishAccountCreatedAsync(accountCreatedMessage);

            return(accountDto);
        }
Example #14
0
        [AllowAnonymous] //FromForm  -form -data x-wwww-form-urlencoded  [FromBody]:只能传递一个参数
        public async Task <IActionResult> AddUser(AdminUsersDto adminUsers)
        {
            var fileName = "";

            IFormFile formFile = adminUsers.HeadPortrait;

            if (formFile != null)
            {
                fileName = ContentDispositionHeaderValue.Parse(formFile.ContentDisposition).FileName.Trim('"');
                string filePath = _environment.WebRootPath + $@"\Files\Pictures\";
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string suffix = fileName.Split('.')[1];
                fileName = Guid.NewGuid() + "." + suffix;
                string fileFullName = filePath + fileName;
                using (FileStream fs = System.IO.File.Create(fileFullName))
                {
                    await formFile.CopyToAsync(fs);

                    fs.Flush();
                }
            }

            string imgpath    = $"/src/Pictures/{fileName}";
            var    adminmodel = _mapper.Map <AdminUsers>(adminUsers);

            adminmodel.HeadPortraitUrl = imgpath;

            var optresult = await _accountService.AddAsync(adminmodel);

            _cacheHelper.SetCache(adminmodel.Id.ToString(), adminmodel, DateTimeOffset.Now.AddHours(1));

            //var product = new ProductInfoDto()
            //{
            //    ID = 1,
            //    //BusinessID = 1,
            //    ClassID = 1,
            //    ProductID = 1
            //};
            //var model = _mapper.Map<ProductInfoToClass>(product);
            var result = ApiResultBase.GetInstance(ResultCode.Access, result: adminmodel);

            return(Ok(result));

            //_accountService.AddAsync()
        }
        public async Task <IActionResult> Add(AddUserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var(_, errors) = await accountService.AddAsync(model).ConfigureAwait(false);

            if (errors != Error.NoError)
            {
                return(this.ErrorView(errors));
            }

            return(RedirectToAction("Index"));
        }
Example #16
0
        public async Task <AccountModel> CreateAccountAsync(string username, string password)
        {
            byte[] passwordHash;
            byte[] passwordSalt;

            CreatePassword(password, out passwordHash, out passwordSalt);

            var account = new AccountModel
            {
                UserName     = username,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                ChangeDate   = DateTime.Now
            };

            return(await _accountService.AddAsync(account));
        }
        public async Task <ActionResult> PostAsync([FromBody] Accounts item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            try
            {
                var exist = await service.GetAsync(x => x.accountno == item.accountno);

                if (exist != null)
                {
                    return(Conflict(new Response()
                    {
                        Status = false, Description = "Duplicate record"
                    }));
                }
                var result = await service.AddAsync(item);

                if (result)
                {
                    var newitem = await service.GetAsync(x => x.accountno == item.accountno);

                    return(StatusCode(201, newitem));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(StatusCode(500, new Response()
                {
                    Status = false, Description = "System error"
                }));
            }
        }
Example #18
0
        protected override async Task <GetAccountDto> ExecuteAsync(CreateAccountCommand request, CancellationToken ct)
        {
            AddAccountDto accountDto = _mapper.Map <AddAccountDto>(request);

            return(await _accountService.AddAsync(accountDto, ct));
        }