-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathAdminController.groovy
186 lines (157 loc) · 6.82 KB
/
AdminController.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/*
* Copyright (C) 2022 Atlas of Living Australia
* All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
package au.org.ala.userdetails
import au.org.ala.auth.PreAuthorise
import au.org.ala.users.IUser
import com.opencsv.CSVWriterBuilder
import com.opencsv.RFC4180ParserBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest
@PreAuthorise
class AdminController {
def passwordService
def emailService
def exportService
def profileService
def authorisedSystemService
@Value('${attributes.affiliations.attribute-name:affiliation}')
String affiliationAttribute = 'affiliation'
@Autowired
@Qualifier('userService')
IUserService userService
def index() {}
def resetPasswordForUser(){
}
def sendPasswordResetEmail(){
def user = userService.getUserById(params.email)
if (user) {
def password = passwordService.generatePassword(user)
//email to user
emailService.sendGeneratedPassword(user, password)
render(view:'userPasswordResetSuccess', model:[email:params.email, password: password])
} else {
render(view:'resetPasswordForUser', model:[email:params.email, emailNotRecognised:true])
}
}
def bulkUploadUsers() {
}
def exportUsers() {
def secondaryFields = profileService.allAvailableProperties
String extraFields = secondaryFields.join(",")
render(view: 'exportUsers',
model: [roles : userService.listRoles(),
primaryFields: grailsApplication.config.getProperty('admin.export.csv.primary.fields'),
extraFields : extraFields])
}
def downloadUsersCsvFile() {
if (authorisedSystemService.isAuthorisedSystem(request)) {
//selectedRoles data type will be different depending on whether one or more option were selected
def roleList = {
if (!params.selectedRoles) {
return []
} else if (params.selectedRoles instanceof String) {
return [params.selectedRoles]
} else {
return params.selectedRoles as List
}
}.call()
//1. Get data based on user inputs
def userList = userService.findUsersForExport(roleList, params?.includeInactiveUsers)
//2. Then prepare the format options
String primaryFieldsProperty = grailsApplication.config.getProperty('admin.export.csv.primary.fields')
def primaryFields = primaryFieldsProperty ? primaryFieldsProperty.split(',').collect { it as String } : []
def fields = primaryFields
def formatters = [:]
if (params.includeExtraFields) {
def secondaryFields = profileService.allAvailableProperties
fields.addAll(secondaryFields)
secondaryFields.each {
formatters[it] = { domain, value ->
String fieldName = it
domain.additionalAttributes.find {
it.name == fieldName
}?.value
}
}
}
if (params.includeRoles) {
String roleFieldName = 'roles'
formatters[roleFieldName] = { IUser domain, value ->
def result = ""
domain.roles.each {
result += it.roleObject.role + " "
}
result
}
fields.add(roleFieldName)
}
log.debug("Export fields ${fields}")
String fileName = "users-" + new Date().format("YYYYMMdd-HHmm")
//3. And finally generate and send file to browser
exportService.export("csv", response, fileName, "csv", userList, fields, [:], formatters, [:])
} else {
response.sendError(403)
}
}
def loadUsersCSV() {
if(request instanceof MultipartHttpServletRequest) {
MultipartFile f = ((MultipartHttpServletRequest) request).getFile('userList')
if (f && f.size > 0) {
def allowedMimeTypes = ['text/plain', 'text/csv']
if (!allowedMimeTypes.contains(f.getContentType())) {
flash.message = "The file must be one of: ${allowedMimeTypes}. Submitted file is of type ${f.getContentType()}"
redirect(action:"bulkUploadUsers")
return
}
def firstRow = (boolean) params.firstRowHasFieldNames
def affiliation = params.affiliation as String
def subject = params.emailSubject as String
def title = params.emailTitle as String
def body = params.emailBody as String
def results = userService.bulkRegisterUsersFromFile(f.inputStream, firstRow, affiliation, subject, title, body)
render(view:'loadUsersResults', model:[results: results])
return
} else {
flash.message = "You must select a file to upload!"
}
}
redirect(action:"bulkUploadUsers")
}
def surveyResults() {
def results = userService.countByProfileAttribute(affiliationAttribute, null, request.locale)
respondWithCsv(results, "user-survey-${new Date()}.csv")
}
def emailListForm() {
}
def emailList() {
def startDate = params.date('start_date')
def endDate = params.date('end_date')
def results = userService.emailList(startDate, endDate)
respondWithCsv(results, "email-list-$startDate-to-${endDate}.csv")
}
private def respondWithCsv(List<String[]> results, String filename) {
def csvWriter = new CSVWriterBuilder(response.writer)
.withParser(new RFC4180ParserBuilder().build())
.build()
response.status = 200
response.contentType = 'text/csv'
response.setHeader('Content-Disposition', "attachment; filename=$filename")
csvWriter.writeAll(results)
csvWriter.flush()
}
}