public IActionResult Index()
        {
            if (!IsWorker())
            {
                return(Redirect("/"));
            }
            User          user          = this._userManager.GetUserAsync(HttpContext.User).Result;
            WorkerAccount workerAccount =
                _applicationDbContext.
                WorkerAccounts.Where(a => a.Id == user.WorkerAccountId).
                Include(a => a.Jobs).First();

            if (!workerAccount.Jobs.Any(a => a.JobState == JobState.Hiring))
            {
                ViewData["Jobs"] = "<h2>You have no active jobs!</h2>";
                return(View());
            }
            StringBuilder stringBuilder = new StringBuilder();

            foreach (var job in workerAccount.Jobs.Where(a => a.JobState == JobState.Hiring))
            {
                stringBuilder.AppendLine("<li>");
                stringBuilder.AppendLine("<a href=\"/WorkerActiveJob/Index/" + job.Id + "\">" + job.Name + "</a>");
                stringBuilder.AppendLine("</li>");
            }
            ViewData["Jobs"] = stringBuilder.ToString();

            return(View());
        }
Exemplo n.º 2
0
        public bool UpdateWorkerAccount(WorkerAccount workerAccount)
        {
            //TODO: its not returning from database workerAccount is from body
            ReplaceOneResult result = _workers.ReplaceOne(w => w.Id == workerAccount.Id, workerAccount);

            return(result.MatchedCount > 0);
        }
Exemplo n.º 3
0
        public IActionResult Index()
        {
            if (!service.IsWorker())
            {
                return(Redirect("/"));
            }
            User          user          = service.GetCurrentUser();
            WorkerAccount workerAccount = service.GetWorkerAccount();

            if (!service.HasActiveJobs())
            {
                ViewData["Jobs"] = "<h2>You have no active jobs!</h2>";
                return(View());
            }
            StringBuilder stringBuilder = new StringBuilder();

            foreach (var job in service.ActiveJobs())
            {
                stringBuilder.AppendLine("<li>");
                stringBuilder.AppendLine("<a href=\"/WorkerActiveJob/Index/" + job.Id + "\">" + job.Name + "</a>");
                stringBuilder.AppendLine("</li>");
            }
            ViewData["Jobs"] = stringBuilder.ToString();

            return(View());
        }
Exemplo n.º 4
0
        private string generateJwtTokenRequestOTP(WorkerAccount account, String OtpCode)
        {
            var token = generateJwtToken(new[] {
                new Claim("user_id", account.Id.ToString()),
                new Claim("otp_code", OtpCode)
            }, DateTime.UtcNow.AddSeconds(60));

            return(token);
        }
 private static void SetUpdatedWorkerAccountFields(WorkerAccount worker, WorkerAccount workerAccount)
 {
     worker.Username  = workerAccount.Username;
     worker.FirstName = workerAccount.FirstName;
     worker.LastName  = workerAccount.LastName;
     worker.Telephone = workerAccount.Telephone;
     //TODO: ckeck if start < end
     worker.StartContractDate = workerAccount.StartContractDate;
     worker.EndContractDate   = workerAccount.EndContractDate;
 }
Exemplo n.º 6
0
 private string generateJwtTokeAuthResponse(WorkerAccount account)
 {
     if (account != null)
     {
         var token = generateJwtToken(new[] {
             new Claim("user_id", account.Id.ToString()),
         }, DateTime.UtcNow.AddDays(10));;
         return(token);
     }
     return(null);
 }
        public bool UpdateWorkerAccount(WorkerAccount workerAccount)
        {
            WorkerAccount worker = _accountsRepository.GetWorkerAccount(workerAccount.Id);

            if (worker == null)
            {
                return(false);
            }
            SetUpdatedWorkerAccountFields(worker, workerAccount);
            return(_accountsRepository.UpdateWorkerAccount(worker));
        }
        public WorkerAccount AddWorkerAccount(WorkerAccount workerAccount)
        {
            string     roleName = "Worker";
            SystemRole role     = _systemRolesRepository.GetSystemRoleByName(roleName);

            workerAccount.Role        = role;
            workerAccount.AccountType = "Worker";
            workerAccount.Password    = BCrypt.Net.BCrypt.HashPassword(workerAccount.Password);
            WorkerAccount w = _accountsRepository.AddWorkerAccount(workerAccount);

            return(w);
        }
Exemplo n.º 9
0
        public async Task <WorkerAccount> CreateAccount(WorkerAccount account)
        {
            var nowDateTime = DateTime.Now;
            var newAccount  = new WorkerAccount()
            {
                Phonenumber = account.Phonenumber,
                CreatedOn   = nowDateTime,
            };
            await context.WorkerAccount.AddAsync(newAccount);

            await context.SaveChangesAsync();

            return(newAccount);
        }
Exemplo n.º 10
0
 public IActionResult AddWorker(WorkerAccountCreationDto workerAccount)
 {
     try
     {
         WorkerAccount worker = _mapper.Map <WorkerAccount>(workerAccount);
         worker = _accountsServices.AddWorkerAccount(worker);
         ;
         return(CreatedAtRoute("GetWorker", new { id = worker.Id }, worker));
     }
     catch (Exception ex)
     {
         return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
     }
 }
Exemplo n.º 11
0
 public IActionResult GetWorkerById(string id)
 {
     try
     {
         WorkerAccount w = _accountsServices.GetWorkerAccount(id);
         if (w == null)
         {
             return(NotFound("Worker account with id not found"));
         }
         return(Ok(_mapper.Map <WorkerAccountDto>(w)));
     }
     catch (Exception ex)
     {
         return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
     }
 }
        public List <Reservation> GetReservationsForAccount(string id)
        {
            //TODO: Worker can also make reservations
            ClientAccount client = _accountsService.GetClientAccount(id);

            if (client == null)
            {
                WorkerAccount worker = _accountsService.GetWorkerAccount(id);
                if (worker == null)
                {
                    throw new InvalidForeignKeyException("Invalid account id");
                }
                return(_reservationsRepository.GetReservationsForAccount(id));
            }
            return(_reservationsRepository.GetReservationsForAccount(id));
        }
Exemplo n.º 13
0
        public bool WorkerAlreadyApplied(int jobId)
        {
            WorkerAccount workerAccount = applicationDbContext.
                                          WorkerAccounts.First
                                              (a => a.Id == GetCurrentUser().WorkerAccountId);
            Job job = applicationDbContext.Jobs.Where(a => a.Id == jobId).
                      Include(a => a.Applicants).First();

            if (workerAccount.ActiveApplications.Any(a => a.JobId == job.Id))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 14
0
        private void setPaymentFields(Payment payment)
        {
            WorkerAccount w = _accountsService.GetWorkerAccount(payment.WorkerAccount.Id);

            if (w == null)
            {
                throw new InvalidForeignKeyException("Invalid workerAccountId");
            }
            Reservation r = _reservationsService.GetReservation(payment.Reservation.Id);

            if (r == null)
            {
                throw new InvalidForeignKeyException("Invalid reservationId");
            }
            payment.WorkerAccount = w;
            payment.Reservation   = r;
        }
Exemplo n.º 15
0
        public IActionResult Index()
        {
            ListWorkerJobsViewModel model = new ListWorkerJobsViewModel();

            if (!service.IsWorker())
            {
                return(Redirect("/"));
            }
            User          user          = service.GetCurrentUser();
            WorkerAccount workerAccount = service.GetWorkerAccount();

            model.AnyActiveJobs = service.HasActiveJobs();
            if (!model.AnyActiveJobs)
            {
                return(View(model));
            }
            model.ActiveJobs = service.ActiveJobs();
            return(View(model));
        }
        public IActionResult Index()
        {
            if (!IsWorker())
            {
                return(Redirect("/"));
            }
            User          user          = this._userManager.GetUserAsync(HttpContext.User).Result;
            WorkerAccount workerAccount = _applicationDbContext.
                                          WorkerAccounts.Where(a => a.Id == user.WorkerAccountId).
                                          Include(a => a.ActiveApplications).ThenInclude(a => a.Job).First();

            if (!workerAccount.ActiveApplications.Any())
            {
                ViewData["applications"] = "<h2>You haven't made any applications yet!</h2>";
                return(View());
            }
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("<table class=\"table\"\">");
            stringBuilder.AppendLine("<thead>");
            stringBuilder.AppendLine("<tr>");
            stringBuilder.AppendLine("<th scope=\"col\">Name of job</th>");
            stringBuilder.AppendLine("<th scope=\"col\">Description</th>");
            stringBuilder.AppendLine("<th scope=\"col\">Payment</th>");
            stringBuilder.AppendLine("<th scope=\"col\">Status</th>");
            stringBuilder.AppendLine("</tr>");
            stringBuilder.AppendLine("</thead>");
            stringBuilder.AppendLine("<tbody>");
            foreach (var application in workerAccount.ActiveApplications)
            {
                stringBuilder.AppendLine("<tr>");
                stringBuilder.AppendLine("<td>" + application.Job.Name + "</td>");
                stringBuilder.AppendLine("<td>" + application.Job.Description + "</td>");
                stringBuilder.AppendLine("<td>" + application.Job.PayUponCompletion + "</td>");
                stringBuilder.AppendLine("<td>" + this.ParseApplicationState(application.ApplicationState) + "</td>");
                stringBuilder.AppendLine("</tr>");
            }
            stringBuilder.AppendLine("</tbody>");
            stringBuilder.AppendLine("</table>");
            ViewData["applications"] = stringBuilder.ToString();
            return(View());
        }
Exemplo n.º 17
0
        public IActionResult OnGet()
        {
            User currentUser = _userManager.GetUserAsync(HttpContext.User).Result;

            if (currentUser.EmployerAccountId != null)
            {
                EmployerAccount employerAccount =
                    _applicationDbContext.EmployerAccounts.
                    First(a => a.Id == currentUser.EmployerAccountId);
                employerAccount.UserId = currentUser.Id;
            }
            else
            {
                WorkerAccount workerAccount =
                    _applicationDbContext.WorkerAccounts.
                    First(a => a.Id == currentUser.WorkerAccountId);
                workerAccount.UserId = currentUser.Id;
            }
            _applicationDbContext.SaveChanges();
            return(Redirect("/"));
        }
        public IActionResult Index()
        {
            if (!IsWorker())
            {
                return(Redirect("/"));
            }
            User          user          = this._userManager.GetUserAsync(HttpContext.User).Result;
            WorkerAccount workerAccount = _applicationDbContext.
                                          WorkerAccounts.Where(a => a.Id == user.WorkerAccountId).
                                          Include(a => a.ActiveApplications).ThenInclude(a => a.Job).First();
            YourApplicationsViewModel model = new YourApplicationsViewModel();

            model.AnyActiveApplications = workerAccount.ActiveApplications.Any();
            if (!model.AnyActiveApplications)
            {
                return(View(model));
            }
            model.ActiveApplications = workerAccount.ActiveApplications;

            return(View(model));
        }
Exemplo n.º 19
0
 public IActionResult GetUserFromToken()
 {
     try
     {
         string        id     = HttpContext.GetUserId();
         ClientAccount client = _accountsService.GetClientAccount(id);
         if (client != null)
         {
             return(Ok(_mapper.Map <ClientAccountDto>(client)));
         }
         WorkerAccount worker = _accountsService.GetWorkerAccount(id);
         if (worker != null)
         {
             return(Ok(_mapper.Map <WorkerAccountDto>(worker)));
         }
         return(BadRequest("Id from token not mapped to user"));
     }
     catch (Exception ex)
     {
         return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
     }
 }
Exemplo n.º 20
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            AccountsService _accountsService = (AccountsService)context.HttpContext.RequestServices.GetService <IAccountsService>();

            try
            {
                var postRequest = context.ActionArguments["workerAccount"] as WorkerAccountCreationDto;
                var putRequest  = context.ActionArguments["workerAccount"] as WorkerAccountUpdateDto;
                if (postRequest != null)
                {
                    //TODO: If properties are null
                    string        username           = postRequest.Username;
                    string        email              = postRequest.Email;
                    ClientAccount clientWithUsername = _accountsService.GetClientAccountByUsername(username);
                    ClientAccount clientWithEmail    = _accountsService.GetClientAccountByEmail(email);
                    WorkerAccount workerWithUsername = _accountsService.GetWorkerAccountByEmail(email);
                    WorkerAccount workerWithEmail    = _accountsService.GetWorkerAccountByUsername(username);
                    if (clientWithUsername != null || workerWithUsername != null)
                    {
                        throw new Exception("Username is already taken");
                    }
                    if (clientWithEmail != null || workerWithEmail != null)
                    {
                        throw new Exception("Email already in use");
                    }
                }
                else if (putRequest != null)
                {
                    //TODO: If properties are null
                    //TODO: id will be null if post gets updatedto
                    string username = putRequest.Username;
                    string id       = (string)context.ActionArguments["id"];
                    //TODO: Check if id is valid 24 digit hex string, mongodb objectid
                    if (!CheckIdHelpper.CheckId(id))
                    {
                        context.Result = new BadRequestObjectResult("Id is not a valid 24 digit hex string");
                        return;
                    }
                    ClientAccount clientWithId = _accountsService.GetClientAccount(id);
                    if (clientWithId == null)
                    {
                        context.Result = new NotFoundObjectResult("Worker account with id not found");
                        return;
                    }
                    ClientAccount clientWithUsername = _accountsService.GetClientAccountByUsername(username);
                    WorkerAccount workerWithUsername = _accountsService.GetWorkerAccountByUsername(username);
                    if ((workerWithUsername != null && workerWithUsername.Id != id) || clientWithUsername != null)
                    {
                        throw new Exception("Username is already taken");
                    }
                }
                else
                {
                    throw new Exception("Wrong request format");
                }
            }
            catch (Exception e)
            {
                context.Result = new BadRequestObjectResult(e.Message);
                return;
            }
            await next();
        }
Exemplo n.º 21
0
 public WorkerAccount AddWorkerAccount(WorkerAccount workerAccount)
 {
     _workers.InsertOne(workerAccount);
     return(workerAccount);
 }
 public VerificationResponse(WorkerAccount WorkerAccount, string AuthToken)
 {
     this.WorkerAccount = WorkerAccount;
     this.AuthToken     = AuthToken;
 }
Exemplo n.º 23
0
 public IActionResult UpdateWorker(string id, WorkerAccount workerAccount)
 {
     workerAccount.Id = id;
     return(Ok(_accountsServices.UpdateWorkerAccount(workerAccount)));
 }
Exemplo n.º 24
0
        public AuthenticationResult Login(string email, string password)
        {
            var           tokenHandler = new JwtSecurityTokenHandler();
            var           key          = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
            ClientAccount client       = _accountsService.GetClientAccountByEmail(email);

            if (client == null)
            {
                WorkerAccount worker = _accountsService.GetWorkerAccountByEmail(email);
                if (worker == null)
                {
                    return(new AuthenticationResult
                    {
                        Error = "Account with email not found",
                        Success = false
                    });
                }
                if (BCrypt.Net.BCrypt.Verify(password, worker.Password))
                {
                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                        Subject = new ClaimsIdentity(new[]
                        {
                            new Claim("id", worker.Id),
                            new Claim(ClaimTypes.Role, worker.Role.Name)
                        }),
                        Expires            = DateTime.UtcNow.AddHours(2),
                        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                    };
                    var token = tokenHandler.CreateToken(tokenDescriptor);
                    return(new AuthenticationResult
                    {
                        Token = tokenHandler.WriteToken(token),
                        Success = true
                    });
                }
                return(new AuthenticationResult
                {
                    Error = "User/password combination is wrong",
                    Success = false
                });
            }
            if (BCrypt.Net.BCrypt.Verify(password, client.Password))
            {
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new[]
                    {
                        new Claim("id", client.Id),
                        new Claim(ClaimTypes.Role, client.Role.Name)
                    }),
                    Expires            = DateTime.UtcNow.AddHours(2),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                return(new AuthenticationResult {
                    Token = tokenHandler.WriteToken(token),
                    Success = true
                });
            }
            return(new AuthenticationResult
            {
                Error = "User/password combination is wrong",
                Success = false
            });
        }