Add a admin user and the "role" information into the token.

This commit is contained in:
Sébastien André
2021-03-17 14:06:51 +01:00
parent 229fe5d3a5
commit ee3a1273da
4 changed files with 28 additions and 9 deletions

View File

@@ -13,5 +13,7 @@
public string Login { get; set; }
public string Password { get; set; }
public bool IsAdmin { get; set; }
}
}

View File

@@ -12,11 +12,13 @@ namespace skydiveLogs_api.DomainBusiness
{
public InitDbService(IAircraftService aircraftService,
IJumpTypeService jumpTypeService,
IDropZoneService dropZoneService)
IDropZoneService dropZoneService,
IUserService userService)
{
_aircraftService = aircraftService;
_jumpTypeService = jumpTypeService;
_dropZoneService = dropZoneService;
_userService = userService;
}
public void GenerateDb()
@@ -24,6 +26,7 @@ namespace skydiveLogs_api.DomainBusiness
LoadAircrafts();
LoadDropZones();
LoadJumpTypes();
AddAdmin();
}
private void LoadDropZones()
@@ -74,10 +77,23 @@ namespace skydiveLogs_api.DomainBusiness
}
}
private void AddAdmin()
{
var adminUser = new User
{
Login = "administrator",
Password = "logsadmin"
};
_userService.AddNewUser(adminUser);
}
private readonly IAircraftService _aircraftService;
private readonly IJumpTypeService _jumpTypeService;
private readonly IDropZoneService _dropZoneService;
private readonly IUserService _userService;
}
}

View File

@@ -35,8 +35,7 @@ namespace skydiveLogs_api.DomainBusiness
if (foundUser == null)
{
_userRepository.Add(newUser);
result = true;
result = _userRepository.Add(newUser);
}
return result;

View File

@@ -55,9 +55,9 @@ namespace skydiveLogs_api.Controllers
}
else
{
foundUser.Password = null;
var resp = _mapper.Map<UserResp>(foundUser);
resp.Token = CreateToken(resp);
var userRole = foundUser.IsAdmin ? "admin" : string.Empty;
resp.Token = CreateToken(resp, userRole);
result = Ok(resp);
}
@@ -80,9 +80,9 @@ namespace skydiveLogs_api.Controllers
}
else
{
newUser.Password = null;
var resp = _mapper.Map<UserResp>(newUser);
resp.Token = CreateToken(resp);
var userRole = newUser.IsAdmin ? "admin" : string.Empty;
resp.Token = CreateToken(resp, userRole);
result = Ok(resp);
}
@@ -90,7 +90,8 @@ namespace skydiveLogs_api.Controllers
return result;
}
private string CreateToken(UserResp foundUser)
private string CreateToken(UserResp foundUser,
string role)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConf.Passphrase));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
@@ -103,7 +104,8 @@ namespace skydiveLogs_api.Controllers
{
new Claim(ClaimTypes.Name, foundUser.Login),
new Claim(ClaimTypes.UserData, foundUser.Id.ToString()),
new Claim(ClaimTypes.Email, foundUser.Email)
new Claim(ClaimTypes.Email, foundUser.Email),
new Claim(ClaimTypes.Role, role)
});
return new JwtSecurityTokenHandler().WriteToken(token);