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
    @RequestMapping(value = "/countries", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
48
    @ResponseBody
49
    public Country[] getCountries() {
50
        return repositoryService.getCountries();
51
    }
52

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

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

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

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

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

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

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

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

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

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

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

    
139
        return repositoryService.addRepository(datatype, repository);
140
    }
141

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

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

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

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

    
171
    @RequestMapping(value = "/deleteInterface/", method = RequestMethod.DELETE)
172
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
173
    public void deleteRepositoryInterface(@RequestParam("id") String id,
174
                                          @RequestParam("registeredBy") String registeredBy) {
175
        repositoryService.deleteRepositoryInterface(id, registeredBy);
176
    }
177

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

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

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

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

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

    
221
        return repositoryService.getCompatibilityClasses(mode);
222
    }
223

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

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

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

    
245
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
246
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
247

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

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

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