Skip to content

Commit 4a60d00

Browse files
authored
bug/many2one_relationship_dropdown (jhipster#1194)
* Add GetAllPublicUser function on UserService & create PublicUsersController.cs.ejs * change IUserService.cs.ejs interface * rename controller name * update publicuserscontroller - delete getAuthorize * add TU Controller Test * update TU Controller Test * update TU Controller Test * rename test * update userService * add querys * changes on controller * changes on controllers * change file.js * change file.js - add getallpublicuser references * change file.js - delete prettier space * change file.js - update reference * change UserGetAllPublicUsersQueryHandler (interface implementation) * change IsNullOrEmpty in functions * remove unused references & remove includes (user role & role) on public user queries & user service * add references * add references * change getAllPublicUsers function who return userDto now * add references * add references * remove unused fields (mailservice and user manager) * remove unused fields (mailservice and user manager)
1 parent 7fc335c commit 4a60d00

File tree

8 files changed

+303
-2
lines changed

8 files changed

+303
-2
lines changed

generators/server/files.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -980,6 +980,16 @@ const serverFiles = {
980980
},
981981
],
982982
},
983+
{
984+
condition: generator => generator.authenticationType === 'jwt' && generator.applicationType !== 'microservice',
985+
path: SERVER_SRC_DIR,
986+
templates: [
987+
{
988+
file: 'Project/Controllers/PublicUsersController.cs',
989+
renameTo: generator => `${generator.mainProjectDir}/Controllers/PublicUsersController.cs`,
990+
},
991+
],
992+
},
983993
{
984994
condition: generator =>
985995
generator.authenticationType === 'jwt' && generator.applicationType !== 'microservice' && generator.cqrsEnabled === true,
@@ -1028,6 +1038,16 @@ const serverFiles = {
10281038
file: 'Project.Application/Queries/User/UserGetQuery.cs',
10291039
renameTo: generator => `${generator.pascalizedBaseName}${PROJECT_APPLICATION_SUFFIX}/Queries/User/UserGetQuery.cs`,
10301040
},
1041+
{
1042+
file: 'Project.Application/Queries/User/UserGetAllPublicUsersQuery.cs',
1043+
renameTo: generator =>
1044+
`${generator.pascalizedBaseName}${PROJECT_APPLICATION_SUFFIX}/Queries/User/UserGetAllPublicUsersQuery.cs`,
1045+
},
1046+
{
1047+
file: 'Project.Application/Queries/User/UserGetAllPublicUsersQueryHandler.cs',
1048+
renameTo: generator =>
1049+
`${generator.pascalizedBaseName}${PROJECT_APPLICATION_SUFFIX}/Queries/User/UserGetAllPublicUsersQueryHandler.cs`,
1050+
},
10311051
{
10321052
file: 'Project.Application/Queries/User/UserGetQueryHandler.cs',
10331053
renameTo: generator =>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<%#
2+
Copyright 2019-2022 the original author or authors from the JHipster project.
3+
4+
This file is part of the JHipster project, see https://www.jhipster.tech/
5+
for more information.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
-%>
19+
using <%= namespace %>.Dto;
20+
using Microsoft.AspNetCore.Http;
21+
using System.Collections.Generic;
22+
using JHipsterNet.Core.Pagination;
23+
using MediatR;
24+
25+
namespace <%= namespace %>.Application.Queries;
26+
27+
public class UserGetAllPublicUsersQuery : IRequest<(IHeaderDictionary, IEnumerable<UserDto>)>
28+
{
29+
public IPageable Page { get; set; }
30+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<%#
2+
Copyright 2019-2022 the original author or authors from the JHipster project.
3+
4+
This file is part of the JHipster project, see https://www.jhipster.tech/
5+
for more information.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
-%>
19+
using AutoMapper;
20+
using System.Linq;
21+
using <%= namespace %>.Domain.Entities;
22+
using <%= namespace %>.Dto;
23+
using <%= namespace %>.Domain.Services.Interfaces;
24+
using <%= namespace %>.Infrastructure.Web.Rest.Utilities;
25+
using MediatR;
26+
using System.Threading;
27+
using System.Threading.Tasks;
28+
using Microsoft.AspNetCore.Identity;
29+
using Microsoft.EntityFrameworkCore;
30+
using Microsoft.AspNetCore.Http;
31+
using System.Collections.Generic;
32+
using JHipsterNet.Core.Pagination.Extensions;
33+
<%_ if (databaseType === 'mongodb') { _%>
34+
using MongoDB.Driver.Linq;
35+
<%_ } _%>
36+
37+
namespace <%= namespace %>.Application.Queries;
38+
39+
public class UserGetAllPublicUsersQueryHandler : IRequestHandler<UserGetAllPublicUsersQuery, (IHeaderDictionary, IEnumerable<UserDto>)>
40+
{
41+
private readonly UserManager<User> _userManager;
42+
private readonly IMapper _mapper;
43+
44+
public UserGetAllPublicUsersQueryHandler(UserManager<User> userManager, IUserService userService,
45+
IMapper mapper, IMailService mailService)
46+
{
47+
_userManager = userManager;
48+
_mapper = mapper;
49+
}
50+
51+
public async Task<(IHeaderDictionary, IEnumerable<UserDto>)> Handle(UserGetAllPublicUsersQuery request, CancellationToken cancellationToken)
52+
{
53+
<%_ if (databaseType === 'mongodb') { _%>
54+
var page = await Task.FromResult((_userManager.Users as IMongoQueryable<User>)
55+
.Where(it => it.Activated == true && !string.IsNullOrEmpty(it.Id))
56+
.UsePageable(request.Page));
57+
<%_ } else { _%>
58+
var page = await _userManager.Users
59+
.Where(it => it.Activated == true && !string.IsNullOrEmpty(it.Id))
60+
.UsePageableAsync(request.Page);
61+
<%_ } _%>
62+
var userDtos = page.Content.Select(user => _mapper.Map<UserDto>(user));
63+
var headers = page.GeneratePaginationHttpHeaders();
64+
return (headers, userDtos);
65+
}
66+
}

generators/server/templates/dotnetcore/src/Project.Domain.Services/UserService.cs.ejs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,20 @@ public class UserService : IUserService
9191
<%_ } _%>
9292
}
9393

94+
public async Task<IPage<User>> GetAllPublicUsers(IPageable pageable)
95+
{
96+
<%_ if (databaseType === 'mongodb') { _%>
97+
IPage<User> users = await (_userManager.Users as IMongoQueryable<User>)
98+
.Where(it => it.Activated == true && !string.IsNullOrEmpty(it.Id))
99+
.UsePageableAsync(pageable);
100+
return users;
101+
<%_ } else { _%>
102+
return await _userManager.Users
103+
.Where(it => it.Activated == true && !string.IsNullOrEmpty(it.Id))
104+
.UsePageableAsync(pageable);
105+
<%_ } _%>
106+
}
107+
94108
public async Task<User> GetByLogin(string login)
95109
{
96110
<%_ if (databaseType === 'mongodb') { _%>
@@ -250,6 +264,7 @@ public class UserService : IUserService
250264
return await GetUserWithUserRolesByName(userName);
251265
}
252266

267+
253268
public virtual IEnumerable<string> GetAuthorities()
254269
{
255270
return _roleManager.Roles.Select(it => it.Name).AsQueryable();

generators/server/templates/dotnetcore/src/Project.Domain/Services/Interfaces/IUserService.cs.ejs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,5 @@ public interface IUserService
3838
Task<User> RegisterUser(User userToRegister, string password);
3939
Task UpdateUser(string firstName, string lastName, string email, string langKey, string imageUrl);
4040
Task<User> GetUserWithUserRoles();
41+
Task<IPage<User>> GetAllPublicUsers(IPageable pageable);
4142
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
<%#
2+
Copyright 2019-2022 the original author or authors from the JHipster project.
3+
This file is part of the JHipster project, see https://www.jhipster.tech/
4+
for more information.
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
-%>
15+
<%_ if (cqrsEnabled) { _%>
16+
using MediatR;
17+
<%_ } _%>
18+
using AutoMapper;
19+
using System.Collections.Generic;
20+
using System.Linq;
21+
using System.Threading.Tasks;
22+
using JHipsterNet.Core.Pagination;
23+
using JHipsterNet.Core.Pagination.Extensions;
24+
using <%= namespace %>.Domain.Entities;
25+
using <%= namespace %>.Security;
26+
using <%= namespace %>.Domain.Services.Interfaces;
27+
using <%= namespace %>.Dto;
28+
using <%= namespace %>.Web.Extensions;
29+
using <%= namespace %>.Web.Filters;
30+
using <%= namespace %>.Web.Rest.Problems;
31+
using <%= namespace %>.Web.Rest.Utilities;
32+
using <%= namespace %>.Crosscutting.Constants;
33+
using <%= namespace %>.Crosscutting.Exceptions;
34+
using <%= namespace %>.Infrastructure.Web.Rest.Utilities;
35+
<%_ if (cqrsEnabled) { _%>
36+
using <%= namespace %>.Application.Queries;
37+
using <%= namespace %>.Application.Commands;
38+
<%_ } _%>
39+
using Microsoft.AspNetCore.Identity;
40+
using Microsoft.AspNetCore.Authorization;
41+
using Microsoft.AspNetCore.Mvc;
42+
using Microsoft.Extensions.Logging;
43+
44+
namespace <%= namespace %>.Controllers;
45+
46+
47+
[Route("api/users")]
48+
[ApiController]
49+
public class PublicUsersController : ControllerBase
50+
{
51+
private readonly ILogger<UsersController> _log;
52+
<%_ if (cqrsEnabled) { _%>
53+
private readonly IMediator _mediator;
54+
<%_ } else { _%>
55+
private readonly IMapper _mapper;
56+
private readonly IUserService _userService;
57+
<%_ } _%>
58+
59+
<%_ if (cqrsEnabled) { _%>
60+
public PublicUsersController(ILogger<UsersController> log, IMediator mediator)
61+
{
62+
_log = log;
63+
_mediator = mediator;
64+
}
65+
<%_ } else { _%>
66+
public PublicUsersController(ILogger<UsersController> log, IUserService userService, IMapper mapper)
67+
{
68+
_log = log;
69+
_userService = userService;
70+
_mapper = mapper;
71+
}
72+
<%_ } _%>
73+
74+
75+
[HttpGet]
76+
public async Task<ActionResult<IEnumerable<UserDto>>> GetAllPublicUsers(IPageable pageable)
77+
{
78+
_log.LogDebug("REST request to get a page of Users");
79+
<%_ if (cqrsEnabled) { _%>
80+
(var headers, var userDtos) = await _mediator.Send(new UserGetAllPublicUsersQuery { Page = pageable });
81+
<%_ } else { _%>
82+
var page = await _userService.GetAllPublicUsers(pageable);
83+
var userDtos = page.Content.Select(user => _mapper.Map<UserDto>(user));
84+
var headers = page.GeneratePaginationHttpHeaders();
85+
<%_ } _%>
86+
return Ok(userDtos).WithHeaders(headers);
87+
}
88+
89+
}

generators/server/templates/dotnetcore/src/Project/Controllers/UsersController.cs.ejs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,6 @@ public class UsersController : ControllerBase
9393
throw new LoginAlreadyUsedException();
9494
if (await _userManager.FindByEmailAsync(userDto.Email.ToLowerInvariant()) != null)
9595
throw new EmailAlreadyUsedException();
96-
9796
var newUser = await _userService.CreateUser(_mapper.Map<User>(userDto));
9897
await _mailService.SendCreationEmail(newUser);
9998
<%_ } _%>
@@ -113,7 +112,6 @@ public class UsersController : ControllerBase
113112
if (existingUser != null && !existingUser.Id.Equals(userDto.Id)) throw new EmailAlreadyUsedException();
114113
existingUser = await _userManager.FindByNameAsync(userDto.Login);
115114
if (existingUser != null && !existingUser.Id.Equals(userDto.Id)) throw new LoginAlreadyUsedException();
116-
117115
var updatedUser = await _userService.UpdateUser(_mapper.Map<User>(userDto));
118116
<%_ } _%>
119117

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
<%#
2+
Copyright 2019-2022 the original author or authors from the JHipster project.
3+
This file is part of the JHipster project, see https://www.jhipster.tech/
4+
for more information.
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
-%>
15+
using FluentAssertions;
16+
using FluentAssertions.Json;
17+
using <%= namespace %>.Domain.Entities;
18+
using <%= namespace %>.Dto;
19+
using <%= namespace %>.Dto.Authentication;
20+
using <%= namespace %>.Test.Setup;
21+
using Microsoft.AspNetCore.Identity;
22+
using Newtonsoft.Json.Linq;
23+
using System.Linq;
24+
using System.Net;
25+
using System.Net.Http;
26+
using System.Threading.Tasks;
27+
using Xunit;
28+
29+
namespace <%= namespace %>.Test.Controllers;
30+
31+
<%_ if (databaseType === 'mongodb') { _%>
32+
[Collection("MongoDB")]
33+
<%_ } _%>
34+
public class PublicUsersControllerTest
35+
{
36+
public PublicUsersControllerTest()
37+
{
38+
_factory = new AppWebApplicationFactory<TestStartup>();
39+
_client = _factory.CreateClient();
40+
41+
_userManager = _factory.GetRequiredService<UserManager<User>>();
42+
_passwordHasher = _userManager.PasswordHasher;
43+
44+
var config = new MapperConfiguration(cfg =>
45+
{
46+
cfg.AddProfile(new AutoMapperProfile());
47+
});
48+
49+
_mapper = config.CreateMapper();
50+
51+
InitTest();
52+
}
53+
54+
private readonly AppWebApplicationFactory<TestStartup> _factory;
55+
private readonly HttpClient _client;
56+
57+
private readonly UserManager<User> _userManager;
58+
private readonly IPasswordHasher<User> _passwordHasher;
59+
60+
61+
[Fact]
62+
public async Task GetAllUsersTest()
63+
{
64+
// Initialize the database
65+
await _userManager.CreateAsync(_user);
66+
67+
// Get all authenticated users
68+
var response = await _client.GetAsync("/api/users");
69+
response.StatusCode.Should().Be(HttpStatusCode.OK);
70+
71+
var json = JToken.Parse(await response.Content.ReadAsStringAsync());
72+
json.SelectTokens("$.[*].Id).Should().NotBeNull();
73+
json.SelectTokens("$.[*].Activated").Should().Be(true);
74+
json.SelectTokens("$.[*].login").Should().Contain(DefaultLogin);
75+
json.SelectTokens("$.[*].firstName").Should().Contain(DefaultFirstname);
76+
json.SelectTokens("$.[*].lastName").Should().Contain(DefaultLastname);
77+
json.SelectTokens("$.[*].email").Should().Contain(DefaultEmail);
78+
json.SelectTokens("$.[*].imageUrl").Should().Contain(DefaultImageurl);
79+
json.SelectTokens("$.[*].langKey").Should().Contain(DefaultLangkey);
80+
81+
}
82+
}

0 commit comments

Comments
 (0)