Ejemplo n.º 1
0
def update_user(id):
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    try:
        data = request.get_json()
        # Checking required fields
        required = ['first_name', 'last_name', 'username', 'password']
        if not all(field in data for field in required):
            return 'Missing values', 400

        usernameValid = UsernameValidation(data['username'])
        passwordValid = PasswordValidation(data['password'])
        passwordValid.check_all()
        usernameValid.check_all()
        notice = {}
        if any(usernameValid.error_msg.values()) or any(
                usernameValid.error_msg.values()):
            notice['status'] = 'Fail'
            notice['username'] = usernameValid.error_msg
            notice['password'] = passwordValid.error_msg
            return make_response(jsonify(notice)), 401

        if resp['is_admin']:
            old_data = User.query.filter_by(id=id, is_active=True).first()
        else:
            old_data = User.query.filter_by(id=resp['id'],
                                            is_active=True).first()

        # if data exists:
        if old_data:
            # default note = ""
            if 'note' not in data:
                data['note'] = "Information updated by userid " + str(
                    resp['id'])

            old_data.first_name = data['first_name']
            old_data.last_name = data['last_name']
            old_data.username = data['username']
            old_data.password = User.hash_pwd(data['password'])
            old_data.note = data['note']
            old_data.updated_on = datetime.utcnow()

            db.session.commit()

            return user_schema.jsonify(old_data)
        return 'return Data doesn\'s not exists'
    except Exception as e:
        print(e)
        return 'error'
Ejemplo n.º 2
0
def add_password():
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    data = request.get_json()

    try:
        if PMS.find_by_id(data['pms_id']):
            if not Password.is_hibp(password=data['password']):
                passwordValid = PasswordValidation(data['password'])
                passwordValid.check_all()

                if any(passwordValid.error_msg.values()):
                    return make_response(jsonify(passwordValid.error_msg)), 406

                new_pwd = Password(user_id=resp['id'],
                                   pms_id=data['pms_id'],
                                   password=data['password'])
                new_pwd.save()
                return pwd_schema.jsonify(new_pwd), 201
            else:
                return make_response(
                    jsonify("Password is not secure, by HIBP database")), 406
        else:
            responseObject = {
                'status': 'Fail',
                'message': 'PMS don\'t exists.',
            }
            return make_response(jsonify(responseObject)), 200
    except Exception as e:
        print(e)
        return 'Server error'
Ejemplo n.º 3
0
def delete_product(id):
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    try:
        if resp['is_admin']:
            # admin can delete any user
            deleted_data = User.query.filter_by(id=id, is_active=True).first()
        else:
            deleted_data = User.query.filter_by(id=resp['id'],
                                                is_active=True).first()

        # if data exist
        if deleted_data:
            deleted_data.note = "PMS deactivated by {} and current status {}".format(
                resp['id'], resp['is_admin'])
            deleted_data.updated_on = datetime.utcnow()
            deleted_data.is_active = False

            db.session.commit()

            return user_schema.jsonify(deleted_data)
        return 'Data doesn\'s not exists'

    except Exception as e:
        print(e)
        return 'Server error'
Ejemplo n.º 4
0
def update_pms(id):
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    try:
        data = request.get_json()

        # admin can all the data
        if resp['is_admin']:
            old_data = PMS.query.filter_by(id=id, is_active=True).first()

        else:
            old_data = PMS.query.filter_by(id=id, user_id=resp['id'], is_active=True).first()    
        
        if old_data:            
            if 'note' not in data:
                data['note'] = "Information updated by userid "+str(resp['id'])

            old_data.site_url = data['url']        
            old_data.username = data['username']
            old_data.password = data['password']
            old_data.note = data['note']        
            old_data.updated_on = datetime.utcnow()
            
            db.session.commit()

            return pms_schema.jsonify(old_data)
        return 'Data doesn\'s not exists'
    except Exception as e:
        print(e)
        return 'Server error'
Ejemplo n.º 5
0
def get_all_pms():
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    if resp['is_admin']:            
        try:                    
            pms = PMS.query.filter_by(is_active=True).all()            
            responseObject = {
                'status': 'success',
                'data': pmss_schema.dump(pms)
            }
            return make_response(jsonify(responseObject)), 200    
        except Exception as e:
            print(e)
            return 'Server errores'           
    else: 
        try:               
            pms = PMS.query.filter_by(user_id=resp['id'], is_active=True).all()
            print(pms)
            responseObject = {
                'status': 'success',
                'message': pmss_schema.dump(pms)
            }
            return make_response(jsonify(responseObject)), 202  
        except Exception as e:
            print(e)
            return 'Server error'      
Ejemplo n.º 6
0
def refresh():
    # Extend the time us jwt in user_routes: get_user/s, update
    # It takes time so
    # Work on PMS part > Login > CRUD credientials

    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)

    responseObject = {'status': 'success', 'message': resp}
    return make_response(jsonify(responseObject)), 200
Ejemplo n.º 7
0
def get_user(id):
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    if resp['is_admin']:
        try:
            user = User.query.filter_by(id=id, is_active=True).first()
            return user_schema.jsonify(user)
        except Exception as e:
            print(e)
            return 'Server error'
    else:
        return 'No access right'
Ejemplo n.º 8
0
def login():
    credientials = request.get_json()
    username = credientials['username']
    password = credientials['password']

    try:
        user = User.authenticate(username, password)
        # check if the user actually exists
        if not user:
            responseObject = {
                'status': 'authentication failed',
                'message': 'username or password don\'t match.',
            }
            return make_response(jsonify(responseObject)), 200
        auth_token = user.encode_auth_token(user.id, user.is_admin)
        print(password)
        if auth_token:
            # check if any credition config has been changes respect to update_on
            usernameValid = UsernameValidation(username)
            passwordValid = PasswordValidation(password)
            passwordValid.check_all()
            usernameValid.check_all()

            if not dog_watch() or (user.updated_on >
                                   usernameValid.last_update()):
                notice = {}
                if any(usernameValid.error_msg.values()):
                    notice['username'] = usernameValid.error_msg
                if any(passwordValid.error_msg.values()):
                    notice['password'] = passwordValid.error_msg

                responseObject = {
                    'status': 'success',
                    'message': 'Successfully logged in. but',
                    'auth_token': auth_token.decode(),
                    'config_file_modified': dog_watch(),
                    'update_info': notice
                }

                return make_response(jsonify(responseObject)), 200

            responseObject = {
                'status': 'success',
                'message': 'Successfully logged in.',
                'auth_token': auth_token.decode()
            }
            return make_response(jsonify(responseObject)), 200
    except Exception as e:
        print(e)
        responseObject = {'status': 'fail', 'message': 'Try again'}
        return make_response(jsonify(responseObject)), 500
Ejemplo n.º 9
0
def add_credential():
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    data = request.get_json()        
    now = datetime.utcnow()
    if 'note' not in data:
        data['note'] = "By user "+str(resp['id'])
    try:
        new_pms = PMS(user_id=resp['id'], site_url=data['url'], username=data['username'], password=data['password'],
                        created_on=now, updated_on=now, note=data['note']
                    )
        new_pms.save()    
        return pms_schema.jsonify(new_pms)
    except Exception as e:
        print(e)
        return 'Server error'
Ejemplo n.º 10
0
def get_pms_by_id(id):
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    if resp['is_admin']:
        try:            
            pms = PMS.query.filter_by(id=id, is_active=True).first()    
            return pms_schema.jsonify(pms)
        except Exception as e:
            print(e)
            return 'Server error'
    else:
        try:            
            pms = PMS.query.filter_by(id=id, user_id=resp['id'], is_active=True).first()    
            return pms_schema.jsonify(pms)
        except Exception as e:
            print(e)
            return 'Server error'        
Ejemplo n.º 11
0
def check():
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    try:
        if isinstance(resp['id'], int):
            user = User.query.filter_by(id=resp['id'], is_active=True).first()
            responseObject = {
                'status': 'success',
                'id': user.id,
                'first_name': user.first_name,
                'username': user.username
            }
            return make_response(jsonify(responseObject)), 200
        responseObject = {'status': 'fail', 'message': resp}
        return make_response(jsonify(responseObject)), 401
    except Exception as e:
        responseObject = {'status': 'fail', 'message': resp}
        return make_response(jsonify(responseObject)), 401
Ejemplo n.º 12
0
def get_users():
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    try:
        if resp['is_admin']:
            users = User.query.filter_by(is_active=True).all()
            responseObject = {
                'status': 'success',
                'data': users_schema.dump(users)
            }
        else:
            user = User.query.filter_by(id=resp['id'], is_active=True).first()
            responseObject = {
                'status': 'success',
                'message': user_schema.dump(user)
            }
        return make_response(jsonify(responseObject)), 200
    except Exception as e:
        return 'Server errores'
Ejemplo n.º 13
0
def logout():
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    print(type(resp['id']))
    if isinstance(resp['id'], int):
        # mark the token as blacklisted
        try:
            blacklist_token = BlacklistToken(token=auth_token)
            # insert the token
            db.session.add(blacklist_token)
            db.session.commit()
            responseObject = {
                'status': 'success',
                'message': 'Successfully logged out.'
            }
            return make_response(jsonify(responseObject)), 200
        except Exception as e:
            responseObject = {'status': 'fail', 'message': e}
            return make_response(jsonify(responseObject)), 200
    else:
        responseObject = {'status': 'fail', 'message': resp}
        return make_response(jsonify(responseObject)), 401
Ejemplo n.º 14
0
def update_password():
    auth_token = request.headers.get('Authorization')
    resp = User.decode_auth_token(auth_token)
    data = request.get_json()

    try:
        if PMS.find_by_id(data['pms_id']):
            if not Password.is_hibp(password=data['password']):
                passwordValid = PasswordValidation(data['password'])
                passwordValid.check_all()

                if any(passwordValid.error_msg.values()):
                    return make_response(jsonify(passwordValid.error_msg)), 406

                old_data = Password.query.filter_by(id=data['id'],
                                                    user_id=resp['id'],
                                                    pms_id=data['pms_id'],
                                                    is_active=True).first()
                old_data.password = Password.encrypt_message(data['password'])
                old_data.note = ""  #f"Updated by user id: {resp['id']}"

                db.session.commit()

                return pwd_schema.jsonify(old_data)
            else:
                return make_response(
                    jsonify("Password is not secure, by HIBP database")), 406
        else:
            responseObject = {
                'status': 'Fail',
                'message': 'PMS don\'t exists.',
            }
            return make_response(jsonify(responseObject)), 200
    except Exception as e:
        print(e)
        return 'Server error'
Ejemplo n.º 15
0
def add_user():
    data = request.get_json()
    user = User.find_by_username(data['username'])
    # check if username exists then return to login url
    if not user:

        # Checking required fields
        required = ['first_name', 'last_name', 'username', 'password']
        if not all(field in data for field in required):
            return 'Missing values', 400

        # validation based on constrain file
        usernameValid = UsernameValidation(data['username'])
        passwordValid = PasswordValidation(data['password'])
        passwordValid.check_all()
        usernameValid.check_all()
        notice = {}
        if any(usernameValid.error_msg.values()) or any(
                usernameValid.error_msg.values()):
            notice['status'] = 'Fail'
            notice['username'] = usernameValid.error_msg
            notice['password'] = passwordValid.error_msg
            return make_response(jsonify(notice)), 401

        # default note = ""
        if 'note' not in data:
            data['note'] = ""

        now = datetime.utcnow()

        new_user = User(first_name=data['first_name'],
                        last_name=data['last_name'],
                        username=data['username'],
                        password=data['password'].encode('utf-8'),
                        note=data['note'],
                        created_on=now,
                        updated_on=now)

        try:
            new_user.save()
            # generate auth token
            # generate the auth token
            auth_token = new_user.encode_auth_token(new_user.id,
                                                    new_user.is_admin)
            print(type(auth_token))
            responseObject = {
                'status': 'success',
                'message': 'Successfully registered.',
                'auth_token': auth_token.decode()
            }
            return make_response(jsonify(responseObject)), 201
            # return user_schema.jsonify(new_user)
        except Exception as e:
            print(e)
            responseObject = {
                'status': 'fail',
                'message': 'Some error occurred. Please try again.'
            }
            return make_response(jsonify(responseObject)), 401
    else:
        responseObject = {
            'status': 'fail',
            'message': 'User already exists. Please Log in.',
        }
        return make_response(jsonify(responseObject)), 202