async def create_short_url( item: schema.Url, db: Session = Depends(get_db) ): # Проверка на правильность URL if validators.url(item.url) or validators.domain(item.url): # Проверка на уже имеющийся в БД свой URL try: url_obj = service.create_short_url(db, item) except IntegrityError: return {"url": ALIAS_ALREADY_EXIST} else: return {"url": INVALID_URL} # Конфигурирование URL в зависимости от заданных параметров if item.special_url: # Проверка на случайное попадание собственного URL в генерируемый try: short_url.decode_url(item.special_url) return {"url": INVALID_ALIAS} except ValueError: # Проверка правильности заданного собственного URL if validators.slug(item.special_url): out_url = DOMAIN + item.special_url else: out_url = INVALID_ALIAS else: # Крафт URL по его ID в БД out_url = "http://127.0.0.1:8000/" + short_url.encode_url(url_obj.id) return {"url": out_url}
def verify(**kwargs): """Verifies a markdown file before publishing to your blog""" # assume this is not silent silent = kwargs.get('silent', None) # get the url url = kwargs['url'] # make sure url is valid if not validators.url(url): print('{} is not a valid URL'.format(url)) return # make the parser md = markdown.Markdown(extensions=['markdown.extensions.meta']) # open markdown file and mark it down with open(kwargs['md']) as f: body = md.convert(f.read()) # if md.Meta doesn't have created and title reject it if 'created' not in md.Meta.keys() or \ 'title' not in md.Meta.keys() or \ 'slug' not in md.Meta.keys(): print('Error: meta section of doc requires "slug", "created" "title"') return False # validate slug if not validators.slug(md.Meta['slug'][0]): print('Error: "{}" is not a valid slug.'.format(md.Meta['slug'][0])) return # validate date try: datetime.datetime.strptime( md.Meta['created'][0], DATETIME_FORMAT) except (IndexError, TypeError, ValueError): print('Error: "{}" is not a valid datetime for "{}"'.format( md.Meta['created'][0], DATETIME_FORMAT)) return # if we have no html reject it. if len(body) == 0: print('Error: document contains no html') return False # all good if this is silent return a bool, else text if not silent: print('Success: looks good') else: return { 'created': md.Meta['created'][0], 'title': md.Meta['title'][0], 'slug': md.Meta['slug'][0], 'body': body }
def validate_name(self, key, value): if len(value) > 64: # Value cannot exceed 64 characters message = 'First and lastnames cannot exceed 64 characters' raise AssertionError(message) if not validators.slug(value) and value != '': # Username should only accept a restricted set of characters message = 'First and lastnames can only contain alphanumeric characters, hyphens and underscores.' raise AssertionError(message) return value
def slug(value): """ Validate whether or not the given string is a valid slug. Args: value (str): the value to validate. Raises: ValidationError: when the value is not a valid slug. """ if not validators.slug(value): raise ValidationError('{!r} is not a valid slug'.format(value))
def validate_url(value: str) -> bool: if (validatorslib.url(value) or validatorslib.domain(value) or validatorslib.ipv4(value) or validatorslib.ipv6(value) or validatorslib.ipv4_cidr(value) or validatorslib.ipv6_cidr(value) or validatorslib.slug(value)): return True if DOMAIN_PORT_REGEX.match(value): return True return False
def validate_client_name(self, key, client): if not client: # Client name must exist raise AssertionError('Client name cannot be null.') if len(client) > 64: # Name should not exceed 64 chars raise AssertionError('Client name cannot exceed 64 characters.') if not validators.slug(client) and client != '': # Username should only accept a restricted set of characters message = 'Client name can only contain alphanumeric characters, hyphens and underscores.' raise AssertionError(message) return client
def createsqluser(self, user): if validators.slug(user) is not True: raise Exception("The database user contains unsupported characters.") try: userexists = sqlexec("SELECT * FROM mysql.user WHERE User = '******'".format(user)) except: userexists = False if userexists: raise Exception('A MySQL user with username {} already exists.'.format(user)) password = "" while len(password.strip()) < 5: password = getpass() if len(password.strip()) < 5: print(colored("Password should contain at least 5 characters.", "yellow")) if len(password.strip()) >= 5: sqlexec("CREATE USER '{}'@'localhost' IDENTIFIED BY '{}'".format(user, password)) sqlexec("FLUSH PRIVILEGES")
def validate_username(self, key, username): if not username: # Username cannot be Null raise AssertionError('No username provided.') if User.query.filter_by(username=username).first(): # Username must be unique raise AssertionError('User is already in use') if len(username) > 32: # Username cannot exceed 32 chars raise AssertionError('Username must be 32 charactes maximum') if not validators.slug(username): # Username should only accept a restricted set of characters message = 'The username can only contain alphanumeric characters, hyphens and underscores.' raise AssertionError(message) return username
def validate_project_name(self, key, name): if not name: # Project name must exist raise AssertionError('Project name cannot be null.') if Project.query.filter_by(name=name).first(): # Project name must be unique raise AssertionError('This project already exists.') if len(name) > 64: # Name should not exceed 64 chars raise AssertionError('Project name cannot exceed 64 characters.') if not validators.slug(name) and name != '': # Username should only accept a restricted set of characters message = 'Project name can only contain alphanumeric characters, hyphens and underscores.' raise AssertionError(message) return name
def generate_config(): # Generate a hidden file in pwd config_file = ".ghauth.cfg" if not os.path.isfile(config_file): logging.info("No configuration file found, creating one now...") else: if not ("USER" in config and "PASSWORD" in config and "TOKEN" in config): logging.info("Detected that some configuration variables may not exist in the {0} file, creating them now...").format(config_file) pass if not "USER" in config: while True: USER = raw_input("Enter GitHub username: "******"Please enter a valid GitHub username.") else: break save_config(config_file, "USER",USER) if not "PASSWORD" in config: while True: plain_password = getpass.getpass('Enter GitHub password: '******'password', plain_password) # Write the encrypted_password out to it's own file open(".ghpassword".format(config_dir), "w").write(encrypted_password); os.chmod(".ghpassword", 0666) # Save the config so we know password has been captured save_config(config_file, "PASSWORD", "ENCRYPTED") if not "TOKEN" in config: while True: TOKEN = raw_input("Enter GitHub Personal access token: ") if not validators.length(from_number, min=41): print("Please enter a valid GitHub token.") else: break save_config(config_file, "TOKEN",TOKEN)
async def m_register(self, data): global objects antispam(self.getip(), "register_before_valid", 50) users_c = self.count_users() errors = [] if not validators.email(data['email']): errors += ['Email invalid'] if not validators.email(data['kindle_email'] ) or '@kindle.com' not in data['kindle_email']: errors += ['Kindle email invalid'] if not validators.slug(data['username']): errors += ['Username invalid'] if len(data['username']) < 6: errors += ['Username has to be at least 6 characters long'] if len(data['password']) < 6: errors += ['Password has to be at least 6 characters long'] if users_c >= 50: errors += [ "The user limit has already reached 50. Please try again and consider letting us know if you'd prefer premium ($1 a month)." ] if len(errors) > 0: self.send_data({ "key": "form_register", "success": False, "errors": errors }) return None #check if it exists already try: user = await objects.get(UserModel, username=data['username']) self.send_data({ "key": "form_register", "success": False, "errors": ["Username already exists"] }) return None except UserModel.DoesNotExist: pass try: user = await objects.get(UserModel, email=data['email']) self.send_data({ "key": "form_register", "success": False, "errors": ["Email already exists"] }) return None except UserModel.DoesNotExist: pass antispam(self.getip(), "register", 10) last_sent = get_datetime_today_3_30() activation_key = id_generator(6) user = await objects.create(UserModel, username=data['username'], password=hash_password(data['password']), kindle_email=data['kindle_email'], email=data['email'], activation_key=activation_key, activated=False, last_sent=last_sent) send_email_activation(data['email'], activation_key) self.send_data({"key": "form_register", "success": True}) return user
def main(): sp = ServerPilot() ignoredbs = ["information_schema", "mysql", "performance_schema", "sys"] ignoresqlusers = [ "root", "sp-admin", "debian-sys-maint", "mysql.session", "mysql.sys" ] ap = argparse.ArgumentParser( description= 'A powerful tool to manage servers provisioned using ServerPilot.io.') subparsers = ap.add_subparsers(dest="action") # SSH Users subparsers.add_parser('listsysusers', help='Show all SSH users existing on this server.') sysuser = subparsers.add_parser('createsysuser', help='Create a new SSH user.') sysuser.add_argument('--username', dest='username', help='Username for your new SSH user.', required=True) # Apps listapps = subparsers.add_parser('listapps', help='Show all existing apps.') listapps.add_argument('--user', dest='user', help='SSH user to list apps for.', required=False) createapp = subparsers.add_parser('createapp', help='Create a new app.') createapp.add_argument('--name', dest='name', help='The name for your new app.', required=True) createapp.add_argument( '--user', dest='user', help= 'The SSH username for your new app. User will be created if not present.', required=True) createapp.add_argument('--php', dest='php', help='PHP version for your new app.', default=False) createapp.add_argument( '--domains', dest='domains', help='Comma-separated domains list, i.e. rehmat.works,www.rehmat.works', required=True) updatedomains = subparsers.add_parser( 'updatedomains', help='Update an apps\' domains and recreate vhost files.') updatedomains.add_argument( '--app', dest='app', help='The name of your app for which you want to modify the domains.', required=True) updatedomains.add_argument( '--domains', dest='domains', help='Comma-separated domains list, i.e. rehmat.works,www.rehmat.works', required=True) changephp = subparsers.add_parser('changephp', help='Change PHP version of an app.') changephp.add_argument( '--app', dest='app', help='The name of the app that you want to change PHP version for.', required=True) changephp.add_argument('--php', dest='php', help='PHP version (Available: {}).'.format( ', '.join(sp.availphpversions())), choices=sp.availphpversions(), required=True) changephpall = subparsers.add_parser( 'changephpall', help='Change PHP version for all apps.') changephpall.add_argument( '--user', dest='user', help= 'SSH user to update PHP version for their owned apps. If not provided, all apps will be affected with this change.', required=False) changephpall.add_argument('--php', dest='php', help='PHP version (Available: {}).'.format( ', '.join(sp.availphpversions())), choices=sp.availphpversions(), required=True) delapp = subparsers.add_parser('deleteapp', help='Delete an app permanently.') delapp.add_argument('--name', dest='name', help='The name of the app that you want to delete.', required=True) delapps = subparsers.add_parser('delallapps', help='Delete all apps permanently.') delapps.add_argument( '--user', dest='user', help= 'SSH user to delete their owned apps. If not provided, all apps from all users will be deleted.', required=False) # MySQL users subparsers.add_parser('listdbusers', help='Show all existing database users.') sqluser = subparsers.add_parser('createsqluser', help='Create a new MySQL user.') sqluser.add_argument('--name', dest='name', help='The name for your new MySQL user.', required=True) sqluserpass = subparsers.add_parser( 'updatesqlpassword', help='Update any MySQL user\'s password.') sqluserpass.add_argument( '--user', dest='user', help= 'The name for MySQL user for which you want to update the password.', required=True) deldbuser = subparsers.add_parser('dropuser', help='Drop a MySQL user.') deldbuser.add_argument( '--name', dest='name', help='The name of the database user that you want to delete.', required=True) subparsers.add_parser( 'dropallsqlusers', help='Drop all MySQL users except system users ({}).'.format( ', '.join(ignoresqlusers))) # MySQL database subparsers.add_parser('listdbs', help='Show all existing databases.') createdb = subparsers.add_parser('createdb', help='Create a new MySQL database.') createdb.add_argument('--name', dest='name', help='The name for your new database.', required=True) createdb.add_argument('--user', dest='user', help='MySQL user for the new database.', required=True) dropdb = subparsers.add_parser('dropdb', help='Drop a MySQL database.') dropdb.add_argument( '--name', dest='name', help='The name of the database that you want to delete.', required=True) subparsers.add_parser( 'dropalldbs', help='Drop all databases except system databases ({}).'.format( ', '.join(ignoredbs))) # SSL ssl = subparsers.add_parser('getcert', help='Get letsencrypt cert for an app.') ssl.add_argument('--app', dest='app', help='App name for which you want to get an SSL cert.', required=True) sslall = subparsers.add_parser('getcerts', help='Get letsencrypt certs for all apps.') sslall.add_argument( '--user', dest='user', help= 'SSH user to activate SSL for their owned apps. If not provided, SSL will be activated for all apps.', required=False) ussl = subparsers.add_parser('removecert', help='Uninstall SSL cert from an app.') ussl.add_argument( '--app', dest='app', help='App name from which you want to uninstall the SSL cert.', required=True) usslall = subparsers.add_parser('removecerts', help='Uninstall SSL certs for all apps.') usslall.add_argument( '--user', dest='user', help= 'SSH user to remove SSLs for their owned apps. If not provided, SSL will be uninstalled from all apps.', required=False) forcessl = subparsers.add_parser('forcessl', help='Force SSL certificate for an app.') forcessl.add_argument( '--app', dest='app', help='App name for which you want to force the HTTPS scheme.', required=True) unforcessl = subparsers.add_parser( 'unforcessl', help='Unforce SSL certificate for an app.') unforcessl.add_argument( '--app', dest='app', help='App name for which you want to unforce the HTTPS scheme.', required=True) forceall = subparsers.add_parser('forceall', help='Force HTTPs for all apps.') forceall.add_argument( '--user', dest='user', help= 'SSH user to force HTTPs for their owned apps. If not provided, SSL will be forced for all apps.', required=False) unforceall = subparsers.add_parser('unforceall', help='Unforce HTTPs for all apps.') unforceall.add_argument( '--user', dest='user', help= 'SSH user to unforce HTTPs for their owned apps. If not provided, SSL will be unforced for all apps.', required=False) # Deny unknown domains subparsers.add_parser('denyunknown', help='Deny requests from unknown domains.') # Allow unknown domains subparsers.add_parser('allowunknown', help='Allow requests from unknown domains.') args = ap.parse_args() if len(sys.argv) <= 1: ap.print_help() sys.exit(0) if args.action == 'listapps': if args.user: sp.setuser(args.user) try: sp.listapps() except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'createapp': if 'dbmetainfo' in args.name: print( colored( 'The name {} is protected. Please use a different name for your app.' .format(args.name), 'yellow')) sys.exit(0) if validators.slug(args.name) is not True: print( colored( 'App name should only contain letters, dashes/hyphens and numbers.', 'yellow')) sys.exit(0) if validators.slug(args.user) is not True: print( colored( 'SSH username should only contain letters, dashes/hyphens and numbers.', 'yellow')) sys.exit(0) if args.php: try: sp.setphp(args.php) except Exception as e: print(colored(str(e), 'yellow')) sys.exit(0) try: sp.setdomains(args.domains) except Exception as e: print(colored(str(e), 'yellow')) sys.exit(0) sp.setapp(args.name) sp.setuser(args.user) if sp.isvalidapp(): print( colored( 'An app with name {} already exists.'.format(args.name), 'yellow')) sys.exit(0) try: sp.createapp() print( colored( 'The app {} has been successfully created!'.format( args.name), 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'updatedomains': try: sp.setdomains(args.domains) except Exception as e: print(colored(str(e), 'yellow')) sys.exit(0) sp.setapp(args.app) try: sp.updatedomains() print(colored('App domains have been updated.', 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'changephp': sp.setphp(args.php) sp.setapp(args.app) try: sp.changephpversion() print( colored( 'PHP version for the app {} is changed to {}'.format( args.app, args.php), 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'changephpall': if args.user: sp.setuser(args.user) msg = 'All apps owned by {} are now using PHP {}.'.format( args.user, args.php) confirmmsg = 'Do you really want to update PHP version for all apps owned by {} to {}?'.format( args.user, args.php) else: msg = 'All apps existing on this server are now using PHP {}.'.format( args.php) confirmmsg = 'Do you really want to update PHP version to {} for all apps existing on this server?'.format( args.php) sp.setphp(args.php) if doconfirm(confirmmsg): try: sp.changephpall() print(colored(msg, 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'denyunknown': try: sp.denyunknown() print(colored('Unknown domains are now not allowed.', 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'allowunknown': try: sp.allowunknown() print( colored( 'Unknown domains are now allowed to serve the first app.', 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'deleteapp': if doconfirm( "Do you really want to delete the app {} permanently?".format( args.name)): sp.setapp(args.name) if not sp.isvalidapp(): print( colored( 'The app {} you are trying to delete does not exist.'. format(args.name), 'yellow')) sys.exit(0) try: sp.delapp() print( colored( 'The app {} has been successfully deleted!'.format( args.name), 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'delallapps': if args.user: sp.setuser(args.user) msg = 'All apps owned by {} have been deleted.'.format(args.user) confirmmsg = 'Do you really want to delete all apps owned by {}?'.format( args.user) else: msg = 'All apps existing on this server have been deleted.' confirmmsg = 'Do you really want to delete all apps existing on this server?' if doconfirm(confirmmsg): try: sp.deleteallapps() print(colored(msg, 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'createsqluser': try: sp.createsqluser(args.name) print( colored( 'MySQL user {} has been successfully created.'.format( args.name), 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'updatesqlpassword': try: dbuexists = sqlexec( "SELECT * FROM mysql.user WHERE User = '******'".format(args.user)) except: dbuexists = False if not dbuexists: print( colored("User {} does not exist.".format(args.user), "yellow")) sys.exit(0) password = "" while len(password.strip()) < 5: password = getpass() if len(password.strip()) < 5: print( colored("Password should contain at least 5 characters.", "yellow")) if len(password.strip()) >= 5: try: sqlexec( "UPDATE mysql.user SET authentication_string=PASSWORD('{}') WHERE USER='******'" .format(password, args.user)) sqlexec("FLUSH PRIVILEGES") print( colored( 'MySQL user {}\'s password has been successfully updated.' .format(args.user), 'green')) except Exception as e: try: sqlexec( "UPDATE mysql.user SET Password=PASSWORD('{}') WHERE USER='******'" .format(password, args.user)) sqlexec("FLUSH PRIVILEGES") print( colored( 'MySQL user {}\'s password has been successfully updated.' .format(args.user), 'green')) except: print(colored(str(e), 'yellow')) if args.action == 'createdb': try: dbuexists = sqlexec( "SELECT * FROM mysql.user WHERE User = '******'".format(args.user)) except: dbuexists = False if not dbuexists: print( colored( "User {} does not exist. Please create it first.".format( args.user), "yellow")) sys.exit(0) if validators.slug(args.name) is not True: print( colored( "The database name should only contain letters, numbers, hyphens and dashes.", "yellow")) sys.exit(0) try: sqlexec("CREATE DATABASE {}".format(args.name)) sqlexec("GRANT ALL PRIVILEGES ON {}.* TO '{}'@'localhost'".format( args.name, args.user)) sqlexec("FLUSH PRIVILEGES") metainfo = {'name': args.name, 'user': args.user} sp.savemeta(metainfo, 'dbmetainfo-{}'.format(args.name)) print( colored( "The database {} has been created and all permissions are granted to {} on this database." .format(args.name, args.user), "green")) except Exception as e: print(colored(str(e), "yellow")) if args.action == 'dropuser': if doconfirm("Do you really want to drop the user {}?".format( args.name)): if args.name.lower() in ignoresqlusers: print( colored( "You cannot drop the system user {}.".format( args.name), "yellow")) sys.exit(0) try: sp.dropsqluser(args.name) print( colored( "The database user {} has been dropped.".format( args.name), "green")) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'dropdb': if doconfirm("Do you really want to drop the database {}?".format( args.name)): if args.name in ignoredbs: print( colored( "The database {} is protected and cannot be dropped.". format(args.name), "yellow")) sys.exit(0) try: sp.dropdb(args.name) print( colored( "The database {} has been dropped.".format(args.name), "green")) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'listdbs': try: dbslist = sp.dbslist() dbconn = getdbconn() curr = dbconn.cursor() dbs = [] i = 0 for db in dbslist: i += 1 try: curr.execute( "SELECT table_schema FROM information_schema.tables WHERE table_schema = '{}'" .format(str(db).strip())) tablescount = curr.rowcount curr.execute( "SELECT SUM(data_length + index_length) / 1024 / 1024 AS 'size' FROM information_schema.tables WHERE table_schema = '{}'" .format(str(db).strip())) sizeres = curr.fetchone() dbsize = float(sizeres[0]) except: tablescount = 0 dbsize = 0 if db in ignoredbs: dbtype = 'System' else: dbtype = 'General' info = sp.getmeta('dbmetainfo-{}'.format(db)) if info: dbuser = info.get('user') else: if db in ignoredbs: dbuser = '******' else: dbuser = '******' dbs.append([ i, db, dbuser, tablescount, dbtype, '{} MB'.format(str(round(dbsize, 2))) ]) dbconn.close() print( colored( tabulate(dbs, headers=[ '#', 'DB Name', 'User', 'Tables', 'Type', 'Size' ]), 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'listdbusers': try: dbusers = sp.dbuserslist() i = 0 users = [] for user in dbusers: i += 1 if user in ignoresqlusers: usrtype = 'System User' else: usrtype = 'General User' users.append([i, user, usrtype]) print( colored(tabulate(users, headers=['#', 'User Name', 'Type']), 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'dropalldbs': if doconfirm( 'Do you really want to permanently drop all databases on this server?' ): try: dbs = sp.dbslist() for dbname in dbs: try: if dbname in ignoredbs: print( colored( "The database {} is protected and skipped." .format(dbname), "yellow")) else: sp.dropdb(dbname) print( colored( "The database {} has been dropped.".format( dbname), "green")) except: print( colored( '{} cannot be dropped for some unknown reason.' .format(dbname), 'yellow')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'dropallsqlusers': if doconfirm( 'Do you really want to permanently drop all MySQL users on this server?' ): try: dbusers = sp.dbuserslist() for username in dbusers: try: if username in ignoresqlusers: print( colored( "The user {} is protected and skipped.". format(username), "yellow")) else: try: sp.dropsqluser(username) print( colored( "The database user {} has been dropped." .format(username), "green")) except Exception as e: print(colored(str(e), 'yellow')) except: print( colored( '{} cannot be dropped for some unknown reason.' .format(username), 'yellow')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'createsysuser': if validators.slug(args.username) is not True: print( colored('SSH username contains invalid characters.', 'yellow')) sys.exit(0) if userexists(args.username): print( colored('An SSH user with this username already exists.', 'yellow')) sys.exit(0) try: sp.username = args.username sp.createuser() print( colored('SSH user {} has been successfully created.'.format( args.username))) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'getcert': if doconfirm( 'Do you really want to obtain an SSL certificate for the app {}?' .format(args.app)): sp.setapp(args.app) try: print( colored('Activating SSL for app {}...'.format(args.app), 'blue')) sp.getcert() except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'getcerts': if args.user: sp.setuser(args.user) confirmmsg = 'Do you really want to activate SSL for all apps owned by {}?'.format( args.user) else: confirmmsg = 'Do you really want to activate SSL for all apps existing on this server?' if doconfirm(confirmmsg): try: apps = sp.findapps() if len(apps) > 0: for app in apps: print( colored( 'Activating SSL for app {}...'.format(app[1]), 'blue')) sp.app = app[1] sp.getcert() else: raise Exception('No apps found!') except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'removecert': if doconfirm( 'Do you really want to uninstall SSL certificate for the app {}?' .format(args.app)): sp.setapp(args.app) try: print( colored('Uninstalling SSL from app {}...'.format(args.app), 'blue')) sp.removecert() print( colored( 'SSL has been uninstalled from the app {}.'.format( args.app), 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'removecerts': if args.user: sp.setuser(args.user) confirmmsg = 'Do you really want to uninstall SSL for all apps owned by {}?'.format( args.user) else: confirmmsg = 'Do you really want to uninstall SSL for all apps existing on this server?' if doconfirm(confirmmsg): try: apps = sp.findapps() if len(apps) > 0: for app in apps: print( colored( 'Removing SSL certificate from app {}...'. format(app[1]), 'blue')) sp.app = app[1] sp.removecert() print( colored( 'SSL has been uninstalled from app {}.'.format( app[1]), 'green')) else: raise Exception('No apps found!') except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'forcessl': if doconfirm( 'Do you really want to force HTTPs for the app {}?'.format( args.app)): sp.setapp(args.app) try: sp.forcessl() print( colored( 'HTTPs has been forced for the app {}.'.format( args.app), 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'forceall': if args.user: sp.setuser(args.user) confirmmsg = 'Do you really want to force SSL for all apps owned by {}?'.format( args.user) else: confirmmsg = 'Do you really want to force SSL for all apps existing on this server?' if doconfirm(confirmmsg): try: apps = sp.findapps() if len(apps) > 0: for app in apps: print( colored( 'Forcing SSL certificate for app {}...'.format( app[1]), 'blue')) try: sp.app = app[1] sp.forcessl() print( colored( 'SSL has been forced for app {}.'.format( app[1]), 'green')) except Exception as e: print(colored(str(e), 'yellow')) else: raise Exception('No apps found!') except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'unforcessl': if doconfirm( 'Do you really want to unforce HTTPs for the app {}?'.format( args.app)): try: sp.setapp(args.app) sp.unforcessl() print( colored( 'HTTPs has been unforced for the app {}.'.format( args.app), 'green')) except Exception as e: print(colored(str(e), 'yellow')) if args.action == 'unforceall': if args.user: sp.setuser(args.user) confirmmsg = 'Do you really want to unforce SSL for all apps owned by {}?'.format( args.user) else: confirmmsg = 'Do you really want to unforce SSL for all apps existing on this server?' if doconfirm(confirmmsg): try: apps = sp.findapps() if len(apps) > 0: for app in apps: print( colored( 'Unforcing SSL certificate for app {}...'. format(app[1]), 'blue')) try: sp.app = app[1] sp.unforcessl() print( colored( 'SSL has been unforced for app {}.'.format( app[1]), 'green')) except Exception as e: print(colored(str(e), 'yellow')) else: raise Exception('No apps found!') except Exception as e: print(colored(str(e), 'yellow'))
def arg_validator(arg, vlist=None): """ 检查数据,可对同一个数据进行多种检查 arg : 字符串,要验证的参数 vlist : 列表,验证列表,每个元素包含两项. 第一个项是检查类型(字符串),第二项是可选参数字典,类似: [ ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}), ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}), ... ] 返回: 双元组,第一项为True 或 False,第二项为验证失败的类型(第一项为True的话第二项就留空) 注意: vlist 列表的第一项可以是字符串 "required",用于表示是必填项: 如果第一项不是,而且要验证的 arg 为空,会直接返回 True,不是的继续验证。 如果第一项是,就完全按照 vlist[1:] 的要求验证 vlist 的元素如果是验证整数/小数/email等不需要附加参数的可以直接传入验证类型字符串即可 用例(使用args_validator函数的,看这里vdict每个键值对的形式): vdict = { "token": ["required", "uuid"], "username": ["required", ("length", {"min": 4, "max": 30}), "safe_str"], "password": ["required", ("length", {"min": 4, "max": 20}), "safe_str"], "captcha": ["required", ("length", {"min": 4, "max": 8}), "safe_str"], } form = args_validator(self.request.arguments, vdict) """ if not any((isinstance(vlist, list), isinstance(vlist, tuple))): einfo = "不支持的数据类型!应使用列表或元组,但输入的是{}".format(type(vlist)) raise ValueError(einfo) if vlist[0] == "required": # 第一项不是 required 的,把第一项的 "required" 去掉 vlist = vlist[1:] else: # 第一项不是 required 的,如果 arg 是空的,直接返回 True,不是的继续验证 if not arg: return True, None # 待返回的验证结果 verification = None failed_type = None # 验证失败的类型 # 开始检查,有一个不通过就返回 False for i in vlist: local_verification = None if isinstance(i, str): # 如果是字符串的话就改为元组 i = (i, {}) if len(i) == 1: # 只有一个元素的,添加一个空字典 i = (i[0], {}) vtype = i[0] # 检查类型是第一项 vdict = i[1] # 检查类型所需的可选参数字典 # 在 validators 之外添加的 # 没有空白 if vtype == "no_space": if not re.search(r"\s", arg): local_verification = True # 安全字符串,只包含 0-9a-zA-Z-空格和下划线 elif vtype == "safe_str": if re.match(r"^[0-9a-zA-Z-_ ]+$", arg, flags=re.U): local_verification = True # 是否包含 elif vtype == "in": # 迭代 vdict 的键值(所以键名无所谓) for v in vdict.values(): if arg not in v: local_verification = False break elif vtype == "not_in": # 迭代 vdict 的键值(所以键名无所谓) for v in vdict.values(): if arg in v: local_verification = False break # 字符串形式的数字 elif vtype == "str_number": if re.match(r"[+-]?\d+$", arg, flags=re.U) or \ re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U): local_verification = True elif vtype == "str_int": if re.match(r"[+-]?\d+$", arg, flags=re.U): local_verification = True elif vtype == "str_float": if re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U): local_verification = True # 数字 elif vtype == "number": # 整数或浮点数都可以 local_verification = isinstance(arg, int) or isinstance(arg, float) elif vtype == "int": local_verification = isinstance(arg, int) elif vtype == "float": local_verification = isinstance(arg, float) # 直接调用 validators的 elif vtype == "length": local_verification = validators.length(arg, **vdict) elif vtype == "url": local_verification = validators.url(arg, **vdict) elif vtype == "email": local_verification = validators.email(arg, **vdict) elif vtype == "ip": # ipv4 或 ipv6都可以 local_verification = any((validators.ipv4(arg, **vdict), validators.ipv6(arg, **vdict))) elif vtype == "between": local_verification = validators.between(arg, **vdict) elif vtype == "uuid": local_verification = validators.uuid(arg, **vdict) elif vtype == "ipv4": local_verification = validators.ipv4(arg, **vdict) elif vtype == "ipv6": local_verification = validators.ipv6(arg, **vdict) elif vtype == "mac_address": local_verification = validators.mac_address(arg, **vdict) elif vtype == "iban": local_verification = validators.iban(arg, **vdict) elif vtype == "slug": local_verification = validators.slug(arg, **vdict) elif vtype == "truthy": local_verification = validators.truthy(arg, **vdict) # 对于验证不为真或没有验证的 # 不为真的时候返回的是: ValidationFailure(......) if not local_verification: verification = False failed_type = vtype break # 有一条不为 True, 直接返回 False else: verification = True # 处理返回值 if verification not in(False, True): verification = False if not verification: return verification, failed_type else: return True, None
def v_slug(self, key): return validators.slug(self.__dict__[key])
def test_returns_failed_validation_on_invalid_slug(value): assert isinstance(slug(value), ValidationFailure)
def test_returns_true_on_valid_slug(value): assert slug(value)