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.RepositoryTerms;
7
import eu.dnetlib.repo.manager.domain.dto.User;
8
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
9
import eu.dnetlib.repo.manager.service.RepositoryService;
10
import eu.dnetlib.repo.manager.service.security.AuthorizationService;
11
import eu.dnetlib.repo.manager.utils.JsonUtils;
12
import io.swagger.annotations.Api;
13
import org.apache.log4j.Logger;
14
import org.json.JSONException;
15
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
16
import org.springframework.beans.factory.annotation.Autowired;
17
import org.springframework.http.HttpStatus;
18
import org.springframework.http.MediaType;
19
import org.springframework.http.ResponseEntity;
20
import org.springframework.security.access.prepost.PostAuthorize;
21
import org.springframework.security.access.prepost.PreAuthorize;
22
import org.springframework.security.core.Authentication;
23
import org.springframework.security.core.context.SecurityContextHolder;
24
import org.springframework.web.bind.annotation.*;
25

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

    
32
@RestController
33
@RequestMapping(value = "/repositories")
34
@Api(description = "Repository API", tags = {"repositories"})
35
public class RepositoryController {
36

    
37
    private static final Logger logger = Logger.getLogger(RepositoryController.class);
38

    
39
    private final RepositoryService repositoryService;
40
    private final AuthorizationService authorizationService;
41

    
42
    @Autowired
43
    RepositoryController(RepositoryService repositoryService,
44
                         AuthorizationService authorizationService) {
45
        this.repositoryService = repositoryService;
46
        this.authorizationService = authorizationService;
47
    }
48

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

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

    
64
    @RequestMapping(value = "/snippets/user", method = RequestMethod.GET,
65
            produces = MediaType.APPLICATION_JSON_VALUE)
66
    @ResponseBody
67
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
68
    public List<RepositorySnippet> getRepositoriesSnippetsOfUser() throws Exception {
69
        return repositoryService.getRepositoriesSnippetsOfUser("0", "100"); // FIXME
70
    }
71

    
72
    @RequestMapping(value = "/terms", method = RequestMethod.POST,
73
            produces = MediaType.APPLICATION_JSON_VALUE)
74
    @ResponseBody
75
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
76
    public void updateRepositoriesTerms(@RequestBody List<RepositoryTerms> repositoriesTerms) throws Exception {
77
        Date date = new Date();
78
        if (repositoriesTerms != null) {
79
        for (RepositoryTerms terms : repositoriesTerms) {
80
                Repository repository = repositoryService.getRepositoryById(terms.getId());
81
                repository.setConsentTermsOfUse(terms.getConsentTermsOfUse());
82
                repository.setFullTextDownload(terms.getFullTextDownload());
83
                repository.setConsentTermsOfUseDate(date);
84
                repositoryService.updateRepository(repository, SecurityContextHolder.getContext().getAuthentication());
85
            }
86
        }
87
    }
88

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

    
102
        return repositoryService.searchRegisteredRepositories(country, typology, englishName, officialName, requestSortBy, order, page, pageSize);
103
    }
104

    
105
    @RequestMapping(value = "/getRepositoryById/{id}", method = RequestMethod.GET,
106
            produces = MediaType.APPLICATION_JSON_VALUE)
107
    @ResponseBody
108
    @PostAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id) or (returnObject.registeredBy=='null' and hasAuthority('REGISTERED_USER'))")
109
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException, ResourceNotFoundException {
110
        Repository repo = repositoryService.getRepositoryById(id);
111

    
112
        if (repo != null)
113
            logger.info("Returning repository " + repo.getId() + " registered by " + repo.getRegisteredBy());
114
        else
115
            logger.info("Requested repository " + id + " not found");
116
        return repo;
117
    }
118

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

    
126
    @RequestMapping(value = "/getRepositoryAggregationsByYear/{id}", method = RequestMethod.GET,
127
            produces = MediaType.APPLICATION_JSON_VALUE)
128
    @ResponseBody
129
    public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(@PathVariable("id") String id) throws JSONException {
130
        return repositoryService.getRepositoryAggregationsByYear(id);
131
    }
132

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

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

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

    
158
        return repositoryService.addRepository(datatype, repository);
159
    }
160

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

    
168
    @RequestMapping(value = "/getTypologies", method = RequestMethod.GET,
169
            produces = MediaType.APPLICATION_JSON_VALUE)
170
    @ResponseBody
171
    public List<String> getTypologies() {
172
        return repositoryService.getTypologies();
173
    }
174

    
175
    @RequestMapping(value = "/getTimezones", method = RequestMethod.GET,
176
            produces = MediaType.APPLICATION_JSON_VALUE)
177
    @ResponseBody
178
    public List<Timezone> getTimezones() {
179
        return repositoryService.getTimezones();
180
    }
181

    
182
    @RequestMapping(value = "/updateRepository", method = RequestMethod.POST,
183
            consumes = MediaType.APPLICATION_JSON_VALUE)
184
    @ResponseBody
185
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOfInterface(#repository.id)")
186
    public Repository updateRepository(@RequestBody Repository repository, Authentication authentication) throws Exception {
187
        return repositoryService.updateRepository(repository, authentication);
188
    }
189

    
190
    @RequestMapping(value = "/deleteInterface/", method = RequestMethod.DELETE)
191
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOfInterface(#id)")
192
    public void deleteRepositoryInterface(@RequestParam("id") String id,
193
                                          @RequestParam("registeredBy") String registeredBy) {
194
        repositoryService.deleteRepositoryInterface(id, registeredBy);
195
    }
196

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

    
209
    @RequestMapping(value = "/updateRepositoryInterface", method = RequestMethod.POST,
210
            consumes = MediaType.APPLICATION_JSON_VALUE)
211
    @ResponseBody
212
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
213
    public RepositoryInterface updateRepositoryInterface(@RequestParam("repoId") String id,
214
                                                         @RequestParam("registeredBy") String registeredBy,
215
                                                         @RequestParam(value = "comment", required = false) String comment,
216
                                                         @RequestBody RepositoryInterface repositoryInterface) throws Exception {
217
        return repositoryService.updateRepositoryInterface(id, registeredBy, comment, repositoryInterface);
218
    }
219

    
220
    @RequestMapping(value = "/getUrlsOfUserRepos/{page}/{size}/", method = RequestMethod.GET,
221
            produces = MediaType.APPLICATION_JSON_VALUE)
222
    @ResponseBody
223
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
224
    public List<String> getUrlsOfUserRepos(@PathVariable("page") String page, @PathVariable("size") String size) {
225
        return repositoryService.getUrlsOfUserRepos(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
226
    }
227

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

    
235
    @RequestMapping(value = "/getCompatibilityClasses/{mode}", method = RequestMethod.GET,
236
            produces = MediaType.APPLICATION_JSON_VALUE)
237
    @ResponseBody
238
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode) {
239

    
240
        return repositoryService.getCompatibilityClasses(mode);
241
    }
242

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

    
250
    @RequestMapping(value = "/getMetricsInfoForRepository/{id}", method = RequestMethod.GET,
251
            produces = MediaType.APPLICATION_JSON_VALUE)
252
    @ResponseBody
253
    public MetricsInfo getMetricsInfoForRepository(@PathVariable("id") String id) throws RepositoryServiceException {
254
        return repositoryService.getMetricsInfoForRepository(id);
255
    }
256

    
257
    @RequestMapping(value = "/getListLatestUpdate/{mode}", method = RequestMethod.GET,
258
            produces = MediaType.APPLICATION_JSON_VALUE)
259
    @ResponseBody
260
    public Map<String, String> getListLatestUpdate(@PathVariable("mode") String mode) throws JSONException {
261
        return repositoryService.getListLatestUpdate(mode);
262
    }
263

    
264
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
265
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
266

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

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

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