Skip to content

Commit 2834ec2

Browse files
committed
Code clean up
-- 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
1 parent 9ba6b54 commit 2834ec2

36 files changed

+500
-391
lines changed

WebApi/Controllers/AccountsController.cs

Lines changed: 27 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -19,83 +19,71 @@ namespace WebApi.Controllers
1919
[Route("api/[controller]")]
2020
public class AccountsController : ControllerBase
2121
{
22-
private readonly IRepository<Employee> _repo;
23-
private readonly IEmployeeService _service;
2422
private readonly UserManager<User> _manager;
23+
private readonly IEmployeeService _service;
2524
private readonly IMapper _mapper;
2625

2726
public AccountsController(
28-
IRepository<Employee> repo,
2927
UserManager<User> manager,
3028
IEmployeeService service,
3129
IMapper mapper)
3230
{
33-
_repo = repo;
34-
_service = service;
3531
_manager = manager;
32+
_service = service;
3633
_mapper = mapper;
3734
}
3835

3936
// POST: api/accounts/register
4037
[HttpPost("register")]
4138
public async Task<IActionResult> Register([FromBody]RegisterViewModel model)
4239
{
43-
if (!ModelState.IsValid)
40+
var isCardExist = await _service.isCardExist(Guid.Empty, model.CardNo);
41+
if (isCardExist)
4442
{
45-
return BadRequest("Invalid Request!");
43+
return BadRequest("Card No. is already in use");
4644
}
4745

48-
if (await _service.isCardExist(Guid.Empty, model.CardNo))
46+
var isUsernameExist = await _manager.FindByNameAsync(model.UserName);
47+
if(isUsernameExist != null)
4948
{
50-
return BadRequest("Card No. is already in use");
49+
return BadRequest($"Username {model.UserName} is already taken");
5150
}
5251

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

58-
if (!result.Succeeded) return new BadRequestObjectResult("Username \'" + model.UserName + "\' is already taken");
59-
60-
try
61-
{
62-
// Synchronize account to customer
63-
var emp = new Employee
64-
{
65-
IdentityId = user.Id,
66-
Identity = user,
67-
FullName = model.FullName,
68-
CardNo = model.CardNo,
69-
Position = model.Position
70-
};
57+
// Check if account is successfully registered
58+
if (!result.Succeeded) return new BadRequestObjectResult("Unable to register account");
7159

72-
_repo.Context.Insert(emp);
73-
await _repo.SaveAsync();
74-
return new OkObjectResult(JsonConvert.SerializeObject(emp, new JsonSerializerSettings { Formatting = Formatting.Indented }));
75-
}
76-
catch (Exception ex)
60+
// Synchronize new account to employee information
61+
var syncResult = await _service.AddAsync(new EmployeeViewModel
7762
{
78-
throw ex;
79-
}
63+
IdentityId = user.Id,
64+
Identity = user,
65+
FullName = model.FullName,
66+
CardNo = model.CardNo,
67+
Position = model.Position
68+
});
69+
return new OkObjectResult(syncResult);
8070
}
8171

8272
[Authorize]
8373
[HttpPost("change-password")]
84-
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordViewModel model)
74+
public async Task<IActionResult> ChangePassword([FromBody]ChangePasswordViewModel model)
8575
{
86-
if (!ModelState.IsValid)
87-
{
88-
return BadRequest("Invalid Request!");
89-
}
90-
76+
// Check if Old password is correct
9177
var user = await _manager.FindByNameAsync(model.UserName);
92-
var result = await _manager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
93-
94-
if (!result.Succeeded)
78+
if(!await _manager.CheckPasswordAsync(user, model.OldPassword))
9579
{
9680
return BadRequest("Incorrect password");
9781
}
98-
82+
83+
// Change account password
84+
var result = await _manager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
85+
if(!result.Succeeded) return BadRequest("Unable to change password");
86+
9987
return Ok();
10088
}
10189
}

WebApi/Controllers/AuthController.cs

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ public AuthController(
2626
RoleManager<IdentityRole> roleManager,
2727
IEmployeeService service,
2828
IJwtService jwtService,
29-
IOptions<JwtIssuerOptions> jwtOptions
30-
)
29+
IOptions<JwtIssuerOptions> jwtOptions)
3130
{
3231
_userManager = userManager;
3332
_roleManager = roleManager;
@@ -40,21 +39,21 @@ IOptions<JwtIssuerOptions> jwtOptions
4039
[HttpPost("login")]
4140
public async Task<IActionResult> Login([FromBody]LoginViewModel model)
4241
{
43-
if (!ModelState.IsValid)
44-
{
45-
return BadRequest("Invalid Request!");
46-
}
47-
42+
// Check if password is correct
4843
var user = await _userManager.FindByNameAsync(model.UserName);
49-
if (! await _userManager.CheckPasswordAsync(user, model.Password))
50-
{
51-
return BadRequest("Invalid username or password"); // user does not exist
52-
}
44+
if (!await _userManager.CheckPasswordAsync(user, model.Password))
45+
return BadRequest("Invalid username or password");
5346

47+
// Get User Claims
5448
var identity = await GetClaimsIdentity(model.UserName, model.Password);
49+
50+
// Check if account does not exist
5551
if (identity == null) return BadRequest("Invalid username or password");
5652

53+
// Get employee information
5754
var employee = await _service.GetEmployeeByUserId(user.Id);
55+
56+
// Generate access token for authorization
5857
var jwt = await Tokens.GenerateJwt(identity, _jwtService, employee.Id, employee.FullName, model.UserName, _jwtOptions);
5958
return new OkObjectResult(jwt);
6059
}
@@ -83,26 +82,30 @@ public IActionResult IsEmployee()
8382
return Ok();
8483
}
8584

85+
#region Helpers
8686
private async Task<ClaimsIdentity> GetClaimsIdentity(string userName, string password)
8787
{
8888
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
8989
return await Task.FromResult<ClaimsIdentity>(null);
9090

91-
// get the user to verifty
91+
// Get the user to verifty
9292
var userToVerify = await _userManager.FindByNameAsync(userName);
93-
// get roles
93+
94+
// Get roles
9495
var roles = await _userManager.GetRolesAsync(userToVerify);
9596

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

98-
// check the credentials
99+
// Check the credentials
99100
if (await _userManager.CheckPasswordAsync(userToVerify, password))
100101
{
101-
return await Task.FromResult(_jwtService.GenerateClaimsIdentity(userName, roles, userToVerify.Id));
102+
// Generate Claims
103+
return await Task.FromResult(_jwtService.GenerateRoleClaimsIdentity(roles));
102104
}
103105

104106
// Credentials are invalid, or account doesn't exist
105107
return await Task.FromResult<ClaimsIdentity>(null);
106108
}
109+
#endregion
107110
}
108111
}

WebApi/Controllers/ConfigController.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ namespace WebApi.Controllers
2020
[ApiController]
2121
public class ConfigController : ControllerBase
2222
{
23-
private JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
2423
private readonly IConfigService _service;
2524
public ConfigController(IConfigService service)
2625
{
@@ -31,8 +30,7 @@ public ConfigController(IConfigService service)
3130
[HttpGet]
3231
public async Task<IActionResult> Index()
3332
{
34-
var res = await _service.FirstOrDefaultAsync();
35-
return new OkObjectResult( JsonConvert.SerializeObject(res, settings) );
33+
return new OkObjectResult(await _service.FirstOrDefaultAsync());
3634
}
3735

3836
// PUT api/config

WebApi/Controllers/EmployeeController.cs

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ namespace WebApi.Controllers
2020
[ApiController]
2121
public class EmployeeController : ControllerBase
2222
{
23-
private JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
2423
private readonly IEmployeeService _service;
2524

2625
public EmployeeController(IEmployeeService service)
@@ -29,38 +28,31 @@ public EmployeeController(IEmployeeService service)
2928
}
3029

3130
// GET api/employee
31+
/// <summary>
32+
/// List of employees
33+
/// </summary>
3234
[HttpGet]
3335
public async Task<IActionResult> Index()
3436
{
35-
var res = await _service.GetAllAsync();
36-
return new OkObjectResult( JsonConvert.SerializeObject(res, settings) );
37+
return new OkObjectResult(await _service.GetAllAsync());
3738
}
3839

3940
// GET api/employee/id
4041
[HttpGet("{id:guid}")]
4142
public async Task<IActionResult> Find(Guid id)
4243
{
43-
var res = await _service.FindAsync(id);
44-
return new OkObjectResult( JsonConvert.SerializeObject(res, settings) );
44+
return new OkObjectResult(await _service.FindAsync(id));
4545
}
4646

47-
4847
// PUT api/employee
4948
[HttpPut]
50-
public async Task<IActionResult> Update([FromBody]EmployeeViewModel model)
49+
public async Task<IActionResult> Update(EmployeeViewModel model)
5150
{
52-
if(!ModelState.IsValid)
53-
{
54-
return BadRequest("Invalid Request!");
55-
}
56-
57-
if(await _service.isCardExist(model.Id, model.CardNo))
58-
{
59-
return BadRequest("Card No. is already in use");
60-
}
51+
// Check if Card No already exist
52+
var isCardExist = await _service.isCardExist(model.Id, model.CardNo);
53+
if(isCardExist) return BadRequest("Card No. is already in use");
6154

62-
var res = await _service.UpdateAsync(model);
63-
return new OkObjectResult( JsonConvert.SerializeObject(res, settings) );
55+
return new OkObjectResult(await _service.UpdateAsync(model));
6456
}
6557
}
6658
}

WebApi/Controllers/LogController.cs

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -36,45 +36,29 @@ public LogController(ILogService service, IHubContext<BroadcastHub> hubContext)
3636
[HttpGet]
3737
public async Task<IActionResult> Index()
3838
{
39-
var res = await _service.GetAllAsync();
40-
return new OkObjectResult(JsonConvert.SerializeObject(res, settings));
39+
return new OkObjectResult(await _service.GetAllAsync());
4140
}
4241

4342
// POST api/log
4443
[HttpPost]
4544
[AllowAnonymous]
4645
public async Task<IActionResult> Log([FromBody] LogInOutViewModel model)
4746
{
48-
var user = await _service.CheckCardNo(model);
49-
if (user.Id == Guid.Empty)
50-
{
51-
return BadRequest("Invalid username or password!");
52-
}
47+
// Validate card no. & password
48+
var user = await _service.ValidateTimeInOutCredentials(model);
49+
if (user.Id == Guid.Empty) return BadRequest("Invalid username or password!");
5350

54-
var res = await _service.Log(user);
55-
await _hubContext.Clients.All.SendAsync("employee-logged"); // broadcast to web client
56-
return new OkObjectResult(JsonConvert.SerializeObject(res, settings));
51+
// Broadcast to web client
52+
await _hubContext.Clients.All.SendAsync("employee-logged");
53+
return new OkObjectResult(await _service.Log(user));
5754
}
5855

5956
// PUT api/log
6057
[HttpPut]
6158
[Authorize(Roles = "Admin")]
6259
public async Task<IActionResult> Update([FromBody]LogEditViewModel model)
6360
{
64-
try
65-
{
66-
if (!ModelState.IsValid)
67-
{
68-
return BadRequest("Invalid Request!");
69-
}
70-
71-
var res = await _service.UpdateAsync(model);
72-
return new OkObjectResult(JsonConvert.SerializeObject(res, settings));
73-
}
74-
catch (Exception ex)
75-
{
76-
throw ex;
77-
}
61+
return new OkObjectResult(await _service.UpdateAsync(model));
7862
}
7963
}
8064
}

WebApi/Controllers/ValuesController.cs

Lines changed: 0 additions & 49 deletions
This file was deleted.

WebApi/Controllers/XsrfTokenController.cs

Lines changed: 0 additions & 24 deletions
This file was deleted.

0 commit comments

Comments
 (0)