superset icon indicating copy to clipboard operation
superset copied to clipboard

Automatically create users from csv file

Open pajachiet opened this issue 9 years ago • 18 comments

Goal

We need to automate the creation and maintenance of Superset users. This is useful to setup rapidly new Superset instances, or for tests.

Personal hack

Based on a csv files listing users and their password, we developed a script that create missing users and set their passwords. The script that we use currently is called create_superset_users.py in this gist. It works with a dockerized Superset instance (easy modification to adapt otherwise).

One csv list users, with the following header first_name;last_name;email Another list their passwords, with the following header email;password Other columns may be added if needed. The same file could be used if you don't need to separate informations.

Feature request

Would it be possible to develop a similar feature directly into Superset ? A complete feature would be to export the current list of users as a csv, modify it if needed, then import it again.

pajachiet avatar Jul 05 '17 11:07 pajachiet

FWIW, a) you shouldn't directly work with the ab_user table - use object model instead. and b) the user management is handled by Flask-AppBuilder - that might be a better place to implement a bulk user loader

ratb3rt avatar Jul 06 '17 12:07 ratb3rt

It sounds like we had similar needs. Note that you can extend the SecurityManager class and call self.add_user inside a superset_config.py.

It would look a bit like this (not tested, just typing out the general idea for what we use) :

CustomSecurityManager(SecurityManager): def my_bulk_insert_method(self): for newuser in users_to_add: # Pull your username, etc. from your csv user = self.add_user( username=username, first_name=user_firstname, last_name=user_lastname, email=user_email, role=user_role )

CUSTOM_SECURITY_MANAGER = CustomSecurityManager

On Thu, Jul 6, 2017 at 1:59 PM, Rich @ RadICS [email protected] wrote:

FWIW, a) you shouldn't directly work with the ab_user table - use object model instead. and b) the user management is handled by Flask-AppBuilder - that might be a better place to implement a bulk user loader

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/apache/incubator-superset/issues/3083#issuecomment-313388784, or mute the thread https://github.com/notifications/unsubscribe-auth/ATMSk8y8XWfNVGlnRl8iLcx-6zSyg3JJks5sLNotgaJpZM4OOPFz .

robert-digit avatar Jul 07 '17 08:07 robert-digit

Considering my note above can this be marked resolved?

robert-digit avatar Jul 13 '17 10:07 robert-digit

Thanks a lot for your answers. This looks much better indeed ! And its great to put that in superset_config.py

Where do you import the class SecurityManager ? Is it from flask_appbuilder.security.manager import BaseSecurityManager ?

pajachiet avatar Jul 18 '17 11:07 pajachiet

Hi !

I am working with pajachiet on this subject.

This method looks quite nice indeed but, if I am right, it implies calling the new my_bulk_insert_method at some point, inside superset code (we use superset inside a container, not as a module).

We have decided to try using superset API, to be more specific, we use superset/update_role/ route. This seems to fit our needs. If someone has any feedback regarding this method, we are really interested.

JulieRossi avatar Aug 25 '17 08:08 JulieRossi

Notice: this issue has been closed because it has been inactive for 240 days. Feel free to comment and request for this issue to be reopened.

mistercrunch avatar Apr 23 '18 07:04 mistercrunch

@JulieRossi Hi ! I have a similar demand to create user automatically. Using superset API seems to be a better idea,but I don't know where to start . Would you mind sharing some detail on how to do it ? It would be a great help,thanks.

yqylovy avatar Nov 10 '18 10:11 yqylovy

Hi @yqylovy, if it helps, here's how our code looks like : Tool class to be able to use superset api (needs to be connected for some actions)

class UseSupersetApi:
    def __init__(self, username=None, password=None):
        self.s = requests.Session()
        self.base_url = SUPERSET_URL
        self._csrf = get_csrf_token(self.s.get(self.url('login/')))
        self.headers = {'X-CSRFToken': self._csrf, 'Referer': self.url('login/')}
        # note: does not use headers because of flask_wtf.csrf.validate_csrf
        # if data is dict it is used as form and ends up empty but flask_wtf checks if data ...
        self.s.post(self.url('login/'),
                    data={'username': username, 'password': password, 'csrf_token': self._csrf})

    def url(self, url_path):
        return self.base_url + url_path

    def get(self, url_path):
        return self.s.get(self.url(url_path), headers=self.headers)

    def post(self, url_path, data=None, json_data=None, **kwargs):
        kwargs.update({'url': self.url(url_path), 'headers': self.headers})
        if data:
            data['csrf_token'] = self._csrf
            kwargs['data'] = data
        if json_data:
            kwargs['json'] = json_data
        return self.s.post(**kwargs)

And then we use it to create users :

superset = UseSupersetApi('admin', SUPERSET_ADMIN_MDP)

for user in users:
    payload = {'first_name': user['first_name'],
               'last_name': user['last_name'],
               'username': user['username'],
               'email': user['email'],
               'active': True,
               'conf_password': user['password'],
               'password': user['password']}
    superset.post(url_path='users/api/create', json=payload)

users_by_role = _group_users_by_role(users)
for role in users_by_role:
    payload = {'users': users_by_role[role], 'role_name': role}
    superset.post(url_path='superset/update_role/', json=payload)

Don't hesitate if you have any questions

JulieRossi avatar Nov 12 '18 09:11 JulieRossi

@JulieRossi Thanks !!! I tried to login but aways fail , by viewing your code,I found that I missing the csrf_token param and finally successfully login. Thank you again!

yqylovy avatar Nov 13 '18 06:11 yqylovy

For those who may need the code to do it. It works outside the host server.

import requests
from bs4 import BeautifulSoup as bs
from bs4 import Comment

class UseSupersetApi:
    def __init__(self, username=None, password=None):
        self.s = requests.Session()
        self.base_url = "http://123.45.67.890:8088/"
        self._csrf = self._getCSRF(self.url('login/'))
        self.headers = {'X-CSRFToken': self._csrf, 'Referer': self.url('login/')}
        # note: does not use headers because of flask_wtf.csrf.validate_csrf
        # if data is dict it is used as form and ends up empty but flask_wtf checks if data ...
        self.s.post(self.url('login/'),
        data={'username': username, 'password': password, 'csrf_token': self._csrf})
        
    def url(self, url_path):
        return self.base_url + url_path

    def get(self, url_path):
        return self.s.get(self.url(url_path), headers=self.headers)

    def post(self, url_path, data=None, json_data=None, **kwargs):
        kwargs.update({'url': self.url(url_path), 'headers': self.headers})
        if data:
            data['csrf_token'] = self._csrf
            kwargs['data'] = data
        if json_data:
            kwargs['json'] = json_data
        return self.s.post(**kwargs)

    def _getCSRF(self, url_path):
        response = self.s.get(base_url)
        soup = bs(response.content, "html.parser")
        for tag in soup.find_all('input', id='csrf_token'):
            csrf_token = tag['value']
        return csrf_token

superset = UseSupersetApi('admin', 'passoword')
users = [] #some user dicts inside

for user in users:
    payload = {'first_name': user['first_name'],
               'last_name': user['last_name'],
               'username': user['username'],
               'email': user['email'],
               'active': True,
               'conf_password': user['password'],
               'password': user['password'],
               user['roles']} 
    print(superset.post(url_path='users/api/create', json=payload))

SWoto avatar Sep 30 '19 17:09 SWoto

@SWoto thanks for sharing the source, I am able to login successfully but the /users/api/create results in 404, users/add is working for me

abhishekkumaresan avatar Jul 10 '20 09:07 abhishekkumaresan

Hi this does not seem to work for me. I get 200 but no users are added.

vmallya-123 avatar May 27 '21 05:05 vmallya-123

I have the same issue as well. This is not working, I get 200 but no users are added. I am using apache superset version 1.1.0

example: $ python create_superset_user.py <Response [200]>

ghost avatar Jun 15 '21 13:06 ghost

My code is : " import requests from bs4 import BeautifulSoup as bs from bs4 import Comment

class UseSupersetApi: def init(self, username=None, password=None): self.s = requests.Session() self.base_url = "http://10.XX.XX.XX:8088/" self._csrf = self._getCSRF(self.url('login/')) self.headers = {'X-CSRFToken': self._csrf, 'Referer': self.url('login/')} # note: does not use headers because of flask_wtf.csrf.validate_csrf # if data is dict it is used as form and ends up empty but flask_wtf checks if data ... self.s.post(self.url('login/'), data={'username': username, 'password': password, 'csrf_token': self._csrf})

def url(self, url_path):
    return self.base_url + url_path

def get(self, url_path):
    return self.s.get(self.url(url_path), headers=self.headers,verify=False)

def post(self, url_path, data=None, json_data=None, **kwargs):
    kwargs.update({'url': self.url(url_path), 'headers': self.headers})
    if data:
        data['csrf_token'] = self._csrf
        kwargs['data'] = data
    if json_data:
        kwargs['json'] = json_data
    return self.s.post(**kwargs)

def _getCSRF(self, url_path):
    response = self.s.get(self.base_url)
    soup = bs(response.content, "html.parser")
    for tag in soup.find_all('input', id='csrf_token'):
        csrf_token = tag['value']
        return csrf_token

superset = UseSupersetApi('admin', 'Admin@123') users = [{ 'first_name': 'fname', 'last_name':'lname', 'username': 'cplc', 'email': '[email protected]', 'conf_password': 'cplcapp', 'password': 'cplcapp', 'roles': ['10'] }] for user in users: payload = {'first_name': user['first_name'], 'last_name': user['last_name'], 'username': user['username'], 'email': user['email'], 'active': True, 'conf_password': user['password'], 'password': user['password'], 'roles': user['roles'] } print(superset.post(url_path='users/add', json=payload,verify=False)) " It is giving error 'response '400'' Please help on this??

meghna-ana avatar Aug 23 '21 10:08 meghna-ana

@SWoto code really helped me a lot. It didn't work right away for my needs:

  • delete dozens of users read from a .jsonl file
  • add dozens of users read from a .jsonl file

But after slightly modifying it, I could do all of that programmatically:

import requests
from bs4 import BeautifulSoup as bs
from bs4 import Comment
import json

class UserSupersetApi:
    def __init__(self, username=None, password=None):
        self.s = requests.Session()
        self.base_url = "superset.xyz"
        self._csrf = self._getCSRF(self.url('login/'))
        self.headers = {'X-CSRFToken': self._csrf, 'Referer': self.url('login/')}
        # note: does not use headers because of flask_wtf.csrf.validate_csrf
        # if data is dict it is used as form and ends up empty but flask_wtf checks if data ...
        self.s.post(self.url('login/'),
        data={'username': username, 'password': password, 'csrf_token': self._csrf},
                   allow_redirects=False)
        
    def url(self, url_path):
        return self.base_url + url_path

    def get(self, url_path):
        return self.s.get(self.url(url_path), headers=self.headers)

    def post(self, url_path, data=None, json_data=None, **kwargs):
        kwargs.update({'url': self.url(url_path), 'headers': self.headers})
        if data:
            data['csrf_token'] = self._csrf
            kwargs['data'] = data
        if json_data:
            kwargs['json'] = json_data
        return self.s.post(**kwargs, allow_redirects=False)

    def _getCSRF(self, url_path):
        response = self.s.get(url_path)
        soup = bs(response.content, "html.parser")
        for tag in soup.find_all('input', id='csrf_token'):
            csrf_token = tag['value']
        return csrf_token
    
    '''
    builds User Name
    fails if 2 people have the same name
    '''
    @staticmethod  
    def build_username (first_name, last_name):
        return f'{first_name}_{last_name}'

## authenticate + set global vars

superset_username = 'ff'
superset_pw = 'fff'
file_name = 'students_data.jsonl'

superset = UserSupersetApi(superset_username, superset_pw)

## create users based on file

# users = [
#     {
#     'first_name': 'one',
#     'last_name':'one',
#     'username': 'one',
#     'email': '[email protected]',
#     'password': 'one',
#     'conf_password': 'one',
#     'roles': [] 
#     },
#     {
#     'first_name': 'two',
#     'last_name':'two',
#     'username': 'two',
#     'email': '[email protected]',
#     'password': 'two',
#     'conf_password': 'two',
#     'roles': [] 
#     }
# ]
# for user in users:
#     payload = {'first_name': user['first_name'],
#                'last_name': user['last_name'],
#                'username': user['username'],
#                'email': user['email'],
#                'active': True,
#                'conf_password': user['password'],
#                'password': user['password'],
#                'roles': user['roles']} 
#     print(superset.post(url_path='users/add', json=payload))
    
with open(file_name , 'r') as f:
    for l in f:
        user_dct = json.loads(l)
        
        
        payload = {'first_name': user_dct['first_name'],
                   'last_name': user_dct['last_name'],
                   'username': UserSupersetApi.build_username(user_dct['first_name'], user_dct['last_name']),
                   'email': user_dct['email'],
                   'active': True,
                   'conf_password': user_dct['password'],
                   'password': user_dct['password'],
                   'roles': user_dct['roles']
                  } 

        superset.post(url_path=f'users/add', json=payload)

## delete users based on file

# provides pk given a username
res = superset.get(url_path='users/api/read')

pks = res.json()['pks']
users = res.json()['result']
n_pk = len(pks)

# build dict of all current users
pk_lut = dict()
for i in range(n_pk):
    pk_lut[users[i]['email']] = pks[i]
    
# for all entries in file delete users from superset based on email
with open(file_name , 'r') as f:
    for l in f:
        user_dct = json.loads(l)
        pk = pk_lut[user_dct['email']]
        superset.post(url_path=f'users/delete/{pk}')

Hope this helps someone.

Best regards Tridelt

tridelt avatar Mar 07 '22 11:03 tridelt

@srikark16 I'm in the same situation as you, and then change it to the following and it works. 'active': True -> 'active':'y'

dwshmilyss avatar Mar 17 '22 10:03 dwshmilyss

@dwshmilyss can you please tell me the folder structure or in which files i have to ad this function? This will be a great help.

poojabhather99 avatar Oct 31 '22 07:10 poojabhather99

@SWoto code really helped me a lot. It didn't work right away for my needs:

  • delete dozens of users read from a .jsonl file
  • add dozens of users read from a .jsonl file

But after slightly modifying it, I could do all of that programmatically:

import requests
from bs4 import BeautifulSoup as bs
from bs4 import Comment
import json

class UserSupersetApi:
    def __init__(self, username=None, password=None):
        self.s = requests.Session()
        self.base_url = "superset.xyz"
        self._csrf = self._getCSRF(self.url('login/'))
        self.headers = {'X-CSRFToken': self._csrf, 'Referer': self.url('login/')}
        # note: does not use headers because of flask_wtf.csrf.validate_csrf
        # if data is dict it is used as form and ends up empty but flask_wtf checks if data ...
        self.s.post(self.url('login/'),
        data={'username': username, 'password': password, 'csrf_token': self._csrf},
                   allow_redirects=False)
        
    def url(self, url_path):
        return self.base_url + url_path

    def get(self, url_path):
        return self.s.get(self.url(url_path), headers=self.headers)

    def post(self, url_path, data=None, json_data=None, **kwargs):
        kwargs.update({'url': self.url(url_path), 'headers': self.headers})
        if data:
            data['csrf_token'] = self._csrf
            kwargs['data'] = data
        if json_data:
            kwargs['json'] = json_data
        return self.s.post(**kwargs, allow_redirects=False)

    def _getCSRF(self, url_path):
        response = self.s.get(url_path)
        soup = bs(response.content, "html.parser")
        for tag in soup.find_all('input', id='csrf_token'):
            csrf_token = tag['value']
        return csrf_token
    
    '''
    builds User Name
    fails if 2 people have the same name
    '''
    @staticmethod  
    def build_username (first_name, last_name):
        return f'{first_name}_{last_name}'

## authenticate + set global vars

superset_username = 'ff'
superset_pw = 'fff'
file_name = 'students_data.jsonl'

superset = UserSupersetApi(superset_username, superset_pw)

## create users based on file

# users = [
#     {
#     'first_name': 'one',
#     'last_name':'one',
#     'username': 'one',
#     'email': '[email protected]',
#     'password': 'one',
#     'conf_password': 'one',
#     'roles': [] 
#     },
#     {
#     'first_name': 'two',
#     'last_name':'two',
#     'username': 'two',
#     'email': '[email protected]',
#     'password': 'two',
#     'conf_password': 'two',
#     'roles': [] 
#     }
# ]
# for user in users:
#     payload = {'first_name': user['first_name'],
#                'last_name': user['last_name'],
#                'username': user['username'],
#                'email': user['email'],
#                'active': True,
#                'conf_password': user['password'],
#                'password': user['password'],
#                'roles': user['roles']} 
#     print(superset.post(url_path='users/add', json=payload))
    
with open(file_name , 'r') as f:
    for l in f:
        user_dct = json.loads(l)
        
        
        payload = {'first_name': user_dct['first_name'],
                   'last_name': user_dct['last_name'],
                   'username': UserSupersetApi.build_username(user_dct['first_name'], user_dct['last_name']),
                   'email': user_dct['email'],
                   'active': True,
                   'conf_password': user_dct['password'],
                   'password': user_dct['password'],
                   'roles': user_dct['roles']
                  } 

        superset.post(url_path=f'users/add', json=payload)

## delete users based on file

# provides pk given a username
res = superset.get(url_path='users/api/read')

pks = res.json()['pks']
users = res.json()['result']
n_pk = len(pks)

# build dict of all current users
pk_lut = dict()
for i in range(n_pk):
    pk_lut[users[i]['email']] = pks[i]
    
# for all entries in file delete users from superset based on email
with open(file_name , 'r') as f:
    for l in f:
        user_dct = json.loads(l)
        pk = pk_lut[user_dct['email']]
        superset.post(url_path=f'users/delete/{pk}')

Hope this helps someone.

Best regards Tridelt

k6407399 avatar Mar 20 '23 03:03 k6407399