Example #1
0
 public IActionResult Post([FromBody] EmployeeApplicationUser employee)
 {
     try
     {
         //TO DO for later on: move the create logic for the employee position into a service
         List <PositionApplicationRole> positions = iPositionRepository.GetPositions();
         if (employee.Position == null || employee.Position.Id == 0)
         {
             employee.Position = positions.Where(x => x.Name == "No Position!").FirstOrDefault();
         }
         else
         {
             PositionApplicationRole employeePositionFromDropDownList = positions.Where(x => x.Id == employee.Position.Id).FirstOrDefault();
             employee.Position = employeePositionFromDropDownList;
         }
         iEmployeeRepository.CreateEmployee(employee);
         Uri uri = new Uri(Url.Link("GetEmployeeByID", new { Id = employee.Id }));
         iUnitOfWork.Save();
         return(Created(uri, employee.Id.ToString()));
     }
     catch (Exception ex)
     {
         return(Content(ex.ToString(), BadRequest().ToString()));
     }
 }
 public IActionResult Post([FromBody] CreateReservationViewModel createReservationViewModel)
 {
     try
     {
         foreach (RoomReservation roomReservation in createReservationViewModel.RoomReservations)
         {
             if (roomReservation.RoomID == 0)
             {
                 return(BadRequest("The room is required"));
             }
         }
         createReservationViewModel.StartDate = createReservationViewModel.StartDate.ToUniversalTime();
         createReservationViewModel.EndDate   = createReservationViewModel.EndDate.ToUniversalTime();
         Guest guestFromDropDownList = iGuestRepository.GetGuestByID(createReservationViewModel.Guest.ID);
         createReservationViewModel.Guest = guestFromDropDownList;
         EmployeeApplicationUser employeeFromDropDownList = iEmployeeRepository.GetEmployeeByID(createReservationViewModel.Employee.Id);
         createReservationViewModel.Employee = employeeFromDropDownList;
         Reservation reservation = new Reservation();
         reservation = iCreateReservationMapper.MapCreateReservationViewModelToModel(createReservationViewModel, reservation);
         iReservationRepository.CreateReservation(reservation);
         Uri uri = new Uri(Url.Link("GetReservationByID", new { Id = reservation.ID }));
         iUnitOfWork.Save();
         return(Created(uri, reservation.ID.ToString()));
     }
     catch (Exception ex)
     {
         return(Content(ex.ToString(), BadRequest().ToString()));
     }
 }
Example #3
0
 public IActionResult Put(int id, [FromBody] UpdateEmployeeViewModel employeeViewModel)
 {
     if (employeeViewModel != null)
     {
         employeeViewModel.ID = id;
         if (string.IsNullOrEmpty(employeeViewModel.UserName))
         {
             employeeViewModel.UserName = iEmployeeRepository.GetEmployeeByID(employeeViewModel.ID).UserName;
         }
         //TO DO for later on: move the update logic for the employee position into a service
         List <PositionApplicationRole> positions = iPositionRepository.GetPositions();
         if (employeeViewModel.Position.Id == 0)
         {
             employeeViewModel.Position = iEmployeeRepository.GetEmployeeByID(employeeViewModel.ID).Position;
         }
         else
         {
             PositionApplicationRole employeePositionFromDropDownList = positions.Where(x => x.Id == employeeViewModel.Position.Id).FirstOrDefault();
             employeeViewModel.Position = employeePositionFromDropDownList;
         }
         EmployeeApplicationUser employee = new EmployeeApplicationUser()
         {
             Id       = employeeViewModel.ID,
             UserName = employeeViewModel.UserName,
             Position = employeeViewModel.Position
         };
         iEmployeeRepository.UpdateEmployee(employee);
         iUnitOfWork.Save();
         return(Ok(employee));
     }
     else
     {
         return(NotFound("Employee with ID " + id.ToString() + " was not found."));
     }
 }
Example #4
0
        public void DeleteEmployee(int id)
        {
            EmployeeApplicationUser employee = GetEmployeeByID(id);

            if (employee != null)
            {
                dbContext.Employees.Remove(employee);
            }
        }
Example #5
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                /*var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.NormalPassword, Input.RememberMe, lockoutOnFailure: false);*/
                HttpClient httpClient         = new HttpClient();
                InputModel inputModelEmployee = new InputModel()
                {
                    UserName       = Input.UserName,
                    NormalPassword = Input.NormalPassword
                };
                string              json     = JsonConvert.SerializeObject(inputModelEmployee);
                StringContent       data     = new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await httpClient.PostAsync("https://localhost:44357/api/Authentication", data);

                if (response.IsSuccessStatusCode)
                {
                    _logger.LogInformation("User logged in.");
                    string jsonToken = await response.Content.ReadAsStringAsync();

                    TokenDTO token        = JsonConvert.DeserializeObject <TokenDTO>(jsonToken);
                    string   jsonWebToken = token.Token;
                    HttpContext.Response.Cookies.Append("JWTCookie", jsonWebToken, new CookieOptions()
                    {
                        HttpOnly = true, Secure = true, SameSite = SameSiteMode.Strict
                    });
                    returnUrl = "/Home/Index";
                    SecurityTokenHandler handler             = new JwtSecurityTokenHandler();
                    JwtSecurityToken     decodedJsonWebToken = handler.ReadToken(jsonWebToken) as JwtSecurityToken;
                    string   userIDClaim       = decodedJsonWebToken.Claims.Where(x => x.Type.Contains("nameidentifier")).FirstOrDefault().Value;
                    DateTime jwtExpirationDate = decodedJsonWebToken.ValidTo.ToLocalTime();
                    EmployeeApplicationUser currentEmployeeUser = iEmployeeRepository.GetEmployeeByID(int.Parse(userIDClaim));
                    bool isAuthenticated = currentEmployeeUser.Id != 0;
                    HttpContext.Session.SetString("IsAuthenticated", isAuthenticated.ToString().ToLower());
                    HttpContext.Session.SetString("UserName", currentEmployeeUser.UserName);
                    if (currentEmployeeUser.Position != null)
                    {
                        HttpContext.Session.SetString("Role", currentEmployeeUser.Position.Name);
                    }
                    HttpContext.Session.SetString("JWTExpirationDate", jwtExpirationDate.ToString());
                    return(LocalRedirect(returnUrl));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Example #6
0
        public void UpdateEmployee(EmployeeApplicationUser employee)
        {
            EmployeeApplicationUser employeeToUpdate = GetEmployeeByID(employee.Id);

            if (employeeToUpdate != null)
            {
                // this code might be extended later, for more property updates
                employeeToUpdate.UserName = employee.UserName;
                employeeToUpdate.Position = employee.Position;
                dbContext.Employees.Update(employeeToUpdate);
            }
        }
Example #7
0
        public IActionResult GetEmployeeByID(int id)
        {
            EmployeeApplicationUser employee = iEmployeeRepository.GetEmployeeByID(id);

            if (employee != null)
            {
                return(Ok(employee));
            }
            else
            {
                return(NotFound("Employee with ID " + id.ToString() + " was not found."));
            }
        }
Example #8
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            List <PositionApplicationRole> positions = iPositionRepository.GetPositions();

            if (ModelState.IsValid)
            {
                var user = new EmployeeApplicationUser {
                    UserName = Input.UserName, Email = Input.Email,
                    Position = positions.Where(x => x.Name == "No Position!").FirstOrDefault()
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.UserName, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Example #9
0
        public IActionResult Delete(int id)
        {
            EmployeeApplicationUser employeeToDelete = iEmployeeRepository.GetEmployeeByID(id);

            if (employeeToDelete != null)
            {
                //if a certain reservation has this employee(the employee for deletion), we are setting its employee to be "NoEmployee"
                employeeToDelete.Reservations.ForEach(x =>
                                                      x.Employee = iEmployeeRepository.GetEmployees().Where(x => x.UserName == "NoEmployee").FirstOrDefault());
                iEmployeeRepository.DeleteEmployee(employeeToDelete.Id);
                iUnitOfWork.Save();
                return(Ok(employeeToDelete));
            }
            else
            {
                return(NotFound("Employee with ID " + id.ToString() + " was not found."));
            }
        }
        public IActionResult Login(EmployeeViewModel employeeViewModel)
        {
            EmployeeApplicationUser employee = new EmployeeApplicationUser();

            employee = iEmployeeRepository.GetEmployees().Where(x => x.UserName == employeeViewModel.UserName).FirstOrDefault();
            if (employee != null)
            {
                PasswordVerificationResult isNormalPasswordEqualToHashedPassword =
                    userManager.PasswordHasher.VerifyHashedPassword(employee, employee.PasswordHash, employeeViewModel.NormalPassword);
                List <EmployeeApplicationUser> employees = iEmployeeRepository.GetEmployees();
                if (isNormalPasswordEqualToHashedPassword != PasswordVerificationResult.Failed)
                {
                    // password is correct
                    if (employees.Exists(x => x.UserName == employee.UserName && x.PasswordHash == employee.PasswordHash))
                    {
                        string secret   = Configuration["JWTConfiguration:secret"];
                        string issuer   = Configuration["JWTConfiguration:issuer"];
                        string audience = Configuration["JWTConfiguration:audience"];

                        SymmetricSecurityKey secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
                        SigningCredentials   signInCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
                        List <Claim>         claims            = new List <Claim>()
                        {
                            new Claim(ClaimTypes.NameIdentifier, employee.Id.ToString()),
                            new Claim(ClaimTypes.Name, employee.UserName)
                        };
                        if (employee.Position != null)
                        {
                            claims.Add(new Claim(ClaimTypes.Role, employee.Position.Name));
                        }
                        JwtSecurityToken tokenOptions = new JwtSecurityToken(
                            issuer: issuer,
                            audience: audience,
                            claims: claims,
                            expires: DateTime.Now.AddMinutes(5),
                            signingCredentials: signInCredentials
                            );
                        string tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
                        return(Ok(new { Token = tokenString }));
                    }
                }
            }
            return(NotFound("Wrong username/password!"));
        }
Example #11
0
 public void CreateEmployee(EmployeeApplicationUser employee)
 {
     dbContext.Employees.Add(employee);
 }