Thorn Tech Marketing Ad
Skip to main content
Version: 1.4.0

Batch Add Users from a CSV File

TLDR

Purpose: Create many StorageLink users at once from a CSV file with a Python script that calls the REST API

Requirements: Python 3.6+ with requests, admin credentials, security.client-id and security.client-secret from /opt/swiftgw/application.properties, and your IP address allowed on port 443

CSV Columns: username and password are required; homeBase (the folder the user's own Personal folder is created in) defaults to /users; canList, canDownload, canUpload and canCreateFolder default to true, canOverwriteDelete to false; groups is an optional ;-separated list of StorageLink group names

Quick Steps:

  1. Create users.csv
  2. Set STORAGELINK_HOST, CLIENT_ID, CLIENT_SECRET, ADMIN_USERNAME and ADMIN_PASSWORD in batch-create-users.py
  3. Run python3 batch-create-users.py, optionally followed by another CSV file name

Note: This article is an unreviewed draft, so test with one user first. A username that already exists fails and the script continues with the rest.

Product: StorageLink by Thorn Technologies — cloud storage gateway for secure file sharing

Draft

This article is a draft and has not been reviewed yet. Please verify all steps before following them in production.

Overview​

The StorageLink REST API lets you create users programmatically. This article provides a Python script that reads users from a CSV file and creates them through the API, giving each one a Personal folder of their own and, optionally, membership of existing groups.

Prerequisites​

  • Python 3.6+
  • The requests library (pip install requests)
  • Admin credentials for the StorageLink web interface
  • The security.client-id and security.client-secret from /opt/swiftgw/application.properties on the StorageLink server
  • Any groups named in the CSV already created under Groups
info

Make sure your IP address is allowed in the Security Group / Firewall for port 443, since the script sends requests over HTTPS.

Step 1: Prepare the CSV File​

Create a file called users.csv with the following format:

username,password,homeBase,canList,canDownload,canUpload,canCreateFolder,canOverwriteDelete,groups
alice,P@ssw0rd123-long,/users,true,true,true,true,false,Finance
bob,S3cur3!Pass-long,/users,true,true,false,false,false,
charlie,Ch@ng3Me1-long,/data,true,true,true,true,true,Finance;Marketing

Column reference:

ColumnRequiredDescription
usernameYesThe username for the new user
passwordYesThe user's first password; it must meet the password policy (12 characters or more by default)
homeBaseNoThe folder the user's own Personal folder is created in, as <homeBase>/<username> (defaults to /users)
canListNoList capability on that folder (defaults to true)
canDownloadNoDownload/Preview capability (defaults to true)
canUploadNoUpload capability (defaults to true)
canCreateFolderNoCreate Folder capability (defaults to true; it only takes effect together with Upload)
canOverwriteDeleteNoDelete/Overwrite/Rename capability (defaults to false)
groupsNoStorageLink group names to add the user to, separated by ;. Each group must already exist

A user needs at least one folder to sign in. Leave homeBase at its default unless you want the personal folders elsewhere; to create users whose access comes only from groups, see the note under the script.

Step 2: Get the Client Credentials​

On the StorageLink server, run:

sudo grep -E '^security.client-(id|secret)=' /opt/swiftgw/application.properties

It shows the security.client-id and security.client-secret values. You will need these in the next step. (Avoid cat on this file: it also prints the database password and the token signing secret.)

Step 3: Create the Script​

Save the following script as batch-create-users.py:

import csv
import sys
import requests
from urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# ---- Configuration (update these values) ----
STORAGELINK_HOST = "https://YOUR-STORAGELINK-IP"
CLIENT_ID = "your-client-id"
CLIENT_SECRET = "your-client-secret"
ADMIN_USERNAME = "admin"
ADMIN_PASSWORD = "your-admin-password"
CSV_FILE = "users.csv"
# ----------------------------------------------

API_URL = f"{STORAGELINK_HOST}/backend"


def get_access_token():
"""Authenticate and return an OAuth access token."""
response = requests.post(
f"{API_URL}/login",
auth=(CLIENT_ID, CLIENT_SECRET),
data={
"grant_type": "password",
"username": ADMIN_USERNAME,
"password": ADMIN_PASSWORD,
},
verify=False,
)
response.raise_for_status()
return response.json()["access_token"]


def get_group_ids(token):
"""Return {group name: id} for every existing group."""
headers = {"Authorization": f"Bearer {token}"}
response = requests.get(f"{API_URL}/1.0.0/groups", headers=headers, params={"size": 1000}, verify=False)
response.raise_for_status()
body = response.json()
rows = body if isinstance(body, list) else body.get("content", [])
return {g["name"].lower(): g["id"] for g in rows}


def create_user(token, user_data):
"""Create a single user via the StorageLink API."""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
}
response = requests.post(
f"{API_URL}/1.0.0/users",
headers=headers,
json=user_data,
verify=False,
)
response.raise_for_status()
return response.json()


def parse_bool(value, default=False):
"""Parse a boolean string from CSV."""
if value is None or value.strip() == "":
return default
return value.strip().lower() in ("true", "1", "yes")


def main():
csv_file = CSV_FILE
if len(sys.argv) > 1:
csv_file = sys.argv[1]

token = get_access_token()
print("Authenticated successfully.\n")
group_ids = get_group_ids(token)

success_count = 0
fail_count = 0

with open(csv_file, newline="") as f:
reader = csv.DictReader(f)
for row in reader:
username = row["username"].strip()
home_base = (row.get("homeBase") or "").strip() or "/users"

# The user's own folder: a Personal grant on the base folder creates <home_base>/<username>
user_data = {
"username": username,
"password": row["password"],
"enabled": True,
"role": "ROLE_SWIFT",
"resetPassword": True,
"directGrants": [
{
"absolutePath": home_base,
"folderType": "PERSONAL",
"permissions": {
"listable": parse_bool(row.get("canList"), default=True),
"downloadable": parse_bool(row.get("canDownload"), default=True),
"uploadable": parse_bool(row.get("canUpload"), default=True),
"canCreateFolder": parse_bool(row.get("canCreateFolder"), default=True),
"deletable": parse_bool(row.get("canOverwriteDelete"), default=False),
},
}
],
}

wanted = [g.strip() for g in (row.get("groups") or "").split(";") if g.strip()]
missing = [g for g in wanted if g.lower() not in group_ids]
if missing:
print(f" FAILED to create user: {username} - unknown group(s): {', '.join(missing)}")
fail_count += 1
continue
if wanted:
user_data["manualGroupIds"] = [group_ids[g.lower()] for g in wanted]

try:
result = create_user(token, user_data)
print(f" Created user: {username} (id: {result.get('id')})")
success_count += 1
except requests.exceptions.HTTPError as e:
print(f" FAILED to create user: {username} - {e.response.text}")
fail_count += 1

print(f"\nDone. {success_count} created, {fail_count} failed.")


if __name__ == "__main__":
main()
Users whose access comes only from groups

To create a user with no folder of their own, send "directGrants": [] with manualGroupIds for at least one group. Without any group such a user cannot sign in.

The 1.3.x fields

homeFolderPath and homeFolderPermissions still work on POST /1.0.0/users in 1.4.0, but they are deprecated and will be removed in a later release; homeFolderPermissions also has no canCreateFolder flag. Use directGrants as above.

Step 4: Run the Script​

# Install the requests library (if not already installed)
pip install requests

# Run the script with the default CSV file (users.csv)
python3 batch-create-users.py

# Or specify a different CSV file
python3 batch-create-users.py my-users.csv

Example output:

Authenticated successfully.

Created user: alice (id: 12)
Created user: bob (id: 13)
Created user: charlie (id: 14)

Done. 3 created, 0 failed.

Tips​

  • Test with one user first. Create a CSV with a single test user and verify it works before importing a large list.
  • Password requirements. Make sure passwords meet your password policy. The script sets resetPassword so each user must choose a new password at first sign-in.
  • Personal folders. The user's own folder is <homeBase>/<username>, /users/<username> by default. It is created when the user is created.
  • Groups. Group names are matched ignoring case. Create the groups, with their folder grants, before running the script.
  • Duplicate usernames. The API returns an error if the username already exists. The script logs the failure and continues with the remaining users.
  • User limit. The license sets how many users you can create; the API refuses the first user over the limit with a message naming the cap.
  • SSL certificates. The script disables SSL verification (verify=False) for self-signed certificates. If you have a valid SSL certificate, you can remove the verify=False parameter.

API Reference​

For more details on the StorageLink REST API, see Uploading Files via the API.

From StorageLink 1.4.0, every instance serves its own OpenAPI description at https://storagelink-hostname/backend/v3/api-docs; it requires an administrator's access token. A snapshot is also available at https://thorntech-public-documents.s3.amazonaws.com/storagelink/KB/storagelink-api-documentation-swagger.json, which you can view in the Swagger Editor.