Project

General

Profile

1
package eu.dnetlib.repo.manager.controllers;
2

    
3
import eu.dnetlib.domain.data.Repository;
4
import eu.dnetlib.domain.data.RepositoryInterface;
5
import eu.dnetlib.repo.manager.domain.*;
6
import eu.dnetlib.repo.manager.domain.dto.User;
7
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
8
import eu.dnetlib.repo.manager.service.RepositoryServiceImpl;
9
import eu.dnetlib.repo.manager.service.security.AuthorizationService;
10
import eu.dnetlib.repo.manager.utils.JsonUtils;
11
import io.swagger.annotations.Api;
12
import org.apache.log4j.Logger;
13
import org.json.JSONException;
14
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.http.HttpStatus;
17
import org.springframework.http.MediaType;
18
import org.springframework.http.ResponseEntity;
19
import org.springframework.security.access.prepost.PostAuthorize;
20
import org.springframework.security.access.prepost.PreAuthorize;
21
import org.springframework.security.core.Authentication;
22
import org.springframework.security.core.context.SecurityContextHolder;
23
import org.springframework.web.bind.annotation.*;
24

    
25
import javax.ws.rs.core.Response;
26
import java.io.IOException;
27
import java.util.List;
28
import java.util.Map;
29

    
30
@RestController
31
@RequestMapping(value = "/repository")
32
@Api(description = "Repository API", tags = {"repository"})
33
public class RepositoryController {
34

    
35
    private static final Logger logger = Logger.getLogger(RepositoryController.class);
36

    
37
    private final RepositoryServiceImpl repositoryService; //TODO: why not RepositoryService??
38
    private final AuthorizationService authorizationService;
39

    
40
    @Autowired
41
    RepositoryController(RepositoryServiceImpl repositoryService,
42
                         AuthorizationService authorizationService) {
43
        this.repositoryService = repositoryService;
44
        this.authorizationService = authorizationService;
45
    }
46

    
47

    
48
    @RequestMapping(value = "/getCountries", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
49
    @ResponseBody
50
    public Country[] getCountries() {
51
        return repositoryService.getCountries();
52
    }
53

    
54
    @RequestMapping(value = "/getRepositoriesByCountry/{country}/{mode}", method = RequestMethod.GET,
55
            produces = MediaType.APPLICATION_JSON_VALUE)
56
    @ResponseBody
57
    public List<RepositorySnippet> getRepositoriesByCountry(@PathVariable("country") String country,
58
                                                            @PathVariable("mode") String mode,
59
                                                            @RequestParam(value = "managed", required = false) Boolean managed) throws JSONException, IOException {
60
        return repositoryService.getRepositoriesByCountry(country, mode, managed);
61
    }
62

    
63
    @RequestMapping(value = "/getRepositoriesOfUser/{page}/{size}", method = RequestMethod.GET,
64
            produces = MediaType.APPLICATION_JSON_VALUE)
65
    @ResponseBody
66
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
67
    public List<RepositorySnippet> getRepositoriesSnippetOfUser(
68
            @PathVariable("page") String page,
69
            @PathVariable("size") String size) throws JSONException, IOException {
70
        return repositoryService.getRepositoriesSnippetOfUser(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
71
    }
72

    
73
    @RequestMapping(value = "/user/repositories/{page}/{size}", method = RequestMethod.GET,
74
            produces = MediaType.APPLICATION_JSON_VALUE)
75
    @ResponseBody
76
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
77
    public List<Repository> getRepositoriesOfUser(
78
            @PathVariable("page") String page,
79
            @PathVariable("size") String size) throws JSONException, IOException {
80
        return repositoryService.getRepositoriesOfUser(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
81
    }
82

    
83
    @RequestMapping(value = "/searchRegisteredRepositories/{page}/{size}", method = RequestMethod.GET,
84
            produces = MediaType.APPLICATION_JSON_VALUE)
85
    @ResponseBody
86
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')")
87
    public List<RepositorySnippet> searchRegisteredRepositories(@RequestParam(name = "country", required = false) String country,
88
                                                                @RequestParam(name = "typology", required = false) String typology,
89
                                                                @RequestParam(name = "englishName", required = false) String englishName,
90
                                                                @RequestParam(name = "officialName", required = false) String officialName,
91
                                                                @RequestParam("requestSortBy") String requestSortBy,
92
                                                                @RequestParam("order") String order,
93
                                                                @PathVariable("page") int page,
94
                                                                @PathVariable("size") int pageSize) throws Exception {
95

    
96
        return repositoryService.searchRegisteredRepositories(country, typology, englishName, officialName, requestSortBy, order, page, pageSize);
97
    }
98

    
99

    
100
    @RequestMapping(value = "/getRepositoryById/{id}", method = RequestMethod.GET,
101
            produces = MediaType.APPLICATION_JSON_VALUE)
102
    @ResponseBody
103
    @PostAuthorize("hasAnyRole('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id) or (returnObject.registeredBy=='null' and hasAuthority('REGISTERED_USER'))")
104
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException, ResourceNotFoundException {
105
        Repository repo = repositoryService.getRepositoryById(id);
106

    
107
        if (repo != null)
108
            logger.info("Returning repository " + repo.getId() + " registered by " + repo.getRegisteredBy());
109
        else
110
            logger.info("Requested repository " + id + " not found");
111
        return repo;
112
    }
113

    
114
    @RequestMapping(value = "/getRepositoryAggregations/{id}", method = RequestMethod.GET,
115
            produces = MediaType.APPLICATION_JSON_VALUE)
116
    @ResponseBody
117
    public List<AggregationDetails> getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
118
        return repositoryService.getRepositoryAggregations(id, 0, 20);
119
    }
120

    
121
    @RequestMapping(value = "/getRepositoryAggregationsByYear/{id}", method = RequestMethod.GET,
122
            produces = MediaType.APPLICATION_JSON_VALUE)
123
    @ResponseBody
124
    public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(@PathVariable("id") String id) throws JSONException {
125
        return repositoryService.getRepositoryAggregationsByYear(id);
126
    }
127

    
128
    @RequestMapping(value = "/getRepositoriesByName/{name:.+}/{page}/{size}/", method = RequestMethod.GET,
129
            produces = MediaType.APPLICATION_JSON_VALUE)
130
    @ResponseBody
131
    public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
132
                                                  @PathVariable("page") String page,
133
                                                  @PathVariable("size") String size) throws JSONException {
134
        return repositoryService.getRepositoriesByName(name, page, size);
135
    }
136

    
137
    @RequestMapping(value = "/getRepositoryInterface/{id}", method = RequestMethod.GET,
138
            produces = MediaType.APPLICATION_JSON_VALUE)
139
    @ResponseBody
140
    @PostAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id) or (@repositoryService.getRepositoryById(#id).registeredBy=='null' and hasAuthority('REGISTERED_USER'))")
141
    public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
142
        return repositoryService.getRepositoryInterface(id);
143
    }
144

    
145
    @RequestMapping(value = "/addRepository", method = RequestMethod.POST,
146
            consumes = MediaType.APPLICATION_JSON_VALUE)
147
    @ResponseBody
148
//    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or (hasAuthority(@authorizationService.convertRepoIdToRoleId(#repository.id)) or hasAuthority(@authorizationService.convertRepoIdToRoleId(returnObject.id)))")
149
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER')")
150
    public Repository addRepository(@RequestParam("datatype") String datatype,
151
                                    @RequestBody Repository repository) throws Exception {
152

    
153
        return repositoryService.addRepository(datatype, repository);
154
    }
155

    
156
    @RequestMapping(value = "/getDnetCountries", method = RequestMethod.GET,
157
            produces = MediaType.APPLICATION_JSON_VALUE)
158
    @ResponseBody
159
    public List<String> getDnetCountries() {
160
        return repositoryService.getDnetCountries();
161
    }
162

    
163
    @RequestMapping(value = "/getTypologies", method = RequestMethod.GET,
164
            produces = MediaType.APPLICATION_JSON_VALUE)
165
    @ResponseBody
166
    public List<String> getTypologies() {
167
        return repositoryService.getTypologies();
168
    }
169

    
170
    @RequestMapping(value = "/getTimezones", method = RequestMethod.GET,
171
            produces = MediaType.APPLICATION_JSON_VALUE)
172
    @ResponseBody
173
    public List<Timezone> getTimezones() {
174
        return repositoryService.getTimezones();
175
    }
176

    
177
    @RequestMapping(value = "/updateRepository", method = RequestMethod.POST,
178
            consumes = MediaType.APPLICATION_JSON_VALUE)
179
    @ResponseBody
180
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#repository.id)")
181
    public Repository updateRepository(@RequestBody Repository repository, Authentication authentication) throws Exception {
182
        return repositoryService.updateRepository(repository, authentication);
183
    }
184

    
185
    @RequestMapping(value = "/deleteInterface/", method = RequestMethod.DELETE)
186
    @PreAuthorize("@authorizationService.isMemberOf(#id)")
187
    public void deleteRepositoryInterface(@RequestParam("id") String id,
188
                                          @RequestParam("registeredBy") String registeredBy) {
189
        repositoryService.deleteRepositoryInterface(id, registeredBy);
190
    }
191

    
192
    @RequestMapping(value = "/addInterface", method = RequestMethod.POST,
193
            consumes = MediaType.APPLICATION_JSON_VALUE)
194
    @ResponseBody
195
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
196
    public RepositoryInterface addRepositoryInterface(@RequestParam("datatype") String datatype,
197
                                                      @RequestParam("id") String id,
198
                                                      @RequestParam("registeredBy") String registeredBy,
199
                                                      @RequestParam(value = "comment", required = false) String comment,
200
                                                      @RequestBody RepositoryInterface repositoryInterface) throws Exception {
201
        return repositoryService.addRepositoryInterface(datatype, id, registeredBy, comment, repositoryInterface);
202
    }
203

    
204
    @RequestMapping(value = "/getUrlsOfUserRepos/{page}/{size}/", method = RequestMethod.GET,
205
            produces = MediaType.APPLICATION_JSON_VALUE)
206
    @ResponseBody
207
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
208
    public List<String> getUrlsOfUserRepos(@PathVariable("page") String page, @PathVariable("size") String size) {
209
        return repositoryService.getUrlsOfUserRepos(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
210
    }
211

    
212
    @RequestMapping(value = "/getDatasourceVocabularies/{mode}", method = RequestMethod.GET,
213
            produces = MediaType.APPLICATION_JSON_VALUE)
214
    @ResponseBody
215
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
216
        return repositoryService.getDatasourceVocabularies(mode);
217
    }
218

    
219
    @RequestMapping(value = "/getCompatibilityClasses/{mode}", method = RequestMethod.GET,
220
            produces = MediaType.APPLICATION_JSON_VALUE)
221
    @ResponseBody
222
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode) {
223

    
224
        return repositoryService.getCompatibilityClasses(mode);
225
    }
226

    
227
    @RequestMapping(value = "/getDatasourceClasses/{mode}", method = RequestMethod.GET,
228
            produces = MediaType.APPLICATION_JSON_VALUE)
229
    @ResponseBody
230
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode) {
231
        return repositoryService.getDatasourceClasses(mode);
232
    }
233

    
234
    @RequestMapping(value = "/getMetricsInfoForRepository/{id}", method = RequestMethod.GET,
235
            produces = MediaType.APPLICATION_JSON_VALUE)
236
    @ResponseBody
237
    public MetricsInfo getMetricsInfoForRepository(@PathVariable("id") String id) throws RepositoryServiceException {
238
        return repositoryService.getMetricsInfoForRepository(id);
239
    }
240

    
241
    @RequestMapping(value = "/getListLatestUpdate/{mode}", method = RequestMethod.GET,
242
            produces = MediaType.APPLICATION_JSON_VALUE)
243
    @ResponseBody
244
    public Map<String, String> getListLatestUpdate(@PathVariable("mode") String mode) throws JSONException {
245
        return repositoryService.getListLatestUpdate(mode);
246
    }
247

    
248
    @RequestMapping(value = "/updateRepositoryInterface", method = RequestMethod.POST,
249
            consumes = MediaType.APPLICATION_JSON_VALUE)
250
    @ResponseBody
251
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
252
    public RepositoryInterface updateRepositoryInterface(@RequestParam("id") String id,
253
                                                         @RequestParam("registeredBy") String registeredBy,
254
                                                         @RequestParam(value = "comment", required = false) String comment,
255
                                                         @RequestBody RepositoryInterface repositoryInterface) throws Exception {
256
        return repositoryService.updateRepositoryInterface(id, registeredBy, comment, repositoryInterface);
257
    }
258

    
259

    
260
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
261
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
262

    
263
    /**
264
     * Get all the admins of the repository
265
     */
266
    @RequestMapping(method = RequestMethod.GET, path = "{id}/admins")
267
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
268
    public ResponseEntity<List<User>> getAdminsOfARepo(@PathVariable("id") String id) {
269
        return new ResponseEntity<>(authorizationService.getAdminsOfRepo(id), HttpStatus.OK);
270
    }
271

    
272
    /**
273
     * Subscribe to repo by email
274
     */
275
    @RequestMapping(method = RequestMethod.POST, path = "{id}/admins")
276
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
277
    public Response subscribeByEmail(@PathVariable("id") String id, @RequestBody String email) throws ResourceNotFoundException {
278
        authorizationService.addAdmin(id, email);
279
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(javax.ws.rs.core.MediaType.APPLICATION_JSON).build();
280
    }
281

    
282
    /**
283
     * Unsubscribe from repo by email
284
     */
285
    @RequestMapping(method = RequestMethod.DELETE, path = "{id}/admins/{email:.+}")
286
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
287
    public ResponseEntity<Void> unsubscribeByEmail(@PathVariable("id") String id, @PathVariable("email") String email) throws ResourceNotFoundException {
288
        authorizationService.removeAdmin(id, email);
289
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
290
    }
291
}
(6-6/12)