Skip to content
This repository has been archived by the owner on Jul 12, 2023. It is now read-only.

Logic for batch user import #553

Merged
merged 24 commits into from
Sep 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 168 additions & 3 deletions cmd/server/assets/users/import.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

<head>
{{template "head" .}}
{{template "firebase" .}}
</head>

<body class="bg-light">
Expand All @@ -22,16 +23,180 @@ <h1>Import users</h1>
<p>Bulk import a list of users to <strong>{{.currentRealm.Name}}</strong>.</p>

<div class="card mb-3 shadow-sm">
<div class="card-header">Import options</div>
<div class="card-header">Import</div>
<div class="card-body">
{{template "beta-notice" .}}
<small class="form-text text-muted">Coming soon</small>

<p>
Use this form to import a list of users. The server will create them in batches.
</p>

<pre>Example file contents:
<code>
email@example.com, Anne
another@example.com, Bob
</code>
</pre>
<form id="form">
<div class="custom-file">
<input type="file" class="custom-file-input" id="csv" accept=".csv" required>
<label class="custom-file-label" for="csv" id="fileLabel">Select a CSV file</label>
</div>
<button class="btn btn-primary" type="submit" id="import" disabled>Import users</button>
<button class="btn btn-danger" id="cancel" disabled>Cancel</button>
</form>
</div>

<div class="card-body">
<div class="progress" id="progress-div" style="display:none;">
<div id="progress" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<table class="table table-bordered" id="csv-table" style="display:none;">
<thead>
<tr>
<th>Email</th>
<th>Name</th>
</tr>
</thead>
<tbody id="csv-table-body"></tbody>
</table>
</div>
</div>
<a class="card-link" href="/users">&larr; All users</a>
<a class=" card-link" href="/users">&larr; All users</a>
</main>

{{template "scripts" .}}
<script type="text/javascript">
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmmm this is a lot of javascript. Is there a strong reason to do this on the client vs the server? It seems like a traditional form submit + background processing would suffice here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm also worried about the "modern" requirements here. When you think about most hospitals and medical facilities, they aren't running the latest and greatest browsers. I wouldn't be surprised if we have some clients using IE on XP still, with no support for the HTML5 file objects.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main reason is so that it can batch and update progress as it goes. If we submit the whole file, we still need to return a response with all the users so we can do the password reset in javascript.

$(function() {
let $form = $('#form');
let $csv = $('#csv');
let $fileLabel = $('#fileLabel');
let $import = $('#import');
let $cancel = $('#cancel');
let $table = $('#csv-table');
let $tableBody = $('#csv-table-body');
let $progressDiv = $('#progress-div');
let $progress = $('#progress');

let totalUsersCreated = 0;
let upload = readFile();

if (typeof (FileReader) == "undefined") {
flash.error("Your browser does not support the required HTML5 file reader.");
} else {
$csv.prop('disabled', false);
}

$csv.change(function(file) {
let fileName = file.target.files[0].name;
$fileLabel.html(fileName);
$import.prop('disabled', false);
});

$cancel.on('click', function(event) {
upload.cancel();
flash.error("Canceled batch upload.");
})

$form.on('submit', function(event) {
event.preventDefault();
$import.prop('disabled', true);
$cancel.prop('disabled', false);

$table.show(100);
$progressDiv.show();

var reader = new FileReader();
reader.onload = upload.start;
reader.readAsText($csv[0].files[0]);
});

const batchSize = 10;

function readFile() {
// State for managing cleanup and canceling
let cancelUpload = false;
let cancel = () => {
cancelUpload = true;
};

let start = async function(e) {
let rows = e.target.result.split("\n");
let batch = [];
totalUsersCreated = 0;
$tableBody.empty();
let i = 0;
for (; i < rows.length && !cancelUpload; i++) {
if (rows[i].trim() != "") {
if (batch.length >= batchSize) {
$tableBody.empty();
batch = [];
}

let user = {};
let cols = rows[i].split(",");
user["email"] = cols[0].trim();
user["name"] = (cols.length > 1) ? cols[1].trim() : "";

let row = "<tr><td>" + user["email"] + "</td><td>" + user["name"] + "</td></tr>";
$tableBody.append(row);

batch.push(user);
}

if (batch.length >= batchSize || i == rows.length - 1) {
await uploadBatch(batch).catch(err => { });
if (cancelUpload) {
flash.warning("Successfully created " + totalUsersCreated + " new users."
+ (rows.length - i) + " remaining.");
break;
}

let percent = Math.floor((i + 1) * 100 / rows.length) + "%";
$progress.width(percent);
$progress.html(percent);
}
}

if (!cancelUpload) {
flash.alert("Successfully created " + totalUsersCreated + " new users.");
}
$table.fadeOut(400);
$import.prop('disabled', false);
$cancel.prop('disabled', true);
};

return { start, cancel };
}
});

function uploadBatch(data) {
return $.ajax({
type: 'POST',
url: '/users/import',
data: JSON.stringify({ "users": data }),
headers: { 'X-CSRF-Token': '{{.csrfToken}}' },
contentType: 'application/json',
success: function(result) {
for (user of result.newUsers) {
firebase.auth().sendPasswordResetEmail(user.email)
.then(function() {
totalUsersCreated++;
}).catch(function(error) {
flash.error(error.message);
});
}
if (result.error) {
flash.error(result.error, "danger");
}
},
error: function(xhr, status, e) {
flash.error(e, "danger");
},
});
}
</script>
</body>

</html>
Expand Down
2 changes: 1 addition & 1 deletion cmd/server/assets/users/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ <h1>Users</h1>
<span class="oi oi-plus" aria-hidden="true"></span>
New user
</a>
<a class="btn btn-sm disabled" href="/users/import" data-toggle="tooltip" title="Bulk import users">
<a class="btn btn-sm" href="/users/import" data-toggle="tooltip" title="Bulk import users">
<span class="oi oi-data-transfer-upload" aria-hidden="true"></span>
Import
</a>
Expand Down
1 change: 1 addition & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ func realMain(ctx context.Context) error {
userSub.Handle("", userController.HandleCreate()).Methods("POST")
userSub.Handle("/new", userController.HandleCreate()).Methods("GET")
userSub.Handle("/import", userController.HandleImport()).Methods("GET")
userSub.Handle("/import", userController.HandleImportBatch()).Methods("POST")
userSub.Handle("/{id}/edit", userController.HandleUpdate()).Methods("GET")
userSub.Handle("/{id}", userController.HandleShow()).Methods("GET")
userSub.Handle("/{id}", userController.HandleUpdate()).Methods("PATCH")
Expand Down
100 changes: 100 additions & 0 deletions pkg/controller/user/importbatch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package user

import (
"net/http"

"github.com/google/exposure-notifications-verification-server/pkg/api"
"github.com/google/exposure-notifications-verification-server/pkg/controller"
"github.com/google/exposure-notifications-verification-server/pkg/database"
"github.com/hashicorp/go-multierror"
)

func (c *Controller) HandleImportBatch() http.Handler {
logger := c.logger.Named("user.HandleImportBatch")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()

realm := controller.RealmFromContext(ctx)
if realm == nil {
controller.MissingRealm(w, r, c.h)
return
}

var request api.UserBatchRequest
if err := controller.BindJSON(w, r, &request); err != nil {
logger.Errorw("Error decoding request", "error", err)
c.h.RenderJSON(w, http.StatusBadRequest, api.Error(err))
return
}

newUsers := make([]*api.BatchUser, 0, len(request.Users))

var batchErr *multierror.Error
for _, batchUser := range request.Users {
// See if the user already exists by email - they may be a member of another
// realm.
user, err := c.db.FindUserByEmail(batchUser.Email)
alreadyExists := true
if err != nil {
if !database.IsNotFound(err) {
logger.Errorw("Error finding user", "error", err)
batchErr = multierror.Append(batchErr, err)
continue
}

user = new(database.User)
alreadyExists = false
}

// Build the user struct - keeping email and name if user already exists in another realm.
if !alreadyExists {
user.Email = batchUser.Email
user.Name = batchUser.Name
}
user.Realms = append(user.Realms, realm)
if err := c.db.SaveUser(user); err != nil {
logger.Errorw("Error saving user", "error", err)
batchErr = multierror.Append(batchErr, err)
continue
}

if created, err := user.CreateFirebaseUser(ctx, c.client); err != nil {
logger.Errorw("Error creating firebase user", "error", err)
batchErr = multierror.Append(batchErr, err)
continue
} else if created {
newUsers = append(newUsers, &batchUser)
}
}

response := &api.UserBatchResponse{
NewUsers: newUsers,
}

if err := batchErr.ErrorOrNil(); err != nil {
response.Error = err.Error()
response.ErrorCode = string(http.StatusInternalServerError)

if len(newUsers) == 0 { // We return partial success if any succeeded.
c.h.RenderJSON(w, http.StatusInternalServerError, response)
return
}
}

c.h.RenderJSON(w, http.StatusOK, response)
})
}
3 changes: 3 additions & 0 deletions pkg/database/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ func (db *Database) TouchUserRevokeCheck(u *User) error {
// indicates if the user was created.
func (u *User) CreateFirebaseUser(ctx context.Context, fbAuth *auth.Client) (bool, error) {
if _, err := fbAuth.GetUserByEmail(ctx, u.Email); err != nil {
if auth.IsInvalidEmail(err) {
return false, fmt.Errorf("invalid email: %q", u.Email)
}
if !auth.IsUserNotFound(err) {
return false, fmt.Errorf("failed lookup firebase user: %w", err)
}
Expand Down