Skip to content

Commit

Permalink
Code clean up
Browse files Browse the repository at this point in the history
-- WEB API --
-Added server side validation
-Code refactor
-Added XML comment blocks
-Updated swagger

-- WEB CLIENT --
-Adjusted pascal case variables to camel case
-Added logout on created() in home/login
  • Loading branch information
jioo committed Sep 7, 2018
1 parent 9ba6b54 commit 2834ec2
Show file tree
Hide file tree
Showing 36 changed files with 500 additions and 391 deletions.
66 changes: 27 additions & 39 deletions WebApi/Controllers/AccountsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,83 +19,71 @@ namespace WebApi.Controllers
[Route("api/[controller]")]
public class AccountsController : ControllerBase
{
private readonly IRepository<Employee> _repo;
private readonly IEmployeeService _service;
private readonly UserManager<User> _manager;
private readonly IEmployeeService _service;
private readonly IMapper _mapper;

public AccountsController(
IRepository<Employee> repo,
UserManager<User> manager,
IEmployeeService service,
IMapper mapper)
{
_repo = repo;
_service = service;
_manager = manager;
_service = service;
_mapper = mapper;
}

// POST: api/accounts/register
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody]RegisterViewModel model)
{
if (!ModelState.IsValid)
var isCardExist = await _service.isCardExist(Guid.Empty, model.CardNo);
if (isCardExist)
{
return BadRequest("Invalid Request!");
return BadRequest("Card No. is already in use");
}

if (await _service.isCardExist(Guid.Empty, model.CardNo))
var isUsernameExist = await _manager.FindByNameAsync(model.UserName);
if(isUsernameExist != null)
{
return BadRequest("Card No. is already in use");
return BadRequest($"Username {model.UserName} is already taken");
}

// Create user account
var user = new User { UserName = model.UserName };
var result = await _manager.CreateAsync(user, model.Password);
await _manager.AddToRoleAsync(user, "Employee");

if (!result.Succeeded) return new BadRequestObjectResult("Username \'" + model.UserName + "\' is already taken");

try
{
// Synchronize account to customer
var emp = new Employee
{
IdentityId = user.Id,
Identity = user,
FullName = model.FullName,
CardNo = model.CardNo,
Position = model.Position
};
// Check if account is successfully registered
if (!result.Succeeded) return new BadRequestObjectResult("Unable to register account");

_repo.Context.Insert(emp);
await _repo.SaveAsync();
return new OkObjectResult(JsonConvert.SerializeObject(emp, new JsonSerializerSettings { Formatting = Formatting.Indented }));
}
catch (Exception ex)
// Synchronize new account to employee information
var syncResult = await _service.AddAsync(new EmployeeViewModel
{
throw ex;
}
IdentityId = user.Id,
Identity = user,
FullName = model.FullName,
CardNo = model.CardNo,
Position = model.Position
});
return new OkObjectResult(syncResult);
}

[Authorize]
[HttpPost("change-password")]
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordViewModel model)
public async Task<IActionResult> ChangePassword([FromBody]ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid Request!");
}

// Check if Old password is correct
var user = await _manager.FindByNameAsync(model.UserName);
var result = await _manager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);

if (!result.Succeeded)
if(!await _manager.CheckPasswordAsync(user, model.OldPassword))
{
return BadRequest("Incorrect password");
}


// Change account password
var result = await _manager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if(!result.Succeeded) return BadRequest("Unable to change password");

return Ok();
}
}
Expand Down
33 changes: 18 additions & 15 deletions WebApi/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ public AuthController(
RoleManager<IdentityRole> roleManager,
IEmployeeService service,
IJwtService jwtService,
IOptions<JwtIssuerOptions> jwtOptions
)
IOptions<JwtIssuerOptions> jwtOptions)
{
_userManager = userManager;
_roleManager = roleManager;
Expand All @@ -40,21 +39,21 @@ IOptions<JwtIssuerOptions> jwtOptions
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]LoginViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid Request!");
}

// Check if password is correct
var user = await _userManager.FindByNameAsync(model.UserName);
if (! await _userManager.CheckPasswordAsync(user, model.Password))
{
return BadRequest("Invalid username or password"); // user does not exist
}
if (!await _userManager.CheckPasswordAsync(user, model.Password))
return BadRequest("Invalid username or password");

// Get User Claims
var identity = await GetClaimsIdentity(model.UserName, model.Password);

// Check if account does not exist
if (identity == null) return BadRequest("Invalid username or password");

// Get employee information
var employee = await _service.GetEmployeeByUserId(user.Id);

// Generate access token for authorization
var jwt = await Tokens.GenerateJwt(identity, _jwtService, employee.Id, employee.FullName, model.UserName, _jwtOptions);
return new OkObjectResult(jwt);
}
Expand Down Expand Up @@ -83,26 +82,30 @@ public IActionResult IsEmployee()
return Ok();
}

#region Helpers
private async Task<ClaimsIdentity> GetClaimsIdentity(string userName, string password)
{
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
return await Task.FromResult<ClaimsIdentity>(null);

// get the user to verifty
// Get the user to verifty
var userToVerify = await _userManager.FindByNameAsync(userName);
// get roles

// Get roles
var roles = await _userManager.GetRolesAsync(userToVerify);

if (userToVerify == null) return await Task.FromResult<ClaimsIdentity>(null);

// check the credentials
// Check the credentials
if (await _userManager.CheckPasswordAsync(userToVerify, password))
{
return await Task.FromResult(_jwtService.GenerateClaimsIdentity(userName, roles, userToVerify.Id));
// Generate Claims
return await Task.FromResult(_jwtService.GenerateRoleClaimsIdentity(roles));
}

// Credentials are invalid, or account doesn't exist
return await Task.FromResult<ClaimsIdentity>(null);
}
#endregion
}
}
4 changes: 1 addition & 3 deletions WebApi/Controllers/ConfigController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ namespace WebApi.Controllers
[ApiController]
public class ConfigController : ControllerBase
{
private JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
private readonly IConfigService _service;
public ConfigController(IConfigService service)
{
Expand All @@ -31,8 +30,7 @@ public ConfigController(IConfigService service)
[HttpGet]
public async Task<IActionResult> Index()
{
var res = await _service.FirstOrDefaultAsync();
return new OkObjectResult( JsonConvert.SerializeObject(res, settings) );
return new OkObjectResult(await _service.FirstOrDefaultAsync());
}

// PUT api/config
Expand Down
28 changes: 10 additions & 18 deletions WebApi/Controllers/EmployeeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ namespace WebApi.Controllers
[ApiController]
public class EmployeeController : ControllerBase
{
private JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
private readonly IEmployeeService _service;

public EmployeeController(IEmployeeService service)
Expand All @@ -29,38 +28,31 @@ public EmployeeController(IEmployeeService service)
}

// GET api/employee
/// <summary>
/// List of employees
/// </summary>
[HttpGet]
public async Task<IActionResult> Index()
{
var res = await _service.GetAllAsync();
return new OkObjectResult( JsonConvert.SerializeObject(res, settings) );
return new OkObjectResult(await _service.GetAllAsync());
}

// GET api/employee/id
[HttpGet("{id:guid}")]
public async Task<IActionResult> Find(Guid id)
{
var res = await _service.FindAsync(id);
return new OkObjectResult( JsonConvert.SerializeObject(res, settings) );
return new OkObjectResult(await _service.FindAsync(id));
}


// PUT api/employee
[HttpPut]
public async Task<IActionResult> Update([FromBody]EmployeeViewModel model)
public async Task<IActionResult> Update(EmployeeViewModel model)
{
if(!ModelState.IsValid)
{
return BadRequest("Invalid Request!");
}

if(await _service.isCardExist(model.Id, model.CardNo))
{
return BadRequest("Card No. is already in use");
}
// Check if Card No already exist
var isCardExist = await _service.isCardExist(model.Id, model.CardNo);
if(isCardExist) return BadRequest("Card No. is already in use");

var res = await _service.UpdateAsync(model);
return new OkObjectResult( JsonConvert.SerializeObject(res, settings) );
return new OkObjectResult(await _service.UpdateAsync(model));
}
}
}
32 changes: 8 additions & 24 deletions WebApi/Controllers/LogController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,45 +36,29 @@ public LogController(ILogService service, IHubContext<BroadcastHub> hubContext)
[HttpGet]
public async Task<IActionResult> Index()
{
var res = await _service.GetAllAsync();
return new OkObjectResult(JsonConvert.SerializeObject(res, settings));
return new OkObjectResult(await _service.GetAllAsync());
}

// POST api/log
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Log([FromBody] LogInOutViewModel model)
{
var user = await _service.CheckCardNo(model);
if (user.Id == Guid.Empty)
{
return BadRequest("Invalid username or password!");
}
// Validate card no. & password
var user = await _service.ValidateTimeInOutCredentials(model);
if (user.Id == Guid.Empty) return BadRequest("Invalid username or password!");

var res = await _service.Log(user);
await _hubContext.Clients.All.SendAsync("employee-logged"); // broadcast to web client
return new OkObjectResult(JsonConvert.SerializeObject(res, settings));
// Broadcast to web client
await _hubContext.Clients.All.SendAsync("employee-logged");
return new OkObjectResult(await _service.Log(user));
}

// PUT api/log
[HttpPut]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Update([FromBody]LogEditViewModel model)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid Request!");
}

var res = await _service.UpdateAsync(model);
return new OkObjectResult(JsonConvert.SerializeObject(res, settings));
}
catch (Exception ex)
{
throw ex;
}
return new OkObjectResult(await _service.UpdateAsync(model));
}
}
}
49 changes: 0 additions & 49 deletions WebApi/Controllers/ValuesController.cs

This file was deleted.

24 changes: 0 additions & 24 deletions WebApi/Controllers/XsrfTokenController.cs

This file was deleted.

Loading

0 comments on commit 2834ec2

Please sign in to comment.