User creation API: ‘active’ attribute set to True but returns False in response

Hi all,

I’m using Python to create users via the Discourse API. The user creation request is returning a success response, but I’m encountering an issue where the active attribute in the response is always false, even though I explicitly set it to true in the payload. The confirmed attribute is set to true, and that works fine.

Here’s the code:

import csv
import requests
import json
from datetime import datetime

# Discourse API details
discourse_url = "https://forum.hobiguru.com/"  # Replace with your Discourse URL
api_key = "your-api-key"  # Replace with your Discourse API Key
api_username = "system"  # Admin username

# Request headers
headers = {
    "Api-Key": api_key,
    "Api-Username": api_username,
    "Content-Type": "application/json"
}

# Function to create a user
def create_user(username, name, email, password, bio, location, confirmed, active, join_date):
    url = f"{discourse_url}/users.json"
    join_date_str = join_date.strftime('%Y-%m-%dT%H:%M:%SZ')

    payload = {
        "name": name,
        "email": email,
        "password": password,
        "username": username,
        "active": True,  # Set active to True by default
        "confirmed": True,  # Set confirmed to True by default
        "created_at": join_date_str
    }

    print(f"\nRequest URL: {url}")
    print(f"Request Headers: {json.dumps(headers, indent=2)}")
    print(f"Request Payload: {json.dumps(payload, indent=2)}")

    response = requests.post(url, json=payload, headers=headers)
    
    if response.status_code == 200:
        response_json = response.json()
        if response_json.get("success"):
            print(f"User creation successful: {json.dumps(response_json, indent=2)}")
        else:
            print(f"User creation failed. Reason: {response_json.get('message')}")
            print(f"Errors: {json.dumps(response_json.get('errors'), indent=2)}")
    else:
        print(f"Request failed: {response.status_code}, {response.text}")

# Reading users from a CSV file
with open('input_users.csv', mode='r', encoding='utf-8') as file:
    reader = csv.DictReader(file)
    for row in reader:
        # Extract user details from the row
        create_user(row['Username'], row['Name'], row['Email'], row['Password'], row['Bio'], row['Location'], row['Confirmed'] == 'TRUE', row['Active'] == 'TRUE', datetime.strptime(row['Join Date'], '%Y-%m-%dT%H:%M:%SZ'))

I get this printed:

 Request to create a user

{'name': 'Goran', 'email': 'bla+blaaa@gmail.com', 'password': 'P@ssword!23', 'username': 'goran12', 'active': True, 'confirmed': True, 'created_at': '2024-11-04T10:20:34Z'}
Request URL: https://forum.hobiguru.com/users.json
Request Headers:
{
  "Api-Key": "d9---------------e564d65d9b5a3",
  "Api-Username": "system",
  "Content-Type": "application/json"
}
Request Payload:
{
  "name": "Goran",
  "email": "'bla+blaaa@gmail.com",
  "password": "P@ssword!23",
  "username": "goran12",
  "active": true,
  "confirmed": true,
  "created_at": "2024-11-04T10:20:34Z"
}
Response:

Full Response: {
  "success": true,
  "active": false,
  "message": "Va\u0161 ra\u010dun je aktiviran i spreman za kori\u0161tenje."
}
Request was successful and user got created:
{'success': True, 'active': False, 'message': 'Vaš račun je aktiviran i spreman za korištenje.'}

Problem:

• Despite passing “active”: True in the payload, the active attribute in the response is always false and when I look for the users in the discourse admin panel I cannot find any

• The API returns success: true, but the user does not seem to be fully activated.

Questions:

  1. Is there something I might be missing in my request that could cause the active attribute to not be set correctly?

  2. Are there any specific conditions in Discourse’s API that would override the active attribute, even if it’s explicitly set to true?

Any insights or advice would be greatly appreciated!

2 Likes

You can try running this script once; it might help you. Here you go: A script to create dummy users for your Discourse forum.

Additionally, your script seems to work quite well, but the issue lies with the data you’re using in your CSV file.

I tested your code using the following sample data:

Username,Name,Email,Password,Bio,Location,Confirmed,Active,Join Date
Paul,Paul Paul,paul@example.com,tough001!@,This is Paul,Australia,TRUE,TRUE,2023-12-30T14:00:00Z
radhika01,Radhika Singh,singhradhika@example.com,tough001!@,This is Radhika Tomar,India,TRUE,TRUE,2023-12-30T14:00:00Z

It worked perfectly fine for me. A few things to keep in mind: use passwords that are at least 12 characters long and ensure they are strong.

Give it a shot and let me know if that works for you :))

Hi @MihirR

Thank you so much for your reply and for helping me out with this! I really appreciate it.

I think I’ve found the problem. The issue was with the email addresses I was using — specifically, emails with a plus sign (like Gmail aliases whatever+something@gmail.com, whatever+something2@gmail.com) for dummy users. When I use an email without the plus sign, everything works fine, and the user gets created like is the case with your CSV sample. However, when using an email with a plus sign, the API doesn’t seem to handle it correctly.

In the screenshot you can see 2 curl calls: with a plus sign and without a plus sign in the email…

The weird thing is that when I use the plus sign, I don’t get an error. I actually receive a success response that says the account has been created and activated, but this isn’t true. I checked directly in the Rails console and connected to the database, and the user is not there. The user doesn’t show up in the discourse admin either.

It seems like there’s an issue with the API’s response — it reports a successful creation and activation (Sorry, the string in the screenshot is in Croatian), but the user is never actually created in the system. This suggests there might be a problem with how the API handles or reports on user creation when special characters (like the plus sign) are used in the email.

Again, thanks for your help, and I thought I’d share this discovery with you in case it helps!

1 Like

How is the normalize_emails site setting configured at your instance?

3 Likes

It looks like it actually reports that the activation didn’t work, assuming that’s what "active": false means.

The message key in the response says “Your account is activated and ready for use.”, which is wrong.

1 Like

Exactly, that’s the wrong part in the whole thing. The param says active:false while the message says “Account has been activated and ready for use”

Hi, The response param says active:false while the message says “Account has been activated and ready for use”

I haven’t checked, but I will. It seems that was announced here: Enabling e-mail normalization by default


Yes, it seems that the reason for the failure was the flag normalize_email:true it’s true by default. As I turned it off the users got created… However, the API is not considering the normalize_emails flag and is returning success eventhough the user never got created or activated for that matter :confused: Should I report this in discourse github ?

2 Likes

Or open a Bug rest-api topic :slight_smile:

1 Like