Exemplo n.º 1
0
        public async Task <IActionResult> Signin([FromBody] TokenRequest request)
        {
            var result = new ApiResponse <CredentialResponse>();

            if (!ModelState.IsValid)
            {
                result.AddError(ModelState);
                return(Ok(result));
            }

            var authWithToken = await authneticateService.IsAuthenticatedAsync(request);

            if (authWithToken.IsAuthenticated)
            {
                var credentialReponse = new CredentialResponse
                {
                    Token = authWithToken.Token
                };

                result.AddData(credentialReponse);

                return(Ok(result));
            }

            result.AddError("Invalid Account");

            return(Ok(result));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Retrieve customer by IBAN
        /// </summary>
        /// <param name="iban"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <ApiResponse <CustomerResponse> > GetCustomerByIBANAsync(string iban, CancellationToken cancellationToken = default)
        {
            var responseModel = new ApiResponse <CustomerResponse>();

            var bankAccount = await _bankAccountRepo.FindByIBANAsync(iban);

            if (bankAccount == null)
            {
                responseModel.AddError(ExceptionCreator.CreateNotFoundError(nameof(bankAccount), $"bank Account of IBAN: {iban} not found"));
                return(responseModel);
            }

            var customer = await _customerRepo.FindByIBANAsync(iban);

            if (customer == null)
            {
                responseModel.AddError(ExceptionCreator.CreateNotFoundError(nameof(customer), $"bank Account's holder of IBAN: {iban} not found"));
                return(responseModel);
            }

            var address = await _addressRepo.FindByIdAsync(customer.AddressId);

            responseModel.Data = CreateCustomerResponse(customer, address);

            return(responseModel);
        }
Exemplo n.º 3
0
        public async Task <ActionResult <ApiResponse <SignInApiModel.Response> > > SignIn(SignInApiModel.Request request)
        {
            var response = new ApiResponse <SignInApiModel.Response>();

            var user = await _userManager.FindByEmailAsync(request.Email);

            if (user == null)
            {
                response.AddError(2);
                return(response);
            }

            var result = await _signInManager.PasswordSignInAsync(user, request.Password, false, false);

            if (result.Succeeded == false)
            {
                response.AddError(3);
                return(response);
            }

            response.Data = new SignInApiModel.Response();


            response.Data.AccessToken  = _tokenService.GenerateAccessToken(await user.GetClaimsAsync(_userManager));
            response.Data.RefreshToken = _tokenService.GenerateRefreshToken();

            user.RefreshToken = response.Data.RefreshToken;

            await _userManager.UpdateAsync(user);

            return(Ok(response));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Login user
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <ApiResponse <LoginResponse> > LoginAsync(LoginRequest request, CancellationToken cancellationToken)
        {
            var apiResponse = new ApiResponse <LoginResponse>();

            var user = await _userManager.FindByNameAsync(request.CustomerNo);

            if (user == null)
            {
                apiResponse.AddError(ExceptionCreator.CreateUnauthorizedError("Invalid login credentials"));
                return(apiResponse);
            }

            var result = await _signInManager.PasswordSignInAsync(user, request.Password, false, true);

            if (result.Succeeded)
            {
                apiResponse.Data = new LoginResponse()
                {
                    AccessToken  = _tokenService.GenerateAccessToken(await user.GetClaimsAsync(_userManager)),
                    RefreshToken = _tokenService.GenerateRefreshToken()
                };

                user.RefreshToken = apiResponse.Data.RefreshToken;
                await _userManager.UpdateAsync(user);
            }
            else
            {
                apiResponse.AddError(ExceptionCreator.CreateUnauthorizedError("Invalid login attempt"));
                return(apiResponse);
            }

            return(apiResponse);
        }
Exemplo n.º 5
0
        public async Task <ActionResult <ApiResponse> > ChangePassword(ChangePasswordApiModel.Request requestModel)
        {
            var user = await _userManager.GetUserAsync(User);

            var responseModel = new ApiResponse();

            var correctPassword = await _userManager.CheckPasswordAsync(user, requestModel.OldPassword);

            if (correctPassword == false)
            {
                responseModel.AddError(6);
                return(Ok(responseModel));
            }

            var result = await _userManager.ChangePasswordAsync(user, requestModel.OldPassword, requestModel.NewPassword);

            if (result.Succeeded == false)
            {
                // TODO: Get the errors out
                responseModel.AddError(7);
            }
            else
            {
                user.RefreshToken = null;
                await _userManager.UpdateAsync(user);
            }

            return(Ok(responseModel));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> GetBankAccountFastTransactions([FromRoute] string iban,
                                                                         [FromQuery] int pageNumber          = PagingConstants.DefaultPageNumber,
                                                                         [FromQuery] int pageSize            = PagingConstants.DefaultPageSize,
                                                                         CancellationToken cancellationToken = default)
        {
            var user = await _userManager.GetUserAsync(User);

            var customer = await _customerService.GetCustomerByIBANAsync(iban, cancellationToken);

            var apiResponse = new ApiResponse <FastTransactionListResponse>();

            if (customer == null)
            {
                apiResponse.AddError(ExceptionCreator.CreateNotFoundError(nameof(customer)));

                return(NotFound(apiResponse));
            }

            if (user.Id != customer?.Data?.UserId)
            {
                apiResponse.AddError(ExceptionCreator.CreateBadRequestError(nameof(user), "user is not authorized to complete this operation"));

                return(BadRequest(apiResponse));
            }

            try
            {
                var bankAccount = await _bankAccountService.GetBankAccountByIBANAsync(iban);

                if (bankAccount.Data == null)
                {
                    return(NotFound());
                }

                apiResponse = await _fastTransactionsService.GetBankAccountFastTransactionsAsync(iban, pageNumber, pageSize, cancellationToken);

                if (!apiResponse.Success)
                {
                    return(BadRequest(apiResponse));
                }
                var pagedResponse = new PagedResponse <FastTransactionListResponse>(apiResponse.Data);

                return(Ok(pagedResponse));
            }
            catch (Exception exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, exception.ToString()));
            }
        }
Exemplo n.º 7
0
        public async Task <ActionResult <ApiResponse <GetProfileApiModel.Response> > > GetProfileByUserId(string id)
        {
            var user = await _userManager.FindByIdAsync(id);

            var responseModel = new ApiResponse <GetProfileApiModel.Response>();

            if (user == null)
            {
                responseModel.AddError(5);
                return(Ok(responseModel));
            }

            var profile = await _dataAccess.Profiles.FirstOrDefaultAsync(profile => profile.UserId == user.Id);

            if (profile != null)
            {
                responseModel.Data = new GetProfileApiModel.Response()
                {
                    Id        = profile.Id,
                    Address   = profile.Address,
                    FirstName = profile.FirstName,
                    LastName  = profile.LastName,
                    // TODO: Add the proper rating
                    Rating = 0
                };
            }

            return(Ok(responseModel));
        }
Exemplo n.º 8
0
        public async Task <ApiResponse <bool> > UpdateUserExamStatus(Guid userExamId)
        {
            var result = new ApiResponse <bool>();

            try
            {
                var userExam = await dbContext.UserExams.FirstOrDefaultAsync(e => e.Id == userExamId);

                if (userExam != null)
                {
                    userExam.Status = Models.DB.Exams.enums.Status.Completed;
                    await dbContext.SaveChangesAsync();

                    result.Data = true;
                    result.AddSuccess();
                }
                else
                {
                    result.Data = false;
                    result.AddMessage("Exam not enrolled yet");
                }

                return(await Task.FromResult(result));
            }
            catch (Exception ex)
            {
                result.AddError(ex);
                return(await Task.FromResult(result));
            }
        }
Exemplo n.º 9
0
        public async Task <ApiResponse <List <ExamViewModel> > > Get()
        {
            var result = new ApiResponse <List <ExamViewModel> >();

            try
            {
                result.Data = await dbContext.Exams
                              .Select(e => new ExamViewModel
                {
                    Id          = e.Id,
                    Title       = e.Title,
                    Description = e.Description,
                    Duration    = e.Duration,
                    ImageUrl    = e.ImageUrl,
                    Status      = e.Status,
                    CreatedDate = e.CreatedDate
                })
                              .ToListAsync();

                result.AddSuccess();
                return(await Task.FromResult(result));
            }
            catch (Exception ex)
            {
                result.AddError(ex);
                return(await Task.FromResult(result));
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// forgot password request
        /// </summary>
        /// <param name="email"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <Response> ForgotPasswordAsync(string email, CancellationToken cancellationToken)
        {
            var apiResponse = new ApiResponse <ForgotPasswordResponse>();

            var user = await _userManager.FindByEmailAsync(email);

            if (user == null)
            {
                apiResponse.AddError(ExceptionCreator.CreateNotFoundError(nameof(user), $"user not found"));
                return(apiResponse);
            }

            var token = await _userManager.GeneratePasswordResetTokenAsync(user);

            var encodedToken = Encoding.UTF8.GetBytes(token);
            var validToken   = WebEncoders.Base64UrlEncode(encodedToken);

            string url = $"{_configuration["AppUrl"]}/reset-password?email={email}&token={validToken}";

            await _mailService.SendEmailAsync(email, "Reset Password", "<h1>Follow the instructions to reset your passwod</h1>" +
                                              $"<p>To reset your password <a href='{url}'>Click here</a></p>", cancellationToken);


            return(apiResponse);
        }
        public override async Task Validate(RegisterAccountRequestModel command)
        {
            if (string.IsNullOrEmpty(command.Email))
            {
                ApiResponse.AddError(nameof(RegisterAccountRequestModel.Email), "The email is required.");
            }
            else if (!new EmailAddressAttribute().IsValid(command.Email))
            {
                ApiResponse.AddError(nameof(RegisterAccountRequestModel.Email), "The email address is not valid.");
            }
            else if (await userDataService.EmailIsUsed(command.Email))
            {
                ApiResponse.AddError(nameof(RegisterAccountRequestModel.Email), "Email is already used.");
            }

            if (string.IsNullOrEmpty(command.Password))
            {
                ApiResponse.AddError(nameof(RegisterAccountRequestModel.Password), "The password is required.");
            }
            if (string.IsNullOrEmpty(command.ConfirmPassword))
            {
                ApiResponse.AddError(nameof(RegisterAccountRequestModel.ConfirmPassword), "The confirm password is required.");
            }
            else if (command.Password != command.ConfirmPassword)
            {
                ApiResponse.AddError(nameof(RegisterAccountRequestModel.ConfirmPassword), "The passwords must match.");
            }
        }
Exemplo n.º 12
0
        public async Task <ApiResponse <List <QuestionViewModel> > > Get()
        {
            var result = new ApiResponse <List <QuestionViewModel> >();

            try
            {
                result.Data = await dbContext.Questions
                              .Include(a => a.Options)
                              .Select(q => new QuestionViewModel
                {
                    Id         = q.Id,
                    Title      = q.Title,
                    Type       = q.Type,
                    Options    = q.Options,
                    RatePolicy = q.RatePolicy
                })
                              .ToListAsync();


                result.AddSuccess();
                return(await Task.FromResult(result));
            }
            catch (Exception ex)
            {
                result.AddError(ex);
                return(await Task.FromResult(result));
            }
        }
Exemplo n.º 13
0
        public async Task <ActionResult <ApiResponse <SignUpApiModel.Response> > > SignUp(SignUpApiModel.Request request)
        {
            var response = new ApiResponse <SignUpApiModel.Response>();

            if (await checkEmail(request.Email))
            {
                response.AddError(1);
                return(response);
            }

            var appUser = new AppUser()
            {
                Email    = request.Email,
                UserName = request.Email
            };

            var result = await _userManager.CreateAsync(appUser, request.Password);

            if (result.Succeeded == false)
            {
                // TODO:
                return(NotFound());
            }

            response.Data = new SignUpApiModel.Response()
            {
                Email = request.Email
            };

            return(Ok(response));
        }
Exemplo n.º 14
0
        public async Task <ActionResult <ApiResponse> > DeleteBookImage(int bookImageId)
        {
            var responseModel = new ApiResponse();

            var user = await _userManager.GetUserAsync(User);

            var bookImage = await _dataAccess.BookImages
                            .Include(b => b.Book)
                            .FirstOrDefaultAsync(b => (b.Id == bookImageId && b.Book.AppUserId == user.Id) && bookImageId != b.Book.BookImageId);

            if (bookImage == null)
            {
                responseModel.AddError(11);
                return(Ok(responseModel));
            }

            var pathToFile = Directory.GetCurrentDirectory() + "\\wwwroot" + _imagesFolderPath + bookImage.ImageName;

            System.IO.File.Delete(pathToFile);

            _dataAccess.BookImages.Remove(bookImage);
            await _dataAccess.SaveChangesAsync();

            return(Ok(responseModel));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Retrieve country for the specified id
        /// </summary>
        /// <param name="countryId"></param>
        /// <param name="includeCities"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <ApiResponse <CountryResponse> > GetCountryByIdAsync(int countryId, bool includeCities = false, CancellationToken cancellationToken = default)
        {
            var responseModel = new ApiResponse <CountryResponse>();

            Country country = null;

            if (includeCities)
            {
                country = await _countriesRepo.FindByIdWithCitiesAsync(countryId);
            }

            else
            {
                country = await _countriesRepo.FindByIdAsync(countryId);
            }


            if (country == null)
            {
                responseModel.AddError(ExceptionCreator.CreateNotFoundError(nameof(country), $"country of id {countryId}: not found"));
                return(responseModel);
            }

            if (includeCities)
            {
                responseModel.Data = await CreateCountryWithCitiesResponse(country);
            }

            else
            {
                responseModel.Data = CreateCountryResponse(country);
            }

            return(responseModel);
        }
Exemplo n.º 16
0
        public async Task <ApiResponse <bool> > UdpateExam(ExamViewModel exam)
        {
            var result = new ApiResponse <bool>();

            try
            {
                var oExam = new Exam
                {
                    Id          = exam.Id,
                    Title       = exam.Title,
                    Status      = exam.Status,
                    Description = exam.Description,
                    Duration    = exam.Duration,
                    ImageUrl    = exam.ImageUrl
                };
                dbContext.Exams.Update(oExam);
                await dbContext.SaveChangesAsync();

                result.Data = true;
                result.AddSuccess();
                return(await Task.FromResult(result));
            }
            catch (Exception ex)
            {
                result.AddError(ex);
                return(await Task.FromResult(result));
            }
        }
Exemplo n.º 17
0
        public override async Task Validate(AddAssetCommand command)
        {
            if (!deviceTypeDataService.Exists(command.Model.DeviceTypeId))
            {
                ApiResponse.AddError(nameof(AddAssetRequestModel.DeviceTypeId), "The device type is not valid.");

                return;
            }

            if (string.IsNullOrEmpty(command.Model.Name))
            {
                ApiResponse.AddError(nameof(AddAssetRequestModel.Name), "The name is required.");
            }
            else if (await repository.GetEntities <UserAssetEntity>().AnyAsync(x =>
                                                                               x.UserId == command.UserId &&
                                                                               EF.Functions.Like(x.Asset.Name.ToLower(), $"{command.Model.Name.ToLower()}")))
            {
                ApiResponse.AddError(nameof(AddAssetRequestModel.Name),
                                     "You already have an asset with the same name.");
            }

            if (string.IsNullOrEmpty(command.Model.DeviceId))
            {
                ApiResponse.AddError(nameof(AddAssetRequestModel.DeviceId),
                                     "The device id is required.");
            }
            else if (await deviceService.DeviceIsUsed(command.Model.DeviceId, command.Model.DeviceTypeId))
            {
                ApiResponse.AddError(nameof(AddAssetRequestModel.DeviceId),
                                     "The device id is already used by another device on the same protocol.");
            }
        }
Exemplo n.º 18
0
        public async Task <ApiResponse <List <Option> > > GetOptionsByQuestion(Guid questionId, Guid userExamId)
        {
            var result = new ApiResponse <List <Option> >();

            try
            {
                var response = dbContext.Options.
                               Where(o => o.Question.Id == questionId).ToList()
                               .Select(e => { e.IsCorrect = false; return(e); }).ToList();

                var optionSelected = dbContext.UserAnswers
                                     .Where(e => (e.Option.QuestionId == questionId && e.UserExamId == userExamId));

                if (optionSelected.Count() == 0)
                {
                    result.Data = response;
                    result.AddSuccess();
                }
                else
                {
                    result.Data = null;
                    result.AddMessage("Question answered already");
                }

                return(await Task.FromResult(result));
            }
            catch (Exception ex)
            {
                result.AddError(ex);
                return(await Task.FromResult(result));
            }
        }
Exemplo n.º 19
0
        public async Task <ApiResponse <List <ExamQuestionViewModel> > > GetQuestionsByExam(Guid examId)
        {
            var result = new ApiResponse <List <ExamQuestionViewModel> >();

            try
            {
                var oList = await dbContext.ExamQuestions
                            .Where(ex => ex.ExamId == examId)
                            .Include(e => e.Question)
                            .Include(e => e.Exam)
                            .Select(e => new ExamQuestionViewModel
                {
                    ExamId     = e.ExamId,
                    QuestionId = e.QuestionId,
                    Exam       = e.Exam.Title,
                    Question   = e.Question.Title,
                    Type       = e.Question.Type,
                    RatePolicy = e.Question.RatePolicy
                })
                            .ToListAsync();

                result.Data = oList;
                result.AddSuccess();
                return(await Task.FromResult(result));
            }
            catch (Exception ex)
            {
                result.AddError(ex);
                return(await Task.FromResult(result));
            }
        }
Exemplo n.º 20
0
        public async Task <ActionResult <ApiResponse <GetBookApiModel.Response> > > GetBookById(int bookId)
        {
            var responseModel = new ApiResponse <GetBookApiModel.Response>();

            var book = await _dataAccess.Books.Include(b => b.BookImage).Include(b => b.BookImages).FirstOrDefaultAsync(b => b.Disabled != true && b.Id == bookId);

            if (book == null)
            {
                responseModel.AddError(8);
                return(Ok(responseModel));
            }

            responseModel.Data = new GetBookApiModel.Response()
            {
                Author      = book.Author,
                BookId      = book.Id,
                Condition   = book.Condition,
                Description = book.Description,
                Title       = book.Title,
                Year        = book.Year,
                BookImages  = book.BookImages.Select(bi => new GetBookApiModel.BookImage
                {
                    BookImageId = bi.Id,
                    ImagePath   = $"{_imagesFolderPath}{bi.ImageName}",
                    IsCover     = bi.Id == book.BookImageId
                }).ToList()
            };

            return(Ok(responseModel));
        }
Exemplo n.º 21
0
        public override Task Validate(UpdateUserCommand command)
        {
            if (!command.Model.MeasurementSystem.HasValue ||
                !Enum.IsDefined(typeof(MeasurementSystem), command.Model.MeasurementSystem.Value))
            {
                ApiResponse.AddError(nameof(command.Model.MeasurementSystem), "The value provided is not valid.");
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 22
0
        public async Task <IActionResult> GetBankAccountCashTransactions([FromRoute] string iban,
                                                                         [FromQuery] int lastDays,
                                                                         [FromQuery] int pageNumber          = PagingConstants.DefaultPageNumber,
                                                                         [FromQuery] int pageSize            = PagingConstants.DefaultPageSize,
                                                                         CancellationToken cancellationToken = default)
        {
            try
            {
                var apiResponse = new ApiResponse <CashTransactionListResponse>();

                var user = await _userManager.GetUserAsync(User);

                var customer = await _customerService.GetCustomerByIBANAsync(iban, cancellationToken);

                if (customer == null)
                {
                    apiResponse.AddError(ExceptionCreator.CreateNotFoundError(nameof(customer)));
                    return(NotFound(apiResponse));
                }

                if (user.Id != customer?.Data?.UserId)
                {
                    apiResponse.AddError(ExceptionCreator.CreateForbiddenError(nameof(user), "user is not authorized to perform operation"));
                    return(Forbid());
                }

                apiResponse = await _cashTransactionsService.GetBankAccountCashTransactionsAsync(iban, lastDays, pageNumber, pageSize, cancellationToken);

                if (apiResponse.Success)
                {
                    var pagedApiResponse = new PagedResponse <CashTransactionListResponse>(apiResponse.Data);

                    return(Ok(pagedApiResponse));
                }

                return(BadRequest(apiResponse));
            }

            catch (Exception exception)
            {
                return(_actionResultMapper.Map(exception));
            }
        }
Exemplo n.º 23
0
        public async Task <ApiResponse <bool> > SubmitUserAnswer(List <UserAnswerViewModel> userAnswer)
        {
            var result = new ApiResponse <bool>();

            try
            {
                var proceed = false;
                for (var i = 0; i < userAnswer.Count; i++)
                {
                    var currentUseranswer = await dbContext.UserAnswers
                                            .FirstOrDefaultAsync(a => (a.OptionId == userAnswer[0].OptionId &&
                                                                       a.UserExamId == userAnswer[0].UserExamId));


                    if (currentUseranswer == null)
                    {
                        var checkAnswer = await dbContext.Options.FindAsync(userAnswer[0].OptionId);

                        if (checkAnswer.IsCorrect)
                        {
                            var checkUserExam = await dbContext.UserExams.FirstOrDefaultAsync(ue => ue.Id == userAnswer[0].UserExamId);

                            checkUserExam.Score = checkUserExam.Score + checkAnswer.Score;
                        }

                        var oUserAnswer = new UserAnswer
                        {
                            OptionId   = userAnswer[i].OptionId,
                            UserExamId = userAnswer[i].UserExamId
                        };
                        await dbContext.AddAsync(oUserAnswer);

                        result.AddSuccess();
                        result.Data = true;
                        proceed     = true;
                    }
                    else
                    {
                        result.Data = false;
                        result.AddMessage("Answer Already Exist");
                    }
                }
                if (proceed)
                {
                    await dbContext.SaveChangesAsync();
                }
                return(await Task.FromResult(result));
            }
            catch (Exception ex)
            {
                result.AddError(ex);
                return(await Task.FromResult(result));
            }
        }
        /// <summary>
        /// Create a deposit transaction in db
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <Response> MakeDepositAsync(CreateCashTransactionRequest request, CancellationToken cancellationToken = default)
        {
            var responseModel   = new ApiResponse <CashTransactionResponse>();
            var amountToDeposit = request.Amount;

            var dbContextTransaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);

            try
            {
                var toAccount = await _bankAccountRepo.FindByIBANAsync(request.To);

                if (toAccount == null)
                {
                    responseModel.AddError(ExceptionCreator.CreateNotFoundError(nameof(toAccount)));
                    return(responseModel);
                }

                //Add amount to recipient balance
                toAccount.Balance             += amountToDeposit;
                toAccount.AllowedBalanceToUse += amountToDeposit;

                //Update bank account
                await _bankAccountRepo.UpdateAsync(_dbContext, toAccount);

                //Add transaction to db & save changes
                await _cashTransactionsRepo.AddAsync(_dbContext, CreateCashTransaction(request, 0, toAccount.Balance));

                await dbContextTransaction.CommitAsync(cancellationToken);

                return(responseModel);
            }

            catch (Exception ex)
            {
                await dbContextTransaction.RollbackAsync(cancellationToken);

                responseModel.AddError(ExceptionCreator.CreateInternalServerError(ex.ToString()));

                return(responseModel);
            }
        }
Exemplo n.º 25
0
        public async Task <IActionResult> Register([FromBody] RegisterViewModel model)
        {
            var result = new ApiResponse <Empty>();

            if (!ModelState.IsValid)
            {
                result.AddError(ModelState);
                return(Ok(result));
            }

            var createResult = await userManagerService.CreateUserAsync(model.Email, model.Password);

            if (createResult.RegisterResult.Succeeded)
            {
                return(Ok(result));
            }

            result.AddError(createResult.RegisterResult.Errors);

            return(Ok(result));
        }
Exemplo n.º 26
0
        public async Task <IActionResult> GetLastCashTransactions([FromRoute] string iban,
                                                                  CancellationToken cancellationToken = default)
        {
            try
            {
                var apiResponse = new ApiResponse <LastCashTransactionListResponse>();

                var user = await _userManager.GetUserAsync(User);

                var customer = await _customerService.GetCustomerByIBANAsync(iban, cancellationToken);

                if (customer == null)
                {
                    apiResponse.AddError(ExceptionCreator.CreateNotFoundError(nameof(customer)));
                    return(NotFound(apiResponse));
                }

                if (user.Id != customer?.Data?.UserId)
                {
                    apiResponse.AddError(ExceptionCreator.CreateBadRequestError(nameof(user), "user is not authorized to perform operation"));
                    return(BadRequest(apiResponse));
                }

                apiResponse = await _cashTransactionsService.GetLastCashTransactionsAsync(iban, cancellationToken);

                if (apiResponse.Success)
                {
                    return(Ok(apiResponse));
                }

                return(BadRequest(apiResponse));
            }

            catch (Exception exception)
            {
                return(_actionResultMapper.Map(exception));
            }
        }
Exemplo n.º 27
0
        public async Task <ActionResult <ApiResponse <EditProfileApiModel.Response> > > EditMyProfile(EditProfileApiModel.Request requestModel)
        {
            var user = await _userManager.GetUserAsync(User);

            var responseModel = new ApiResponse <GetProfileApiModel.Response>();

            var profile = await _dataAccess.Profiles.FirstOrDefaultAsync(profile => profile.UserId == user.Id);

            if (profile != null)
            {
                bool editted = false;
                if (!string.IsNullOrEmpty(requestModel.FirstName) && requestModel.FirstName != profile.FirstName)
                {
                    editted           = true;
                    profile.FirstName = requestModel.FirstName;
                }
                if (!string.IsNullOrEmpty(requestModel.LastName) && requestModel.LastName != profile.LastName)
                {
                    editted          = true;
                    profile.LastName = requestModel.LastName;
                }
                if (!string.IsNullOrEmpty(requestModel.Address) && requestModel.Address != profile.Address)
                {
                    editted         = true;
                    profile.Address = requestModel.Address;
                }

                if (editted == true)
                {
                    _dataAccess.Profiles.Update(profile);
                    await _dataAccess.SaveChangesAsync();
                }

                responseModel.Data = new GetProfileApiModel.Response()
                {
                    Id        = profile.Id,
                    Address   = profile.Address,
                    FirstName = profile.FirstName,
                    LastName  = profile.LastName,
                    // TODO: Add the proper rating
                    Rating = 0
                };
            }
            else
            {
                responseModel.AddError(4);
            }

            return(Ok(responseModel));
        }
Exemplo n.º 28
0
        public override Task Validate(GetDeviceConnectionsCommand command)
        {
            if (command.Page < 1)
            {
                ApiResponse.AddError(nameof(DeviceConnectionRequestModel.Page), "The Page property must be >= 1.");
            }

            if (command.PerPage < 10 || command.PerPage > 100)
            {
                ApiResponse.AddError(nameof(DeviceConnectionRequestModel.PerPage),
                                     "The PerPage property must be between 10 and 100.");
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 29
0
 public override async Task Validate(RenameAssetCommand command)
 {
     if (string.IsNullOrEmpty(command.Model.Name))
     {
         ApiResponse.AddError(nameof(AddAssetRequestModel.Name), "The name is required.");
     }
     else if (await repository.GetEntities <UserAssetEntity>().AnyAsync(x =>
                                                                        x.AssetId != command.AssetId &&
                                                                        x.UserId == command.UserId &&
                                                                        EF.Functions.Like(x.Asset.Name.ToLower(), $"{command.Model.Name.ToLower()}")))
     {
         ApiResponse.AddError(nameof(AddAssetRequestModel.Name),
                              "You already have an asset with the same name.");
     }
 }
Exemplo n.º 30
0
        /// <summary>
        /// Retrieve debit card by id
        /// </summary>
        /// <param name="debitCardId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <ApiResponse <DebitCardResponse> > GetDebitCardByIdAsync(int debitCardId, CancellationToken cancellationToken = default)
        {
            var responseModel = new ApiResponse <DebitCardResponse>();

            var debitCard = await _debitCardsRepo.FindByIdAsync(debitCardId);

            if (debitCard == null)
            {
                responseModel.AddError(ExceptionCreator.CreateNotFoundError(nameof(DebitCard), $"Debit card of id: {debitCardId}: is not found"));
                return(responseModel);
            }

            responseModel.Data = CreateDebitCardResponse(debitCard);

            return(responseModel);
        }