API
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RegisterController.cs 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Linq;
  5. using System.Security.Claims;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using AutoMapper;
  9. using Microsoft.AspNetCore.Authorization;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.Extensions.Options;
  12. using Microsoft.IdentityModel.Tokens;
  13. using UnivateProperties_API.Containers.Users;
  14. using UnivateProperties_API.Helpers;
  15. using UnivateProperties_API.Model.Users;
  16. using UnivateProperties_API.Repository;
  17. using UnivateProperties_API.Repository.Users;
  18. namespace UnivateProperties_API.Controllers.Users
  19. {
  20. [Route("api/[controller]")]
  21. [ApiController]
  22. public class RegisterController : ControllerBase
  23. {
  24. private readonly IRegisterRepository _Repo;
  25. private IMapper _mapper;
  26. private readonly AppSettings _appSettings;
  27. public RegisterController(IRegisterRepository repo, IMapper mapper, IOptions<AppSettings> appSettings)
  28. {
  29. _Repo = repo;
  30. _mapper = mapper;
  31. _appSettings = appSettings.Value;
  32. }
  33. [AllowAnonymous]
  34. [HttpPost("authenticate")]
  35. public IActionResult Authenticate([FromBody]UserDto userDto)
  36. {
  37. var user = _Repo.Authenticate(userDto.Username, userDto.Password);
  38. if (user == null)
  39. return BadRequest(new { message = "Username or password is incorrect" });
  40. var tokenHandler = new JwtSecurityTokenHandler();
  41. var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
  42. var tokenDescriptor = new SecurityTokenDescriptor
  43. {
  44. Subject = new ClaimsIdentity(new Claim[]
  45. {
  46. new Claim(ClaimTypes.Name, user.Id.ToString()),
  47. new Claim(ClaimTypes.Role, user.Role)
  48. }),
  49. Expires = DateTime.UtcNow.AddMinutes(15),
  50. SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
  51. };
  52. var token = tokenHandler.CreateToken(tokenDescriptor);
  53. var tokenString = tokenHandler.WriteToken(token);
  54. // return basic user info (without password) and token to store client side
  55. return Ok(new
  56. {
  57. user.Id,
  58. user.Username,
  59. user.Name,
  60. user.Surname,
  61. Token = tokenString
  62. });
  63. }
  64. [AllowAnonymous]
  65. [HttpPost("register")]
  66. public IActionResult Register([FromBody]UserDto userDto)
  67. {
  68. // map dto to entity
  69. var user = _mapper.Map<User>(userDto);
  70. try
  71. {
  72. // save
  73. _Repo.Create(user, userDto.Password, true);
  74. return Ok();
  75. }
  76. catch (AppException ex)
  77. {
  78. // return error message if there was an exception
  79. return BadRequest(new { message = ex.Message });
  80. }
  81. }
  82. [AllowAnonymous]
  83. [HttpPost("registeragency")]
  84. public IActionResult RegisterAgency([FromBody]AgencyDto agency)
  85. {
  86. // map dto to entity
  87. _mapper.Map<Agency>(agency);
  88. try
  89. {
  90. // save
  91. _Repo.CreateAgency(agency);
  92. return Ok();
  93. }
  94. catch (AppException ex)
  95. {
  96. // return error message if there was an exception
  97. return BadRequest(new { message = ex.Message });
  98. }
  99. }
  100. [HttpPut("{id}")]
  101. public IActionResult Update(int id, [FromBody]UserDto userDto)
  102. {
  103. // map dto to entity and set id
  104. var user = _mapper.Map<User>(userDto);
  105. user.Id = id;
  106. try
  107. {
  108. // save
  109. _Repo.Update(user, userDto.Password);
  110. return Ok();
  111. }
  112. catch (AppException ex)
  113. {
  114. // return error message if there was an exception
  115. return BadRequest(new { message = ex.Message });
  116. }
  117. }
  118. [HttpPut("{id}")]
  119. public IActionResult UpdateAgency(int id, [FromBody]UserDto userDto)
  120. {
  121. // map dto to entity and set id
  122. var agency = _mapper.Map<Agency>(userDto);
  123. agency.Id = id;
  124. try
  125. {
  126. // save
  127. _Repo.UpdateAgency(agency, userDto.Password);
  128. return Ok();
  129. }
  130. catch (AppException ex)
  131. {
  132. // return error message if there was an exception
  133. return BadRequest(new { message = ex.Message });
  134. }
  135. }
  136. [HttpGet("{id}")]
  137. public IActionResult GetById(int id)
  138. {
  139. var user = _Repo.GetById(id);
  140. var userDto = _mapper.Map<UserDto>(user);
  141. if (user == null)
  142. {
  143. return NotFound();
  144. }
  145. // Only allow SuperAdmins to access other user records
  146. var currentUserId = int.Parse(User.Identity.Name);
  147. if (id != currentUserId && !User.IsInRole(Role.SuperAdmin))
  148. {
  149. return Forbid();
  150. }
  151. return Ok(userDto);
  152. }
  153. [HttpGet("{id}")]
  154. public IActionResult GetByAgencyId(int id)
  155. {
  156. var agency = _Repo.GetByAgencyId(id);
  157. var agencyDto = _mapper.Map<AgencyDto>(agency);
  158. if (agency == null)
  159. {
  160. return NotFound();
  161. }
  162. var currentAgencyId = int.Parse(User.Identity.Name);
  163. if (id != currentAgencyId && !User.IsInRole(Role.Agency))
  164. {
  165. return Forbid();
  166. }
  167. return Ok(agencyDto);
  168. }
  169. [Authorize(Roles = Role.SuperAdmin)]
  170. [HttpDelete("{id}")]
  171. public IActionResult Delete(User user)
  172. {
  173. _Repo.Delete(user.Id);
  174. return Ok();
  175. }
  176. [Authorize(Roles = Role.SuperAdmin)]
  177. [HttpDelete("{id}")]
  178. public IActionResult DeleteAgency(Agency agency)
  179. {
  180. _Repo.DeleteAgency(agency.Id);
  181. return Ok();
  182. }
  183. }
  184. }