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("@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("id") 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 = "/getUrlsOfUserRepos/{page}/{size}/", method = RequestMethod.GET,
191
            produces = MediaType.APPLICATION_JSON_VALUE)
192
    @ResponseBody
193
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
194
    public List<String> getUrlsOfUserRepos(@PathVariable("page") String page, @PathVariable("size") String size) {
195
        return repositoryService.getUrlsOfUserRepos(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
196
    }
197

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

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

    
210
        return repositoryService.getCompatibilityClasses(mode);
211
    }
212

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

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

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

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

    
245

    
246
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
247
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
248

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

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

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