Commit c94f03fa authored by Mathieu Giraud's avatar Mathieu Giraud
Browse files

Merge branch 'feature-t/update_api_impersonate' into 'dev'

Feature t/update api impersonate

See merge request !1272
parents 3a132b6d 12876e40
Pipeline #734978 failed with stages
in 72 minutes and 58 seconds
......@@ -51,7 +51,7 @@ test_tools:
stage: test_tools
- apt-get update && apt-get install -y python3-pip
- pip3 install beautifulsoup4 tabulate requests requests_toolbelt
- pip3 install beautifulsoup4 bs4 tabulate requests requests-toolbelt urllib3
- make -C tools/tests
- .need_for_quick_test
......@@ -2,6 +2,7 @@
from api_vidjil import Vidjil
import argparse
import os
import getpass
TAGS = []
......@@ -157,6 +158,21 @@ if __name__ =='__main__':
if not args.public and not args.local:
if (args.stress or args.public):
if PUBLIC_USER == "":
PUBLIC_USER = input("Enter public login user:")
print( "Attempted to log as '%s' on public server" % PUBLIC_USER)
PUBLIC_PASSWORD = getpass.getpass("Password for public server:")
if args.local:
if LOCAL_USER == "":
LOCAL_USER = input("Enter local login user:")
print( "Attempted to log as '%s' on local server" % LOCAL_USER)
LOCAL_PASSWORD = getpass.getpass("Password for local server:")
if args.stress:
failures = 0
total = 20
# -*- coding: utf-8 -*-
from requests import Session
from bs4 import BeautifulSoup as bs
import sys
import json
import re
import requests
import os
import random, string
import argparse
import getpass
import sys
import errno
from collections import defaultdict
### Particular module to load
import subprocess
import pkg_resources
required = {'requests', 'bs4', 'tabulate', 'requests-toolbelt', 'urllib3'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
if missing:
python = sys.executable
print( f"Missing modules: {missing}")
cmd = [python, '-m', 'pip', 'install', *missing]
install = input("Do you want to install these modules? (y)es or no? ")
if install.lower() in ["y", "yes"]:
subprocess.check_call(cmd, stdout=subprocess.DEVNULL)
print(f"You choose to not install missing modules. \nYou can install them yourself by typing: `{' '.join(cmd)}`")
print(f"Script will end now.")
import requests
from tabulate import tabulate
from bs4 import BeautifulSoup
from requests_toolbelt import MultipartEncoder
from collections import defaultdict
# REmove warning if no SSL vérification
import urllib3
from tabulate import tabulate
TAGS = []
......@@ -129,9 +149,44 @@ class Vidjil:
self.logged = True
print( "Successful login as %s" % email)
# self.whoami()
whoami = self.whoami()
self.user_id = whoami["id"]
self.user_email = whoami["email"]
# todo; print admin status; groups ?
def impersonate( self, impersonate_id:int):
"""Lauch impersonating action. If not allowed to imperosnate, server will raise an error 'Forbidden' and the script will end.
impersonate_id (int): Id of the user to impersonate
Exception: Error when impersonate don't be succesful; multiple possible reasons: you are not admin, user don't exist
dict: Json response of the server that contain the set if available
new_url = self.url_server + f"/default/impersonate?id={impersonate_id}&next=/vidjil/user/index&="
result = self.request(new_url, "post")
whoami = self.whoami()
if whoami["id"] != impersonate_id:
raise(f"Error. Impersonate haven't work (id: {impersonate_id})")
if "redirect" in result.keys():
print( f"Successful impersonate of user {impersonate_id} ({whoami['email']})")
def stop_impersonate( self):
"""Stop impersonating action.
dict: Json response of the server that contain the set if available
new_url = self.url_server + f"/default/stop_impersonate"
result = self.request(new_url, "post")
whoami = self.whoami()
if whoami["id"] != self.user_id:
raise(f"Error. Stop Impersonate haven't work ( still id: {whoami['id']})")
if "redirect" in result.keys():
print( f"Successful desimpersonating")
def request(self, url:str, method:str, error_msg:bool=False, bypass_error:bool=False):
"""Send a request to server by a designed url and return a json content response
......@@ -154,6 +209,10 @@ class Vidjil:
raise("Error. request function don't get correct method argument")
if response.content in [b"Forbidden", b"Not Authorized"] :
print(f"This call is '{response.content}'. \nVerify that you try to access to a data that EXIST, of your OWN or that you use an ADMIN account.", file=sys.stderr)
content = json.loads(response.content)
except Exception as e:
......@@ -304,13 +363,17 @@ class Vidjil:
return self.request(new_url, "post")
def whoami(self):
def whoami(self, verbose=False):
"""Return a json with user informations on the server for logged user"""
new_url = self.url_server + "/default/whoami.json"
error_msg = "Error of login; WHOAMI function present on server ?"
user = self.request(new_url, "get", error_msg=error_msg, bypass_error=True)
print( "whoami: %s" % user)
for key_to_del in ["ignored_fields", "registration_id", "reset_password_key", "password", "registration_key"]:
user.pop(key_to_del, None)
if verbose:
print( "whoami: %s" % user)
return user
def getSamplesOfSet(self, set_id, config_id=-1):
new_url = self.url_server+"/sample_set/index.json?id=%s&config_id=%s" % (set_id, config_id)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment