def create(request: CreateRequest): user_id = request.id with translate_errors_context("creating user"): if user_id and User.objects(id=user_id).only("id"): raise errors.bad_request.UserIdExists(id=user_id) user = User(**request.to_struct()) user.save(force_insert=True)
def get_all(call: APICall, company_id, _): with translate_errors_context("retrieving users"): res = User.get_many(company=company_id, parameters=call.data, query_dict=call.data) call.result.data = {"users": res}
def update_user(user_id, company_id, data: dict) -> Tuple[int, dict]: """ Update user. :param user_id: user ID to update :param company_id: ID of company user belongs to :param data: mapping to update user by :return: (updated fields count, updated fields) pair """ update_fields = { k: v for k, v in create_fields.items() if k in User.user_set_allowed() } partial_update_dict = parse_from_call(data, update_fields, User.get_fields()) with translate_errors_context("updating user"): return User.safe_update(company_id, user_id, partial_update_dict)
def get_current_user(call: APICall, company_id, _): with translate_errors_context("retrieving users"): projection = ({"company.name"}.union(User.get_fields()).difference( User.get_exclude_fields())) res = User.get_many_with_join( query=Q(id=call.identity.user), company=company_id, override_projection=projection, ) if not res: raise errors.bad_request.InvalidUser("failed loading user") user = res[0] user["role"] = call.identity.role resp = {"user": user} call.result.data = resp
def ensure_fixed_user(user: FixedUser, company_id: str, log: Logger): if User.objects(id=user.user_id).first(): return data = attr.asdict(user) data["id"] = user.user_id data["email"] = f"{user.user_id}@example.com" data["role"] = Role.user _ensure_auth_user(user_data=data, company_id=company_id, log=log) given_name, _, family_name = user.name.partition(" ") User( id=user.user_id, company=company_id, name=user.name, given_name=given_name, family_name=family_name, ).save()
def get_all_ex(call): assert isinstance(call, APICall) with translate_errors_context("retrieving users"): res = User.get_many_with_join( company=call.identity.company, query_dict=call.data, query_options=get_all_query_options, ) call.result.data = {"users": res}
def _ensure_backend_user(user_id: str, company_id: str, user_name: str): given_name, _, family_name = user_name.partition(" ") User( id=user_id, company=company_id, name=user_name, given_name=given_name, family_name=family_name, ).save() return user_id
def ensure_fixed_user(user: FixedUser, company_id: str, log: Logger): if User.objects(id=user.user_id).first(): return data = attr.asdict(user) data["id"] = user.user_id data["email"] = f"{user.user_id}@example.com" data["role"] = Role.user _ensure_auth_user(user_data=data, company_id=company_id, log=log) return _ensure_backend_user(user.user_id, company_id, user.name)
def get_all_ex2_8(call: APICall, company_id, _): with translate_errors_context("retrieving users"): data = call.data active_in_projects = call.data.get("active_in_projects", None) if active_in_projects is not None: active_users = project_bll.get_active_users( company_id, active_in_projects, call.data.get("id")) active_users.discard(None) if not active_users: call.result.data = {"users": []} return data = data.copy() data["id"] = list(active_users) res = User.get_many_with_join(company=company_id, query_dict=data) call.result.data = {"users": res}
def set_preferences(call, company_id, req_model): # type: (APICall, str, SetPreferencesRequest) -> Dict assert isinstance(call, APICall) changes = req_model.preferences def invalid_key(_, key, __): if not isinstance(key, str): return True elif key.startswith("$") or "." in key: raise errors.bad_request.FieldsValueError( f"Key {key} is invalid. Keys cannot start with '$' or contain '.'." ) return True remap(changes, visit=invalid_key) base_preferences = get_user_preferences(call) new_preferences = deepcopy(base_preferences) for key, value in changes.items(): try: dpath.new(new_preferences, key, value, separator=".") except Exception: log.exception( 'invalid preferences update for user "{}": key=`%s`, value=`%s`', key, value, ) raise errors.bad_request.InvalidPreferencesUpdate(key=key, value=value) if new_preferences == base_preferences: updated, fields = 0, {} else: with translate_errors_context("updating user preferences"): updated = User.objects(id=call.identity.user, company=company_id).update( upsert=False, preferences=dumps(new_preferences)) return { "updated": updated, "fields": { "preferences": new_preferences } if updated else {}, }
def ensure_fixed_user(user: FixedUser, log: Logger): db_user = User.objects(company=user.company, id=user.user_id).first() if db_user: # noinspection PyBroadException try: log.info(f"Updating user name: {user.name}") given_name, _, family_name = user.name.partition(" ") db_user.update(name=user.name, given_name=given_name, family_name=family_name) except Exception: pass return data = attr.asdict(user) data["id"] = user.user_id data["email"] = f"{user.user_id}@example.com" data["role"] = Role.guest if user.is_guest else Role.user _ensure_auth_user(user_data=data, company_id=user.company, log=log) return _ensure_backend_user(user.user_id, user.company, user.name)
def get_user(call, user_id, only=None): """ Get user object by the user's ID :param call: API call :param user_id: user ID :param only: fields to include in projection, by default all :return: User object """ if call.identity.role in (Role.system, ): # allow system users to get info for all users query = dict(id=user_id) else: query = dict(id=user_id, company=call.identity.company) with translate_errors_context("retrieving user"): user = User.objects(**query) if only: user = user.only(*only) res = user.first() if not res: raise errors.bad_request.InvalidUserId(**query) return res.to_proper_dict()
from apimodels.base import UpdateResponse from apimodels.users import ( CreateRequest, SetPreferencesRequest, ) from bll.user import UserBLL from config import config from database.errors import translate_errors_context from database.model.auth import Role from database.model.company import Company from database.model.user import User from database.utils import parse_from_call from service_repo import APICall, endpoint log = config.logger(__file__) get_all_query_options = User.QueryParameterOptions(list_fields=("id", )) def get_user(call, user_id, only=None): """ Get user object by the user's ID :param call: API call :param user_id: user ID :param only: fields to include in projection, by default all :return: User object """ if call.identity.role in (Role.system, ): # allow system users to get info for all users query = dict(id=user_id) else: query = dict(id=user_id, company=call.identity.company)
def add_user(name, passwd): user = User(name, passwd) db.session.add(user) db.session.commit() return
def delete(user_id: str): with translate_errors_context("deleting user"): res = User.objects(id=user_id).delete() if not res: raise errors.bad_request.InvalidUserId(id=user_id)