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.RepositoryService;
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 = "/repositories")
32
@Api(description = "Repository API", tags = {"repositories"})
33
public class RepositoryController {
34

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

    
37
    private final RepositoryService repositoryService;
38
    private final AuthorizationService authorizationService;
39

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

    
47

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

    
71
    @RequestMapping(value = "/searchRegisteredRepositories/{page}/{size}", method = RequestMethod.GET,
72
            produces = MediaType.APPLICATION_JSON_VALUE)
73
    @ResponseBody
74
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')")
75
    public List<RepositorySnippet> searchRegisteredRepositories(@RequestParam(name = "country", required = false) String country,
76
                                                                @RequestParam(name = "typology", required = false) String typology,
77
                                                                @RequestParam(name = "englishName", required = false) String englishName,
78
                                                                @RequestParam(name = "officialName", required = false) String officialName,
79
                                                                @RequestParam("requestSortBy") String requestSortBy,
80
                                                                @RequestParam("order") String order,
81
                                                                @PathVariable("page") int page,
82
                                                                @PathVariable("size") int pageSize) throws Exception {
83

    
84
        return repositoryService.searchRegisteredRepositories(country, typology, englishName, officialName, requestSortBy, order, page, pageSize);
85
    }
86

    
87

    
88
    @RequestMapping(value = "/getRepositoryById/{id}", method = RequestMethod.GET,
89
            produces = MediaType.APPLICATION_JSON_VALUE)
90
    @ResponseBody
91
    @PostAuthorize("hasAnyRole('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id) or (returnObject.registeredBy=='null' and hasAuthority('REGISTERED_USER'))")
92
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException, ResourceNotFoundException {
93
        Repository repo = repositoryService.getRepositoryById(id);
94

    
95
        if (repo != null)
96
            logger.info("Returning repository " + repo.getId() + " registered by " + repo.getRegisteredBy());
97
        else
98
            logger.info("Requested repository " + id + " not found");
99
        return repo;
100
    }
101

    
102
    @RequestMapping(value = "/getRepositoryAggregations/{id}", method = RequestMethod.GET,
103
            produces = MediaType.APPLICATION_JSON_VALUE)
104
    @ResponseBody
105
    public List<AggregationDetails> getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
106
        return repositoryService.getRepositoryAggregations(id, 0, 20);
107
    }
108

    
109
    @RequestMapping(value = "/getRepositoryAggregationsByYear/{id}", method = RequestMethod.GET,
110
            produces = MediaType.APPLICATION_JSON_VALUE)
111
    @ResponseBody
112
    public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(@PathVariable("id") String id) throws JSONException {
113
        return repositoryService.getRepositoryAggregationsByYear(id);
114
    }
115

    
116
    @RequestMapping(value = "/getRepositoriesByName/{name:.+}/{page}/{size}/", method = RequestMethod.GET,
117
            produces = MediaType.APPLICATION_JSON_VALUE)
118
    @ResponseBody
119
    public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
120
                                                  @PathVariable("page") String page,
121
                                                  @PathVariable("size") String size) throws JSONException {
122
        return repositoryService.getRepositoriesByName(name, page, size);
123
    }
124

    
125
    @RequestMapping(value = "/getRepositoryInterface/{id}", method = RequestMethod.GET,
126
            produces = MediaType.APPLICATION_JSON_VALUE)
127
    @ResponseBody
128
    @PostAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id) or (@repositoryService.getRepositoryById(#id).registeredBy=='null' and hasAuthority('REGISTERED_USER'))")
129
    public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
130
        return repositoryService.getRepositoryInterface(id);
131
    }
132

    
133
    @RequestMapping(value = "/addRepository", method = RequestMethod.POST,
134
            consumes = MediaType.APPLICATION_JSON_VALUE)
135
    @ResponseBody
136
//    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or (hasAuthority(@authorizationService.convertRepoIdToRoleId(#repository.id)) or hasAuthority(@authorizationService.convertRepoIdToRoleId(returnObject.id)))")
137
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER')")
138
    public Repository addRepository(@RequestParam("datatype") String datatype,
139
                                    @RequestBody Repository repository) throws Exception {
140

    
141
        return repositoryService.addRepository(datatype, repository);
142
    }
143

    
144
    @RequestMapping(value = "/getDnetCountries", method = RequestMethod.GET,
145
            produces = MediaType.APPLICATION_JSON_VALUE)
146
    @ResponseBody
147
    public List<String> getDnetCountries() {
148
        return repositoryService.getDnetCountries();
149
    }
150

    
151
    @RequestMapping(value = "/getTypologies", method = RequestMethod.GET,
152
            produces = MediaType.APPLICATION_JSON_VALUE)
153
    @ResponseBody
154
    public List<String> getTypologies() {
155
        return repositoryService.getTypologies();
156
    }
157

    
158
    @RequestMapping(value = "/getTimezones", method = RequestMethod.GET,
159
            produces = MediaType.APPLICATION_JSON_VALUE)
160
    @ResponseBody
161
    public List<Timezone> getTimezones() {
162
        return repositoryService.getTimezones();
163
    }
164

    
165
    @RequestMapping(value = "/updateRepository", method = RequestMethod.POST,
166
            consumes = MediaType.APPLICATION_JSON_VALUE)
167
    @ResponseBody
168
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#repository.id)")
169
    public Repository updateRepository(@RequestBody Repository repository, Authentication authentication) throws Exception {
170
        return repositoryService.updateRepository(repository, authentication);
171
    }
172

    
173
    @RequestMapping(value = "/deleteInterface/", method = RequestMethod.DELETE)
174
    @PreAuthorize("@authorizationService.isMemberOf(#id)")
175
    public void deleteRepositoryInterface(@RequestParam("id") String id,
176
                                          @RequestParam("registeredBy") String registeredBy) {
177
        repositoryService.deleteRepositoryInterface(id, registeredBy);
178
    }
179

    
180
    @RequestMapping(value = "/addInterface", method = RequestMethod.POST,
181
            consumes = MediaType.APPLICATION_JSON_VALUE)
182
    @ResponseBody
183
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
184
    public RepositoryInterface addRepositoryInterface(@RequestParam("datatype") String datatype,
185
                                                      @RequestParam("id") String id,
186
                                                      @RequestParam("registeredBy") String registeredBy,
187
                                                      @RequestParam(value = "comment", required = false) String comment,
188
                                                      @RequestBody RepositoryInterface repositoryInterface) throws Exception {
189
        return repositoryService.addRepositoryInterface(datatype, id, registeredBy, comment, repositoryInterface);
190
    }
191

    
192
    @RequestMapping(value = "/getUrlsOfUserRepos/{page}/{size}/", method = RequestMethod.GET,
193
            produces = MediaType.APPLICATION_JSON_VALUE)
194
    @ResponseBody
195
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
196
    public List<String> getUrlsOfUserRepos(@PathVariable("page") String page, @PathVariable("size") String size) {
197
        return repositoryService.getUrlsOfUserRepos(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
198
    }
199

    
200
    @RequestMapping(value = "/getDatasourceVocabularies/{mode}", method = RequestMethod.GET,
201
            produces = MediaType.APPLICATION_JSON_VALUE)
202
    @ResponseBody
203
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
204
        return repositoryService.getDatasourceVocabularies(mode);
205
    }
206

    
207
    @RequestMapping(value = "/getCompatibilityClasses/{mode}", method = RequestMethod.GET,
208
            produces = MediaType.APPLICATION_JSON_VALUE)
209
    @ResponseBody
210
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode) {
211

    
212
        return repositoryService.getCompatibilityClasses(mode);
213
    }
214

    
215
    @RequestMapping(value = "/getDatasourceClasses/{mode}", method = RequestMethod.GET,
216
            produces = MediaType.APPLICATION_JSON_VALUE)
217
    @ResponseBody
218
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode) {
219
        return repositoryService.getDatasourceClasses(mode);
220
    }
221

    
222
    @RequestMapping(value = "/getMetricsInfoForRepository/{id}", method = RequestMethod.GET,
223
            produces = MediaType.APPLICATION_JSON_VALUE)
224
    @ResponseBody
225
    public MetricsInfo getMetricsInfoForRepository(@PathVariable("id") String id) throws RepositoryServiceException {
226
        return repositoryService.getMetricsInfoForRepository(id);
227
    }
228

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

    
236
    @RequestMapping(value = "/updateRepositoryInterface", method = RequestMethod.POST,
237
            consumes = MediaType.APPLICATION_JSON_VALUE)
238
    @ResponseBody
239
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
240
    public RepositoryInterface updateRepositoryInterface(@RequestParam("id") String id,
241
                                                         @RequestParam("registeredBy") String registeredBy,
242
                                                         @RequestParam(value = "comment", required = false) String comment,
243
                                                         @RequestBody RepositoryInterface repositoryInterface) throws Exception {
244
        return repositoryService.updateRepositoryInterface(id, registeredBy, comment, repositoryInterface);
245
    }
246

    
247

    
248
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
249
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
250

    
251
    /**
252
     * Get all the admins of the repository
253
     */
254
    @RequestMapping(method = RequestMethod.GET, path = "{id}/admins")
255
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
256
    public ResponseEntity<List<User>> getAdminsOfARepo(@PathVariable("id") String id) {
257
        return new ResponseEntity<>(authorizationService.getAdminsOfRepo(id), HttpStatus.OK);
258
    }
259

    
260
    /**
261
     * Subscribe to repo by email
262
     */
263
    @RequestMapping(method = RequestMethod.POST, path = "{id}/admins")
264
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
265
    public Response subscribeByEmail(@PathVariable("id") String id, @RequestBody String email) throws ResourceNotFoundException {
266
        authorizationService.addAdmin(id, email);
267
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(javax.ws.rs.core.MediaType.APPLICATION_JSON).build();
268
    }
269

    
270
    /**
271
     * Unsubscribe from repo by email
272
     */
273
    @RequestMapping(method = RequestMethod.DELETE, path = "{id}/admins/{email:.+}")
274
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
275
    public ResponseEntity<Void> unsubscribeByEmail(@PathVariable("id") String id, @PathVariable("email") String email) throws ResourceNotFoundException {
276
        authorizationService.removeAdmin(id, email);
277
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
278
    }
279
}
(6-6/12)