How can I add many users with known passwords - rocket.chat

I'm setting up a rocket chat server in an air gapped testbed where I'll have thousands of automated users talking to each other to generate network traffic. I had seen the user import via CSV documented here. That lets me create my users, but not with pre-assigned passwords. Looking in programs/server/packages/rocketchat_importer-csv.js I see that it is setting the password to a formulaic string including the current date.
That's as good as a random password for my needs.
Is there a way to, say, include another column in the CSV where I can assign the password for each user?
I installed it via snaps on Ubuntu 16.04.4 if that affects anything.

In the end, I wrote a python script to do the job making a web request for each line of the CSV. Here's what I came up with:
import csv
import json
import requests
def main(csv_path, admin_user, admin_pass, base_url):
"""
Read the given CSV of the format:
loginname, email, real name, password
and create all the users described in it in the Rocket.Chat server
available at `base_url`
"""
login_json = json.dumps({'username': admin_user, 'password': admin_pass})
response = requests.post(base_url + '/api/v1/login', data=login_json)
data = response.json()['data']
token = data['authToken']
userid = data['userId']
headers = {
'X-Auth-Token': token,
'X-User-Id': userid,
'Content-type': 'application/json',
}
with open(csv_path) as raw:
reader = csv.reader(raw)
for user in reader:
request = {
'username': user[0],
'email': user[1],
'name': user[2],
'password': user[3],
}
ret = requests.post(base_url + '/api/v1/users.create',
data=json.dumps(request), headers=headers)

Related

Plaid Account ID returns INVALID_ACCOUNT_ID when used as Options in requests in Development

When my application runs in the Development environment, the Account ID that Plaid returns will result in an "INVALID_ACCOUNT_ID" error when applied in an Options object that is sent along with the request. The example code is a simple flow that I expect my application to support. It loads in Accounts from Plaid based on the access token and captures the account IDs, and then randomly chooses an account to query Plaid for the current balance.
import os
import random
from typing import Any
import plaid
from plaid.api import plaid_api
from plaid.model.accounts_balance_get_request import AccountsBalanceGetRequest
from plaid.model.accounts_get_request import AccountsGetRequest
from plaid.model.accounts_get_request_options import AccountsGetRequestOptions
# Load in from environ
plaid_env = os.environ.get("PLAID_ENV", "sandbox").title()
client_id = os.environ["PLAID_CLIENT_ID"]
secret = os.environ["PLAID_SECRET"]
access_token = os.environ["ACCESS_TOKEN"]
# Initialize Plaid Client
configuration = plaid.Configuration(
host=getattr(plaid.Environment, plaid_env),
api_key={
"clientId": client_id,
"secret": secret,
},
)
api_client = plaid.ApiClient(configuration)
plaid_client = plaid_api.PlaidApi(api_client)
# Request for all account balances
account_balance_request = AccountsBalanceGetRequest(access_token=access_token)
account_balance_response = plaid_client.accounts_balance_get(account_balance_request)
# Data structure for accounts
accounts = [
{
"account_name": a["official_name"],
"account_id": a["account_id"],
}
for a in account_balance_response["accounts"]
]
# Pick one account to operate on
test_account = random.choice(accounts)
# Request for Account Balance this account's balance
try:
test_account_balance_request = AccountsGetRequest(
access_token=access_token,
options=AccountsGetRequestOptions(account_ids=[test_account["account_id"]]),
)
test_account_balance_response = plaid_client.accounts_get(
test_account_balance_request
)
print(
f"Balance of {test_account['account_name']} is "
f"{test_account_balance_response['accounts'][0]['balances']['current']}"
)
except Exception as e:
print(f"Unable to update balance of account. Error = {e}")
When operating in the Sandbox, this works perfectly fine:
Balance of Plaid Gold Standard 0% Interest Checking is 110.0
When operating in the Development environment, it returns:
Unable to update balance of account. Error = (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Server': 'nginx', 'Date': 'Wed, 05 Oct 2022 02:58:30 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '308', 'Connection': 'keep-alive', 'plaid-version': '2020-09-14'})
HTTP response body: {
"display_message": null,
"documentation_url": "https://plaid.com/docs/?ref=error#invalid-input-errors",
"error_code": "INVALID_ACCOUNT_ID",
"error_message": "one or more of the account IDs is invalid",
"error_type": "INVALID_INPUT",
"request_id": "",
"suggested_action": null
}
While this sample code is redundant, I am experiencing the INVALID_ACCOUNT_ID error on any function that supports account_ids in the options. If I remove the Options objects from offending requests in my application, the requests works. I have reviewed the causes that are cited in the documentation and I'm not convinced any of them relate to this issue. Would anyone be able to help?

Google Cloud Identity API - missing hostname fields/data

Thank you beforehand for taking the time to check out my question.
While using Cloud Identity API to query for managed devices (Windows, Mac) details from our Google Workspace, I am able to query successfully by the "device ID" assigned by google, however, the "hostname" field is not included in the response.
This is an example of the call and response that I get.
https://cloudidentity.googleapis.com/v1/devices
def device_query():
FILTER = urllib.parse.quote_plus('serial:'+<serialNumber>)
list_url = BASE_URL + 'devices?name=' + FILTER
auth_header = {'Authorization': 'Bearer ' + getAuthToken()}
content = urllib.request.urlopen(
urllib.request.Request(list_url, headers=auth_header)).read()
response = json.loads(content)
deviceDetails = response['devices']
print(deviceDetails)
{'devices':
[{'name': 'devices/xxxxxxxxxxxx',
'createTime': '9999-99-99T20:11:31.680Z',
'lastSyncTime': '9999-99-99T15:01:51.922Z',
'ownerType': 'Company Owned',
'model': 'Windows',
'osVersion': 'Win10',
'deviceType': 'Windows',
'serialNumber': '737dh39he8d3978'}]
}
When looking at any device through Workspace, I can see similar details including the hostname.
[Workspace UI device hostname example][1]
The UI URL looks like this: https://admin.google.com/ac/devices/details/8613sw4fa4-90b2-5098-61384-d139d0775r9gg/information?uid=7dhdhsw7hd3h83d&dt=4
This is the API endpoint: cloudidentity.googleapis.com/v1 I am using to retrieve device data.

How to get the course ID for Google Classroom API

I'm trying to use Google Classroom API, I've read through their documentation, and the course ID is used for basically everything, but they never explained where to find the course ID for a course.
It also seems like when you create a course, the function would return the course ID, but I'm wondering if it's possible to get the course ID for courses that already exist.
As shown in the quickstart page for the documentation (https://developers.google.com/classroom/quickstart/python), you can run a piece of code to list the first 10 courses the user has access to with their credentials. You can then add a print(course['id']) statement whilst iterating through the courses to print the id of the courses you have retrieved. The python example is shown below
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']
def main():
"""Shows basic usage of the Classroom API.
Prints the names of the first 10 courses the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('classroom', 'v1', credentials=creds)
# Call the Classroom API
results = service.courses().list(pageSize=10).execute()
courses = results.get('courses', [])
if not courses:
print('No courses found.')
else:
print('Courses:')
for course in courses:
print(course['name'])
print(course['id'])
if __name__ == '__main__':
main()
I use this in nodejs/javascript to retrieve all classroom
const { google } = require("googleapis");
const classroom = google.classroom('v1');
const SCOPES = [
"https://www.googleapis.com/auth/classroom.rosters",
"https://www.googleapis.com/auth/classroom.profile.emails",
"https://www.googleapis.com/auth/classroom.profile.photos",
"https://www.googleapis.com/auth/classroom.courses"
];
google.options({
auth: client,
});
//retrieve all classroom
async function getClassroom() {
try {
const res = await classroom.courses.list(
// {
// pageSize: 10,
// pageToken: "",
// }
);
console.log(res.data, "res");
} catch (error) {
console.error("Error:", error.message,);
}
}
Note: The client is my preferred authorization method

Unable to get folder by id when using Boxr JWT get_user_token- Box API

I'm unable to a folder by providing an id to that folder using Boxr gem. Previously I didn't has the enterprise settings as shown in this post which I have now fixed. I'm creating a token using JWT authentication get_user_token method the following way.
token = Boxr::get_user_token("38521XXXX", private_key: ENV.fetch('JWT_PRIVATE_KEY'), private_key_password: ENV.fetch('JWT_PRIVATE_KEY_PASSWORD'), public_key_id: ENV.fetch('JWT_PUBLIC_KEY_ID'), client_id: ENV.fetch('BOX_CLIENT_ID'), client_secret: ENV.fetch('BOX_CLIENT_SECRET'))
I then pass this this token when creating a client.
client = Boxr::Client.new(token)
when I check the current user on client this is what I get:
client.current_user
=> {"type"=>"user",
"id"=>"60853XXXX",
"name"=>"OnlineAppsPoC",
"login"=>"AutomationUser_629741_06JgxiPtPj#boxdevedition.com",
"created_at"=>"2018-10-04T08:41:32-07:00",
"modified_at"=>"2018-10-04T08:41:50-07:00",
"language"=>"en",
"timezone"=>"America/Los_Angeles",
"space_amount"=>10737418240,
"space_used"=>0,
"max_upload_size"=>2147483648,
"status"=>"active",
"job_title"=>"",
"phone"=>"",
"address"=>"",
"avatar_url"=>"https://app.box.com/api/avatar/large/6085300897"}
When I run client.methods I see there is folder_from_id however when I call that method I get the following error:
pry(#<FormsController>)> client.folder_from_id("123456", fields: [])
Boxr::BoxrError: 404: Not Found
from /usr/local/bundle/gems/boxr-1.4.0/lib/boxr/client.rb:239:in `check_response_status'
I have the following settings:
I also authorize the application. Not sure what else to do.
token = Boxr::get_user_token(user_id,
private_key: ENV.fetch('JWT_PRIVATE_KEY'),
private_key_password: ENV.fetch('JWT_PRIVATE_KEY_PASSWORD'),
public_key_id: ENV.fetch('JWT_PUBLIC_KEY_ID'),
client_id: ENV.fetch('BOX_CLIENT_ID'),
client_secret: ENV.fetch('BOX_CLIENT_SECRET'))
client = Boxr::Client.new(token.access_token)
folder = client.folder_from_id(folder_id)
client.upload_file(file_path, folder)
For anybody using C# and BOXJWT.
You just need to have a boxManager set up and will get you with anything you need, say BoxFile, Folder etc.
If you have the folderID, well & good, but if you need to retrieve, this can be done as shown below:
string inputFolderId = _boxManager.GetFolder(RootFolderID).Folders.Where(i => i.Name == boxFolder).FirstOrDefault().Id; //Retrieves FolderId
Folder inputFolder = _boxManager.GetFolder(inputFolderId);

Google Vault API HttpError 500 "Internal error encountered."

I'm getting the following error when trying to create a hold using the Google Vault API:
HttpError 500 when requesting
https://vault.googleapis.com/v1/matters/{matterId}/holds?alt=json
returned "Internal error encountered."
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/ediscovery']
SERVICE_ACCOUNT_FILE = './serviceaccount.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject('delegateuser#example.com')
client = googleapiclient.discovery.build('vault', 'v1', credentials=delegated_credentials)
data = { 'name': 'test', 'accounts': [{'email': 'testuser#example.com' }], 'corpus': 'MAIL', 'query': { 'mailQuery': {'terms': 'to:ceo#company.com'} }}
results = client.matters().holds().create(matterId='{matterId}', body=data).execute()
I've replaced the actual matterId string with {matterId}.
Creating matters, listing matters and listing holds work just fine.
I've tried different combinations of fields to include in the request body but the docs are not clear as to which are required...
It turns out you can't use 'email' in holds().create() - you must use accountId, or the 'id' number for the gmail user.
You can use emails to create holds
https://developers.google.com/vault/guides/holds#create_a_hold_for_mail_on_specific_user_accounts_with_a_search_query

Resources