Example #1
0
    def change_local_system_ip(self, username: str, old_local_ip: str, new_local_ip: str) -> dict:
        if not self.username_exists(username):
            return {'success': False, 'error': "You are not logged in to access this resource."}
        if not APIUtils.validate('ipaddress', old_local_ip):
            return {'success': False, 'error': "Please provide a valid old Local IP Address."}
        if not APIUtils.validate('ipaddress', new_local_ip):
            return {'success': False, 'error': "Please provide a valid new Local IP Address."}

        # "Warning"? Issue in pylint: https://github.com/MongoEngine/mongoengine/issues/858
        user = User.objects(username=username)[0]
        oldlocalexists = LocalSystem.objects(
            userId=user, localIP=old_local_ip).count() > 0
        newlocalexists = LocalSystem.objects(
            userId=user, localIP=new_local_ip).count() > 0
        if not oldlocalexists:
            return {
                'success': False,
                'error': "A system with this IP does not exists in your IP Pool."
                }
        if newlocalexists:
            return {
                'success': False,
                'error': "A system with this IP is already exists in your IP Pool."
                }
        localsys: LocalSystem = LocalSystem.objects(
            userId=user, localIP=old_local_ip)[0]
        localsys.localIP = new_local_ip
        localsys.save()
        return {'success': True, 'message': "Local System's IP changed successfully!"}
    def remove_local_system(self, username: str, local_ip: str) -> dict:
        if not self.username_exists(username):
            return {
                'success': False,
                'error': "You are not logged in to access this resource."
            }
        if not APIUtils.validate('ipaddress', local_ip):
            return {
                'success': False,
                'error': "Please provide a valid IP Address."
            }

        # "Warning"? Issue in pylint: https://github.com/MongoEngine/mongoengine/issues/858
        user = User.objects(username=username)[0]
        localexists = LocalSystem.objects(userId=user,
                                          localIP=local_ip).count() > 0
        if not localexists:
            return {
                'success': False,
                'error':
                "A system with this IP does not exists in your IP Pool."
            }
        localsys: LocalSystem = LocalSystem.objects(userId=user,
                                                    localIP=local_ip)
        localsys.delete()
        return {
            'success': True,
            'message': "Local System deleted successfully!"
        }
    def add_local_system(self, username: str, local_ip: str) -> dict:
        if not self.username_exists(username):
            return {
                'success': False,
                'error': "You are not logged in to access this resource."
            }
        if not APIUtils.validate('ipaddress', local_ip):
            return {
                'success': False,
                'error': "Please provide a valid IP Address."
            }

        # "Warning"? Issue in pylint: https://github.com/MongoEngine/mongoengine/issues/858
        user = User.objects(username=username)[0]
        localexists = LocalSystem.objects(userId=user,
                                          localIP=local_ip).count() > 0
        if localexists:
            return {
                'success': False,
                'error':
                "A system with this IP is already added to your IP Pool."
            }
        localsys = LocalSystem()
        localsys.userId = user
        localsys.localIP = local_ip
        localsys.os = "Unknown"
        localsys.openPorts = {}
        localsys.systemUp = False
        localsys.save()

        return {'success': True, 'message': "Local System added successfully!"}
Example #4
0
    def login(self, username: str, password: str) -> dict:
        errors = {}
        if username == "":
            errors['username'] = "******"
        if password == "":
            errors['password'] = "******"
        if errors != {}:
            return {'success': False, 'errors': errors}
        elif not self.username_exists(username):
            errors['username'] = "******"
            return {'success': False, 'errors': errors}
        else:
            # "Warning"? Issue in pylint: https://github.com/MongoEngine/mongoengine/issues/858
            users = User.objects(
                username=username)
            
            if users.count() == 1 and APIUtils.decrypt_password(users[0].password) == password:

                # Generate JWT Token
                jwt_iat = int(time.time())
                jwt_exp = int(jwt_iat + (60*60*14))  # Expires after 24 hrs
                decrypted_token = {
                    'email': users[0].emailAddress,
                    'username': users[0].username,
                    'publicip': users[0].publicIP,
                    'iat': jwt_iat,
                    'exp': jwt_exp
                }
                return {'success': True, 'emailVerified': users[0].emailVerified, 'message': "Login successful!", 'token': APIUtils.encrypt_jwt_token(decrypted_token)}
            else:
                return {'success': False, 'message': "Invalid username or password!"}
Example #5
0
    def register(self, firstname: str, lastname: str, username: str, emailaddress: str, password: str, companyname: str) -> dict:
        errors = {}

        # Validate all arguments

        # First Name
        if firstname == "":
            errors['firstname'] = "First name cannot be empty"
        elif not validate("firstname", firstname):
            errors['firstname'] = "First name contains invalid characters and/or it should be more than 2 and less then 20 characters long."

        # Last Name
        if lastname == "":
            errors['lastname'] = "Last name cannot be empty"
        elif not validate("lastname", lastname):
            errors['lastname'] = "Last name contains invalid characters and/or it should be more than 2 and less then 20 characters long."

        # password
        if password == "":
            errors['password'] = "******"
        elif not validate("password", password):
            errors['password'] = "******"

        # Username
        if username == "":
            errors['username'] = "******"
        elif not validate("username", username):
            errors[
                'username'] = "******"
        elif self.username_exists(username):
            errors['username'] = "******"

        # Email
        if emailaddress == "":
            errors['emailaddress'] = "Email Address cannot be empty."
        elif not validate("email", emailaddress):
            errors['emailaddress'] = "Please provide a valid email address."
        elif self.emailaddress_exists(emailaddress):
            errors['emailaddress'] = "Email Address already registered."

        # Comapny Name
        if companyname == "":
            errors['companyname'] = "Compnay name cannot be empty."
        elif not validate("companyname", companyname):
            errors['companyname'] = "Company name contains invalid characters and/or it should be more than 2 and less then 64 characters long."
        # if there are errors return
        if errors != {}:
            return {'success': False, 'errors': errors}

        # All validation tests passed now create a user in database
        user = User(firstName=firstname, lastName=lastname, companyName=companyname,
                    password=APIUtils.encrypt_password(password), username=username,
                    emailAddress=emailaddress, emailVerified=False
                    )
        user.save()
        # TODO check for error returned by generateRecoveryCode
        self.generateRecoveryCode(user, "verifyEmail")
        # return with successful message
        return {'success': True, 'message': "Your account has successfully been created"}
Example #6
0
 def change_password(self, username: str, new_password: str) -> dict:
     if not self.username_exists(username):
         return {'success': False, 'message': 'Invalid Username!'}
     user: User = User.objects(username=username)[0]
     if not validate("password", new_password):
         return {'success': False, 'error': "Password must contain 8 or more character with at least 1 lowercase, uppercase, numeric and special symbol character each."}
     user.password = APIUtils.encrypt_password(new_password)
     user.save()
     return {'success': True, 'message': 'Password updated successfully!'}
Example #7
0
 def recover_account(self, username: str, recovery_code: int, new_password: str):
     users = User.objects(username=username)
     if users.count() == 0:
         return {"success": False, "error": "Username does not exist."}
     elif validate("password", new_password):
         return {"success": False, "error": "Password does not meet the given criteria"}
     else:
         user: User = users[0]
         if user.codeFor is not None and user.recoveryCode is not None and user.recoveryCode == recovery_code and user.codeFor == "resetPassword":
             user.codeFor = None
             user.recoveryCode = None
             user.password = APIUtils.encrypt_password(new_password)
             user.save()
             return {"success": True, "message": "Password changed Successfully!"}
         return {"success": False, "error": "Invalid Code!"}
Example #8
0
 def change_agent_ip(self, username: str, ipaddr: str) -> dict:
     if not self.username_exists(username):
         return {"success": False, "error": "Username does not exist!"}
     if (ipaddr is not None) and not APIUtils.validate("ipaddress", ipaddr):
         return {"success": False, "error": "IP Address is invalid! Please provide a valid IPv4 Address."}
     # "Warning"? Issue in pylint: https://github.com/MongoEngine/mongoengine/issues/858
     user: User = User.objects(username=username)[0]
     user.publicIP = ipaddr
     ipverify = str(uuid4())
     user.publicIPVerifier = ipverify
     user.verifiedPublicIP = True
     user.save()
     return {
         "success": True,
         "message": "Please verify IP Ownership by creating a file named the given code in root of web server of that IP Address.",
         "code": ipverify}
 def get_password(self, username: str) -> str:
     user: User = User.objects(username=username)[0]
     return APIUtils.decrypt_password(user.password)
Example #10
0
from api_utils import APIUtils

#Setup Logging
logger_name = 'media-server-api'
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d %(name)-12s %(levelname)-8s %(message)s',
    datefmt='%d-%m %H:%M',
    filename='./{}.log'.format(logger_name),
    filemode='w')

logger = logging.getLogger(logger_name)

#Initialize objects
app = Flask(__name__)
utils = APIUtils(logger=logger_name)

#Loading config
dir_path = os.path.dirname(os.path.realpath(__file__))
config = utils.loadConfig(dir_path + '/cfg/config.yml')
system = SystemControls(logger=logger_name, services=config['services'])

#Setup auth
app.config['BASIC_AUTH_USERNAME'] = config['auth']['user']
app.config['BASIC_AUTH_PASSWORD'] = config['auth']['pass']
app.config['BASIC_AUTH_FORCE'] = True
#auth = BasicAuth(app)


#API routes
@app.route('/')