def EMAIL(val): atpos = val.find('@') dotpos = val.find('.') if atpos == -1 or dotpos == -1: raise exceptions.BadRequest('Invalid Email Address given') elif dotpos < atpos: raise exceptions.BadRequest('Invalid Email Address given')
def NAME(val): for i in r"""<>"'""": if i in val: raise exceptions.BadRequest('The name you entered contains invalid characters') if len(val) < 2: raise exceptions.BadRequest('The name cannot be shorter than two characters') return True
def add(self, url, name, username='', godToken=None, **kwargs): if not self.portal_url: raise exceptions.BadRequest( 'portal_url not configured in js9 portal config.') if name in j.clients.zrobot.list(): raise exceptions.Conflict( 'robot instance: {} already in the portal'.format(name)) zrobot = j.clients.zrobot.new(name, data={ 'url': url, 'username': username }) if godToken: zrobot.god_token_set(godToken) ctx = kwargs['ctx'] authkey = j.apps.system.usermanager.addAuthkey('robot', name, ctx=ctx) try: zrobot.api.robot.AddWebHook({ 'url': '{0}/restmachine/zrobot/client/taskCallback?authkey={1}'. format(self.portal_url, authkey), 'kind': 'eco' }) except (requests.exceptions.ConnectionError, ConnectionError) as e: j.apps.system.usermanager.deleteAuthkey('robot', name, ctx=ctx) j.clients.zrobot.delete(name) raise return True
def list(self, **kwargs): if not j.core.state.configGetFromDict("myconfig", "path", ''): raise exceptions.BadRequest( "Please setup config manager before using the portal.") results = [] for instance in j.clients.zrobot.list(): results.append(self._zrobot_data(instance)) return results
def prepareCatalog(self, **args): catalog = { 'swagger': '2.0', 'basePath': '/restmachine/', 'paths': {}, 'tags': list() } catalog['info'] = { 'description': '', 'version': '7.0', 'title': 'JumpScale Actors', } catalog['definitions'] = { 'strarray': { 'type': 'array', 'items': { 'type': 'string' } }, 'intarray': { 'type': 'array', 'items': { 'type': 'integer' } }, 'object': { "type": "object", "additionalProperties": { "type": "string" } } } hide_private_api = args.get('skip_private') if 'actors' in args and args['actors']: actors = args['actors'].split(',') else: actors = j.portal.tools.server.active.getActors() if 'group' in args and args['group']: group = args['group'] groups = dict() for actor in actors: group_name = actor.split('__')[0] groups.setdefault(group_name, []).append(actor) if group in groups.keys(): actors = groups[group] else: raise exceptions.BadRequest("invalid actor group") for actor in sorted(actors): try: self.getDocForActor(actor, catalog, hide_private_api) except Exception as e: catalog['info'][ 'description'] += "<p class='alert alert-danger'>Failed to load actor %s error was %s</p>" % ( actor, e) return catalog
def generateJwtToken(self, **kwargs): ctx = kwargs['ctx'] oauth_ctx = ctx.env['beaker.session'].get('oauth', None) if oauth_ctx is None: raise exceptions.BadRequest("No oauth information in session") access_token = oauth_ctx.get('access_token', None) if access_token is None: raise exceptions.BadRequest("No access_token in session") # generate JWT headers = {'Authorization': 'bearer ' + access_token} url = 'https://itsyou.online/v1/oauth/jwt/refresh' resp = requests.post(url, headers=headers, verify=False) resp.raise_for_status() return resp.text
def createUser(self, username, password, email, groups, authkey=None, authkey_name=None): """ Creates a new user and returns the result of the creation. :param username: user's name :param password: user's password :param email: user's email :param groups: list of groups the user belongs :param authkey: user's auth key :param authkey_name: user's auth key's name :return: mongodb WriteResult object """ if self.userExists(username): raise exceptions.Conflict( "Username with name {} already exists".format(username)) if isinstance(email, str): email = [email] if self.emailExists(email): raise exceptions.Conflict( "User with email {} already exists".format(" or ".join(email))) user = self.usermodel() user.name = username if isinstance(groups, str): groups = [groups] user.groups = groups for group in user.groups: g = self.groupmodel.find({'name': group}) if g: continue g = self.groupmodel() g.name = group g.save() if authkey: if not authkey_name: raise exceptions.BadRequest("Authkey_name can't be none") user.authkeys[authkey_name] = authkey self.key2user[authkey] = username user.emails = email user.passwd = password return user.save()
def editGroup(self, name, description, users, **args): """ edit a group param:name name of group param:description of group result bool """ groups = j.portal.tools.models.system.Group.find({"name": name}) if not groups: raise exceptions.NotFound("Group with name %s does not exists" % name) else: group = groups[0] if users and isinstance(users, str): users = users.split(',') elif not users: users = [] users_old = [ u['name'] for u in j.portal.tools.models.system.User.find({'groups': name}) ] users_remove = [x for x in users_old if x not in users] for user_name in users_remove: user = self._getUser(user_name) user['groups'].remove(group.name) user.save() users_add = [x for x in users if x not in users_old] for user_name in users_add: user = self._getUser(user_name) if not user: raise exceptions.BadRequest( "user with name %s does not exists" % user) user['groups'].append(group.name) user.save() group['name'] = name group['description'] = description group.save() return True
def get(self, name, **kwargs): if not self.portal_url: raise exceptions.BadRequest( 'portal_url not configured in js9 portal config.') self._check_zrobot(name) return self._zrobot_data(name, True)
def GROUPNAME(val): m = re.match("[a-zA-Z0-9._-]+", val) if 2 < len(val) < 40 and m and m.end() == len(val): return True else: raise exceptions.BadRequest('Groupnames can only contain alphanumeric characters, dots, dashes, underscores and should be between 2 and 40 characters')
def USERNAME(val): m = re.match("[a-zA-Z0-9._-]+(?:@[a-zA-Z0-9._-]+)?", val) if 2 < len(val.split('@')[0]) < 40 and m and m.end() == len(val): return True else: raise exceptions.BadRequest('Usernames can only contain alphanumeric characters, dots, dashes, underscores and should be between 2 and 40 characters')