Ejemplo n.º 1
0
def import_factories(file):
    from app import app
    full_path = 'app/utils/uploadedfiles/' + file
    dataFrame = pd.read_excel(full_path)
    length = len(dataFrame)
    with app.app_context():
        for i in range(length):
            row = dataFrame.iloc[i]
            if pd.isna(row['ID']):
                username = str(row['username'])
                email = str(row['email'])
                role = 2
                password = User.generate_pass()
                delegate_phone = str(row['user phone'])
                user = User(username=username, email=email, role=role, password=password, phone=delegate_phone,
                            account_status=1)
                db.session.add(user)
                db.session.commit()
                factory_name = str(row['Name'])
                address = str(row['Address'])
                factory_hotline = str(row['Hot line'])
                fac = Factory(name=factory_name, delegate=user.id, address=address, hotline=factory_hotline)
                db.session.add(fac)
                db.session.commit()
                pass_mail(password, email, username)
    return 200
Ejemplo n.º 2
0
    def post(self):
        data = request.form
        factory_name = data["factory_name"]
        username = data["logistic_name"]
        address = data["address"]
        email = data["email"]
        factory_hotline = data["factory_hotline"]
        delegate_phone = data["delegate_phone"]
        password = User.generate_pass()
        role = 2
        img = request.files['factory_logo']
        user = User.query.filter_by(email=email).first()
        if user:
            return redirect(
                url_for('base_blueprint.SignupFactory', error="FAILED: user with entered E-mail already exist!"))

        user = User.query.filter_by(username=username).first()
        if user:
            return redirect(url_for('base_blueprint.SignupFactory', error="user with entered name already exist!"))

        user = User.query.filter_by(phone=delegate_phone).first()
        if user:
            return redirect(url_for('base_blueprint.SignupFactory', error="user with entered phone already exist!"))

        user = User(username=username, email=email, role=role, password=password, phone=delegate_phone, )
        db.session.add(user)

        fac = Factory.query.filter_by(name=factory_name).first()
        if fac:
            return redirect(url_for('base_blueprint.SignupFactory', error="factory with entered name already exist!"))

        fac = Factory.query.filter_by(address=address).first()
        if fac:
            return redirect(
                url_for('base_blueprint.SignupFactory', error="factory with entered address already exist!"))

        fac = Factory.query.filter_by(hotline=factory_hotline).first()
        if fac:
            return redirect(
                url_for('base_blueprint.SignupFactory', error="factory with entered hot line already exist!"))
        _, file_extension = os.path.splitext(img.filename)
        url = upload_file_to_s3(img, file_name=factory_name + file_extension, folder='factory_logo')
        fac = Factory(name=factory_name, delegate=user.id, address=address, hotline=factory_hotline, logo=url)
        db.session.add(fac)
        db.session.commit()
        admin_users = User.query.filter_by(role=3).all()
        for admin in admin_users:
            if admin.device_token:
                device_token = admin.device_token
                message_title = "New Factory"
                message_body = "There are new Factory!"
                click_action = "/AdminDashboard/factory"
                result = notf_service.notify_single_device(registration_id=device_token, message_title=message_title,
                                                           click_action=click_action, message_body=message_body)
        return redirect(url_for('base_blueprint.login',
                                message="Successfully Signed up, waiting for Admin approve then you will "
                                        "receive Accepted E-mail from us"))
Ejemplo n.º 3
0
def import_cars(file, company_id):
    from app import app
    with app.app_context():
        full_path = 'app/utils/uploadedfiles/' + file
        dataFrame = pd.read_excel(full_path)
        length = len(dataFrame)
        role = 4
        with app.app_context():
            for i in range(length):
                row = dataFrame.iloc[i]
                if pd.isna(row['car_id']):
                    car_plate_number = str(row["car_plate_number"])
                    car_type = str(row["car_type"])
                    if car_type == "trilla" or car_type == 'تريلا' or car_type == 'تريله' or car_type == "تريلة":
                        car_type = 0
                    else:
                        car_type = 1
                    car_capacity = float(row["car_capacity"])
                    car_color = str(row["car_color"])
                    qr_code = Car.generate_qrcode()
                    car_user = User(username=car_plate_number, email=car_plate_number, password=qr_code,
                                    phone=car_plate_number, role=role,account_status=1)
                    db.session.add(car_user)
                    db.session.commit()
                    new_car = Car(user_id=car_user.id, number=car_plate_number, owner=company_id, qr_code=qr_code,
                                  _type=car_type, capacity=car_capacity, color=car_color)
                    db.session.add(new_car)
                    db.session.commit()
        return 'done'
Ejemplo n.º 4
0
 def post(self):
     car_user = None
     try:
         role = 4
         data = request.form
         plate_number = data['plate_number']
         car = Car.query.filter_by(number=plate_number).first()
         if car:
             return redirect(
                 url_for(
                     'cars_blueprint_company.route_error',
                     error="Car with entered plate number is already exist")
             )
         car_type = int(data['car_type'])
         if car_type == 1:
             maktura_plate_number = data["maktura_plate_number"]
         else:
             maktura_plate_number = plate_number
         car_capacity = data['car_capacity']
         car_color = data['car_color']
         doc_img = request.files['doc_image']
         qr_code = Car.generate_qrcode()
         owner = Company.query.filter_by(_user_id=current_user.id).first()
         car_user = User(username=plate_number,
                         email=plate_number,
                         password=qr_code,
                         phone=qr_code[0:11],
                         role=role,
                         account_status=1)
         db.session.add(car_user)
         db.session.commit()
         _, file_extension = os.path.splitext(doc_img.filename)
         url = upload_file_to_s3(doc_img,
                                 file_name=plate_number + file_extension,
                                 folder='cars_doc')
         new_car = Car(user_id=car_user.id,
                       number=plate_number,
                       owner=owner.id,
                       qr_code=qr_code,
                       _type=car_type,
                       capacity=car_capacity,
                       color=car_color,
                       doc_img=url,
                       maktura_plate_number=maktura_plate_number)
         db.session.add(new_car)
         db.session.commit()
         print(new_car.serialize())
         return redirect(url_for('cars_blueprint_company.company_cars'))
     except Exception as e:
         print("Exception in NewCar: ", e)
         if car_user:
             db.session.delete(car_user)
             db.session.commit()
         return redirect(
             url_for(
                 'cars_blueprint_company.route_error',
                 error="Some thing Wrong happened, please try again later"))
Ejemplo n.º 5
0
def login_user(json_data):
    """Method checks if the user data provided is valid for login

    Args:
        data (json): User email and password
    """
    try:
        data = auth_schema.load(json_data)
    except ValidationError as e:
        return jsonify({"status": 400, "error": e.messages}), 400
    email = data["email"]

    # Query database for if provided user with email exists
    user_by_email = User.get_user_by_email(email)
    user_email = db().get_single_row(*user_by_email)
    if user_email:
        # check if password provided matches
        password_candidate = data['password']
        user_password = user_email['password']
        if User.verify_hash_password(password_candidate, user_password):
            # get the user id to use for token generation
            identifier = user_email['id']
            access_token = User.encode_auth_token(identifier)
            response = user_schema.dump(user_email)
            return jsonify({
                "status":
                200,
                "message":
                "Successfully logged in.",
                "data": [{
                    "token": access_token.decode(),
                    "user": [response]
                }]
            }), 200
        # response for password and email missmatch
        return jsonify({
            "status": 400,
            "error": "Incorrect user email or password."
        }), 400

    # when no user with particular email exists
    return jsonify({"status": 404, "message": "User does not exists."}), 404
Ejemplo n.º 6
0
 def setUp(self):
     """
     Creeate the user instance.
     """
     self.new_user = User(firstname="peter",
                          lastname="simon",
                          othername="john",
                          email="*****@*****.**",
                          phonenumber="7859393982",
                          password="******",
                          passportUrl="https://api.passposts.com/")
Ejemplo n.º 7
0
def import_companies(file):
    from app import app
    full_path = 'app/utils/uploadedfiles/' + file
    dataFrame = pd.read_excel(full_path)
    length = len(dataFrame)
    with app.app_context():
        for i in range(length):
            row = dataFrame.iloc[i]
            if pd.isna(row['ID']):
                username = str(row['username'])
                email = str(row['email'])
                role = 1
                password = User.generate_pass()
                phone = str(row['Phone'])
                user = User(username=username, email=email, role=role, password=password, phone=phone, account_status=1)
                db.session.add(user)
                db.session.commit()
                company_name = str(row['Name'])
                address = str(row['Address'])
                com = Company(name=company_name, account=user.id, address=address)
                db.session.add(com)
                db.session.commit()
                pass_mail(password, email, username)
    return 200
Ejemplo n.º 8
0
def verify_auth_decode(token):
    """ verify if auth decoding is successful

    return:
       True, False (boolean): True when decoding is successful, false otherwise
       response (str/int): int when decoding is successful, str otherwise

    Expected response value:
    Expired token (str) : "Signature expired. PLease login again."
    Invalid token (str) : "Invalid token. PLease login again."
    Blacklisted token (str): "Token is blacklisted. Login again."
    id (int) : when the decoding exited successfully without error
    """
    resp = User.decode_auth_token(token)

    if not isinstance(resp, str):
        return True, resp
    else:
        return False, resp
Ejemplo n.º 9
0
def newUser():
    signup_form = request.form
    username = signup_form['name'] + ' ' + signup_form['name2']
    email = signup_form['email']
    phone = signup_form['number']
    password = signup_form['password']
    user = User.query.filter_by(email=email).first()
    if user:
        return 'user already exist.\nplease back again!'
    registered_on = datetime.datetime.utcnow()
    user = User(email=email,
                password=password,
                username=username,
                registered_on=registered_on,
                phone=phone)
    db.session.add(user)
    db.session.commit()

    return redirect(url_for('forms_blueprint.route_template', template='user'))
Ejemplo n.º 10
0
    def post(self):
        data = request.json
        print(data)
        try:
            company_name = data.get('company_name')
            username = company_name  # data.get('username')
            email = data.get('email')
            # TODO generate password, and send mail
            password = User.generate_pass(
            )  # 'company'  # data.get('password')
            address = data.get('address')
            phone = data.get('phone')
            # img = request.files['company_logo']
            role = 1
            user = User.query.filter_by(email=email).first()
            if user:
                response_obj = {
                    'status': 'failed',
                    'message': 'user with entered E-mail already exist!'
                }
                return response_obj, 409
            user = User.query.filter_by(username=username).first()
            if user:
                response_obj = {
                    'status': 'failed',
                    'message': 'user with entered name already exist!'
                }
                return response_obj, 409
            user = User.query.filter_by(phone=phone).first()
            if user:
                response_obj = {
                    'status': 'failed',
                    'message': 'user with entered phone already exist!'
                }
                return response_obj, 409
            user = User(username=username,
                        email=email,
                        role=role,
                        password=password,
                        phone=phone)
            db.session.add(user)
            com = Company.query.filter_by(name=company_name).first()
            if com:
                response_obj = {
                    'status': 'failed',
                    'message': 'company with entered name already exist!'
                }
                return response_obj, 409
            com = Company.query.filter_by(address=address).first()
            if com:
                response_obj = {
                    'status': 'failed',
                    'message': 'company with entered address already exist!'
                }
                return response_obj, 409

            # _, file_extension = os.path.splitext(img.filename)
            # url = upload_file_to_s3(img, file_name=company_name + file_extension, folder='company_logo')
            # com = Company(name=company_name, account=user.id, address=address, logo=url)
            com = Company(name=company_name, account=user.id, address=address)
            db.session.add(com)
            db.session.commit()
            admin_users = User.query.filter_by(role=3).all()
            for admin in admin_users:
                if admin.device_token:
                    device_token = admin.device_token
                    message_title = "New Company"
                    message_body = "There are new Company!"
                    click_action = "/AdminDashboard/company"
                    result = notf_service.notify_single_device(
                        registration_id=device_token,
                        message_title=message_title,
                        click_action=click_action,
                        message_body=message_body)
            response_obj = {
                'status': 'success',
                'message': 'Successfully Signed up'
            }
            return response_obj, 201
        except Exception as e:
            print('Exception in company sign up:', e)
            response_obj = {
                'status': 'failed',
                'message': 'Something Wrong, please try again later'
            }
            return response_obj, 500
Ejemplo n.º 11
0
def create_user():
    user = User(**request.form)
    db.session.add(user)
    db.session.commit()
    return jsonify('success')
Ejemplo n.º 12
0
def signin_all_users():
    """
    this signs in all users
    """
    try:
        user_data = request.get_json()
        email = user_data["email"]
        password = user_data["password"]

        # check data for sanity incase it bypass js on the frontend
        check_for_whitespace(user_data, ["email", "password"])
        isValidEmail(email)

        user = User.query.filter_by(email=user_data["email"]).first()

        if not user:
            abort(401)

        _user = user_schema.dump(user)
        _password_hash = _user["password"]

        if not User.compare_password(_password_hash, password):
            abort(401)

        _curr_user = user_schema.dump(user)
        if _curr_user["isActive"] != "true":
            abort(403)

        token = jwt.encode(
            {
                "id":
                _curr_user["id"],
                "role":
                _curr_user["role"],
                "exp":
                datetime.datetime.utcnow() + datetime.timedelta(minutes=480),
            },
            KEY,
            algorithm="HS256",
        )
        resp = custom_make_response(
            "data", {
                "message": "Signed in successfully, \
                    preparing your dashboard...",
                "auth_token": token.decode('utf-8'),
                "username": _curr_user["username"],
                "role": _curr_user["role"],
                "companyId": _curr_user["companyId"]
            }, 200)
        return resp

    except Exception as e:
        if (e.code == 401):
            return custom_make_response(
                "error",
                "Incorrect email and or password, check & try again !", 401)
        elif (e.code == 403):
            return custom_make_response(
                "error",
                "Your account is not in active\
                         status, contact company admin.",
                403,
            )
        elif (e.code == 400):
            return custom_make_response(
                "error", "One or more mandatory fields has not been filled.",
                400)
        else:
            return custom_make_response(
                "error", "Bummer an internal server error has occured,\
                    the site admin has been notified, Please give it a \
                        moment and try again.", 500)
Ejemplo n.º 13
0
def signup_system_users():
    """
    signup system users
    """
    try:
        user_data = request.get_json()
        role = user_data["role"]
        if role == "Admin":
            this_company = Company.query.filter_by(
                company=user_data["company"]).first()
            _company = company_schema.dump(this_company)
            companyId = _company["id"]
            password = user_data["password"]
        else:
            companyId = user_data["companyId"]
            password = generate_random_password()
        email = user_data["email"]
        isActive = user_data["isActive"]

        this_employee = (Employees.query.filter_by(
            email=user_data["email"]).filter_by(
                companyId=user_data["companyId"]).first())
        employee = employee_schema.dump(this_employee)
        id = employee["id"]
        username = employee["fullname"].split(" ")[0] + "." + id

        # check data for sanity incase it bypass js on the frontend
        check_for_whitespace(
            user_data,
            ["companyId", "username", "email", "password", "role", "status"])
        isValidEmail(email)
        # check if user is already registered
        if User.query.filter_by(email=user_data["email"]).first():
            abort(409)

        isValidPassword(password)
        new_user = User(
            id=id,
            username=username,
            email=email,
            password=password,
            companyId=companyId,
            role=role,
            isActive=isActive,
        )

        db.session.add(new_user)
        db.session.commit()

        if role != "Admin":
            token = jwt.encode(
                {
                    "id":
                    id,
                    "email":
                    user_data["email"],
                    "exp":
                    datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
                },
                KEY,
                algorithm="HS256",
            )
            subject = """Activate your account."""
            content = f"""
            Hey {username.split('.', 1)[0]},
            {non_admin_user_registration_content()}
            <a href="{password_reset_url}?u={token.decode('utf-8')}"
            style="{button_style()}">Activate account</a>
            {email_signature()}
            """
            send_mail(email, subject, content)

        return custom_make_response(
            "data",
            f"User registered successfully, email sent to {email}\
                for further instructions.",
            201,
        )

    except Exception as e:
        message = str(e)
        if "id" in message:
            return custom_make_response(
                "error",
                "The user you are creating an account for\
                is not on your company masterfile,\
                    Please add them and try again.",
                400,
            )
        elif (e.code == 409):
            return custom_make_response(
                "error",
                "A user account with that email already exists,\
                    please use another one and try again.",
                409,
            )
        else:
            return custom_make_response(
                "error", "Bummer an internal server error occured\
                    site admin has been notified, please give\
                        it a moment and try again.", 500)
Ejemplo n.º 14
0
    def post(self):
        data = request.form
        try:
            img = request.files['factory_logo']
            factory_name = data.get('factory_name')
            username = data.get('username')
            email = data.get('email')
            password = User.generate_pass()  # 'factory'
            address = data.get('address')
            factory_hotline = data.get('factory_hotline')
            delegate_phone = data.get('delegate_phone')
            role = 2
            user = User.query.filter_by(email=email).first()
            # img = request.files['factory_logo']
            if user:
                response_obj = {
                    'status': 'failed',
                    'message': 'user with entered E-mail already exist!'
                }
                return response_obj, 409
            user = User.query.filter_by(username=username).first()
            if user:
                response_obj = {
                    'status': 'failed',
                    'message': 'user with entered name already exist!'
                }
                return response_obj, 409
            user = User.query.filter_by(phone=delegate_phone).first()
            if user:
                response_obj = {
                    'status': 'failed',
                    'message': 'user with entered phone already exist!'
                }
                return response_obj, 409
            user = User(username=username, email=email, role=role, password=password, phone=delegate_phone)
            db.session.add(user)
            fac = Factory.query.filter_by(name=factory_name).first()
            if fac:
                response_obj = {
                    'status': 'failed',
                    'message': 'factory with entered name already exist!'
                }
                return response_obj, 409
            fac = Factory.query.filter_by(address=address).first()
            if fac:
                response_obj = {
                    'status': 'failed',
                    'message': 'factory with entered address already exist!'
                }
                return response_obj, 409
            fac = Factory.query.filter_by(hotline=factory_hotline).first()
            if fac:
                response_obj = {
                    'status': 'failed',
                    'message': 'factory with entered hot line already exist!'
                }
                return response_obj, 409
            _, file_extension = os.path.splitext(img.filename)
            url = upload_file_to_s3(img, file_name=factory_name + file_extension, folder='factory_logo')

            fac = Factory(name=factory_name, delegate=user.id, address=address, hotline=factory_hotline,logo=url)
            # fac = Factory(name=factory_name, delegate=user.id, address=address, hotline=factory_hotline)
            db.session.add(fac)
            db.session.commit()
            admin_users = User.query.filter_by(role=3).all()
            for admin in admin_users:
                if admin.device_token:
                    device_token = admin.device_token
                    message_title = "New Factory"
                    message_body = "There are new Factory!"
                    click_action = "/AdminDashboard/factory"
                    result = notf_service.notify_single_device(registration_id=device_token,
                                                               message_title=message_title,
                                                               click_action=click_action, message_body=message_body)
            response_obj = {
                'status': 'success',
                'message': 'Successfully Signed up'
            }
            return response_obj, 201
        except Exception as e:
            print('Exception in factory sign up:', e)
            response_obj = {
                'status': 'failed',
                'message': 'Something Wrong, please try again later'
            }
            return response_obj, 500
Ejemplo n.º 15
0
def insertData():
    # insert users
    from app.api.model.user import User
    # print("start inserting users")
    # users = [{'username': '******', 'email': '*****@*****.**', 'password': '******', 'role': 2,'phone':123},
    #          {'username': '******', 'email': '*****@*****.**', 'password': '******', 'role': 1,'phone':1235}, ]
    # for user in users:
    #     user = User(username=user['username'],email=user['email'],password=user['password'],role=user['role']
    #                 ,phone=user['phone'],account_status=1)
    #     db.session.add(user)
    #     db.session.commit()
    # users = User.query.all()
    # print("inserting users ==> Done")
    # print('users is :',users)

    ####################################################
    # insert factory
    # print("start inserting Factory")
    # name = 'الحديد والصلب'
    # delegate = 1
    # address = '5 شارع البحر'
    # hotline = "01255"
    # from app.api.model.factory import Factory
    # fac = Factory(name=name,delegate=delegate,address=address,hotline=hotline)
    # db.session.add(fac)
    # db.session.commit()
    # facts = Factory.query.all()
    # print("inserting factory ==> Done")
    # print("factories is :", facts)
    # ###################################################
    # # insert company
    # print("start inserting Company")
    # from app.api.model.com import Company
    #
    # try:
    #     comp = Company(name='النصر', account=2,address='شارع النحاس')
    #     db.session.add(comp)
    #     db.session.commit()
    # except Exception as e:
    #     # traceback.print_exc()
    #     print("Exceptions is :", e)
    # comps = Company.query.all()
    # print("inserting company ==> Done")
    # print("companies is : ", comps)

    #############################################
    # insert cars to company
    # cars = [
    #     ['car4', 1, Car.generate_qrcode(), 'trilla', 15,"ازرق"],
    #     ['car5', 2, Car.generate_qrcode(), 'maktura', 15,"ابيض"],
    #     ['car6', 2, Car.generate_qrcode(), 'maktura', 15,"اسود"],
    #     ['car7', 2, Car.generate_qrcode(), 'maktura', 15,"ابيض"],
    #     ['car8', 2, Car.generate_qrcode(), 'maktura', 15,"اخضر"],
    # ]
    # role = 4
    # for car in cars:
    #     car_user = User(username=car[0], email=car[0], password=car[2], phone=car[0], role=role)
    #     db.session.add(car_user)
    #     db.session.commit()
    #     new_car = Car(user_id=car_user.id, number=car[0], owner=car[1], qr_code=car[2], car_type=car[3],
    #                   capacity=car[4],color=car[5])
    #     db.session.add(new_car)
    #     db.session.commit()

    # cars = Car.query.all()
    # [print(car) for car in cars]
    ##############################################
    # inser drivers
    # drivers = [['ahmed','01203000270'],['ayman','01203050270'],['osama','01201000270']]
    # from app.api.model.driver import Driver
    # for driver in drivers:
    #     d = Driver(name=driver[0],phone=driver[1])
    #     db.session.add(d)
    #
    # db.session.commit()
    # drivers = Driver.query.all()
    # print(drivers)
    ###########################################
    # inser orders
    # from app.api.model.order import Order
    # order = Order(from_latitude=1,from_longitude=2,to_latitude=6,to_longitude=7,pickup_location='ayman ST',
    #               dropoff_location='ahmed ST', factory_id=1,num_of_cars=5)
    # db.session.add(order)
    # db.session.commit()
    # orders = Order.query.all()
    # print(orders)
    #####################################33
    # assign driver and car for order
    # new = OrderCarsAndDrivers(order_id=25,car_id=2,driver_id=2)
    # car = Car.query.get(2)
    # car.current_order_id = 25
    # car.status = 'busy'
    # db.session.add(new)
    # db.session.commit()
    ###################################3
    # add admin account
    admin = User(username='******',email="*****@*****.**",phone="01200",role=3,password="******",account_status=1)
    db.session.add(admin)
    db.session.commit()
    # import pandas as pd
    # factories = Factory.query.all()
    # f_list = [{
    #     'ID': factory.id,
    #     'Name': factory.name,
    #     'Hot line': factory.hotline,
    #     'username': factory.delegate_opj.username,
    #     'email': factory.delegate_opj.email,
    #     'user phone': factory.delegate_opj.phone
    # } for factory in factories]
    # df = pd.DataFrame.from_dict(f_list)
    # df.to_csv('file1.csv')
    ######################################
    pass
Ejemplo n.º 16
0
def insert_admin_employee(company):
    """
    insert admin details to the employee
    table.
    """
    try:
        user_data = request.get_json()
        id = generate_db_ids()
        this_company = Company.query.filter_by(
            company=user_data["company"]).first()
        _company = company_schema.dump(this_company)
        companyId = _company["id"]
        fullname = user_data["fullname"]
        # mobile = user_data["mobile"]
        email = user_data["email"]
        password = user_data["password"]
        role = user_data["role"]
        isActive = user_data["isActive"]

        # check data for sanity incase it bypass js on the frontend
        check_for_whitespace(
            user_data,
            [
                "companyId",
                "fullname",
                "email",
                # "mobile",
                "password",
                "role",
                "isActive",
            ],
        )
        if (company['id'] != companyId):
            abort(
                custom_make_response(
                    "error",
                    "There is a mismatch in your token info,\
                        we could not complete the request,\
                            Please reopen this page and try again.",
                    401
                )
            )

        isValidEmail(email)

        new_employee = Employees(
            id=id,
            companyId=companyId,
            fullname=fullname,
            # mobile=mobile,
            email=email,
        )

        db.session.add(new_employee)
        db.session.commit()
        # once you have created an admin as an employee
        # let create them as user in the system.
        isValidPassword(password)

        new_user = User(
            id=id,
            username=user_data["fullname"].split(" ")[0] + "." + id,
            email=email,
            password=password,
            role=role,
            companyId=companyId,
            isActive=isActive,
        )

        db.session.add(new_user)
        db.session.commit()

        return custom_make_response(
            "data",
            "Registration completed Successfully,\
                you can now signin & start using the system.",
            201,
        )
    except Exception as e:
        message = str(e)
        if "UniqueViolation" and "Employees_mobile_key" in message:
            abort(
                custom_make_response(
                    "error",
                    "The mobile number you have entered seems\
                        to have been registered to another user,\
                            please change and try again. ",
                    409,
                )
            )
        elif "Employees_email_key" and "UniqueViolation" in message:
            abort(
                custom_make_response(
                    "error",
                    "The email address you have entered seems\
                        to have been registered to another user,\
                            please change and try again. ",
                    409,
                )
            )
        else:
            abort(
                custom_make_response(
                    "error", message,
                    500,
                )
            )
Ejemplo n.º 17
0
def get_logged_in_user(request_header):
    """return the details of the logged in user

    Args:
        request_header (Response Object): flask request
    """

    # from the request get the authorization header
    auth_header = request_header.headers.get('Authorization')

    if auth_header:
        try:
            # check if the Authorization follows the format:
            # 'Bearer token-value'
            auth_token = auth_header.split(" ")[1]
        except IndexError:
            # when no token value can be established from the Authorization
            # value
            response_object = jsonify({
                'status':
                401,
                'message':
                'Malformed token. Check the token format.'
            })
            return response_object, 401
    else:
        auth_token = ''

    if auth_token:
        # check if token is blacklisted
        # prevents unauthorized access of resource when the user is logged out
        is_blacklisted = verify_blacklist(auth_token)
        if is_blacklisted is None:
            token_verified, response = verify_auth_decode(auth_token)

            if token_verified:
                user_by_id = User.get_user_by_id(response)
                user = db().get_single_row(*user_by_id)

                response_object = jsonify({
                    'status': 200,
                    'user': {
                        'user_id': user['id'],
                        'user_email': user['email'],
                        'is_admin': user['isadmin']
                    }
                })
                return response_object, 200
            # token verification error
            response_object = jsonify({"status": 401, "error": response})
            return response_object, 401

        # if the user token is in blacklist list
        response_object = jsonify({
            "status":
            401,
            "error":
            "User is logged out, Please log in again."
        })
        return response_object, 401

    # token provided is invalid
    response_object = jsonify({
        'status': 401,
        'message': 'Provide a valid auth token.'
    })
    return response_object, 401
Ejemplo n.º 18
0
    def post(self):
        data = request.form
        company_name = data.get('company_name')
        username = company_name  # data.get('username')
        email = data.get('email')
        password = User.generate_pass()
        address = data.get('address')
        phone = data.get('company_phone')
        role = 1
        user = User.query.filter_by(email=email).first()
        # img = request.files['company_logo']
        if user:
            return redirect(
                url_for(
                    'base_blueprint.SignupCompany',
                    error="FAILED: user with entered E-mail already exist!"))

        user = User.query.filter_by(username=username).first()
        if user:
            return redirect(
                url_for('base_blueprint.SignupCompany',
                        error="FAILED: user with entered name already exist!"))

        user = User.query.filter_by(phone=phone).first()
        if user:
            return redirect(
                url_for(
                    'base_blueprint.SignupCompany',
                    error="FAILED: user with entered phone already exist!"))

        user = User(username=username,
                    email=email,
                    role=role,
                    password=password,
                    phone=phone)
        db.session.add(user)
        com = Company.query.filter_by(name=company_name).first()
        if com:
            return redirect(
                url_for(
                    'base_blueprint.SignupCompany',
                    error="FAILED: company with entered name already exist!"))

        com = Company.query.filter_by(address=address).first()
        if com:
            return redirect(
                url_for(
                    'base_blueprint.SignupCompany',
                    error="FAILED: company with entered address already exist!"
                ))
        # _, file_extension = os.path.splitext(img.filename)
        # url = upload_file_to_s3(img, file_name=company_name + file_extension, folder='company_logo')
        com = Company(name=company_name, account=user.id, address=address)
        db.session.add(com)
        db.session.commit()
        message_title = "New Company"
        message_body = "There are New company signed up, check pending companies!"
        device_token = "fQQZG641vkY:APA91bH02cIkdvFru7j7n6zwZzitFqZLvrT-IPW6RLuQRJfdSjHRNzG-0HWxd3aL6FsBQMFmTl3X00GaB8NkcTyjQXTmBoaSk2KQJ2Qm2JYvaDdUXzOTomEPhoY_jzFcVILwDtMlUaSR"
        result = notf_service.notify_single_device(
            registration_id=device_token,
            message_title=message_title,
            message_body=message_body,
            click_action="/AdminDashboard/company")
        admin_users = User.query.filter_by(role=3).all()
        for admin in admin_users:
            if admin.device_token:
                device_token = admin.device_token
                message_title = "New Company"
                message_body = "There are new Company!"
                click_action = "/AdminDashboard/company"
                result = notf_service.notify_single_device(
                    registration_id=device_token,
                    message_title=message_title,
                    click_action=click_action,
                    message_body=message_body)
        return redirect(
            url_for(
                'base_blueprint.login',
                message=
                "Successfully Signed up, waiting for Admin approve then you will "
                "receive Accepted E-mail from us"))
Ejemplo n.º 19
0
    def post(self):
        data = request.form
        company_name = data.get('company_name')
        username = company_name  # data.get('username')
        email = data.get('email')
        password = User.generate_pass()  # data.get('password')
        address = data.get('address')
        phone = data.get('company_phone')
        img = request.files['company_logo']
        role = 1
        user = User.query.filter_by(email=email).first()
        if user:
            return redirect(
                url_for(
                    'company_blueprint.route_error',
                    error="FAILED: user with entered E-mail already exist!"))

        user = User.query.filter_by(username=username).first()
        if user:
            return redirect(
                url_for('company_blueprint.route_error',
                        error="FAILED: user with entered name already exist!"))

        user = User.query.filter_by(phone=phone).first()
        if user:
            return redirect(
                url_for(
                    'company_blueprint.route_error',
                    error="FAILED: user with entered phone already exist!"))

        user = User(username=username,
                    email=email,
                    role=role,
                    password=password,
                    phone=phone)
        db.session.add(user)
        com = Company.query.filter_by(name=company_name).first()
        if com:
            return redirect(
                url_for(
                    'company_blueprint.route_error',
                    error="FAILED: company with entered name already exist!"))

        com = Company.query.filter_by(address=address).first()
        if com:
            return redirect(
                url_for(
                    'company_blueprint.route_error',
                    error="FAILED: company with entered address already exist!"
                ))
        _, file_extension = os.path.splitext(img.filename)
        url = upload_file_to_s3(img,
                                file_name=company_name + file_extension,
                                folder='company_logo')
        com = Company(name=company_name,
                      account=user.id,
                      address=address,
                      logo=url)
        db.session.add(com)
        db.session.commit()
        return redirect(url_for('company_blueprint.index'))
Ejemplo n.º 20
0
    def post(self):
        data = request.form
        factory_name = data["factory_name"]
        username = data["logistic_name"]
        address = data["address"]
        email = data["email"]
        factory_hotline = data["factory_hotline"]
        delegate_phone = data["delegate_phone"]
        password = User.generate_pass()
        img = request.files['factory_logo']
        role = 2
        user = User.query.filter_by(email=email).first()
        if user:
            return redirect(
                url_for(
                    'factory_blueprint.route_error',
                    error="FAILED: user with entered E-mail already exist!"))

        user = User.query.filter_by(username=username).first()
        if user:
            return redirect(
                url_for('factory_blueprint.route_error',
                        error="user with entered name already exist!"))

        user = User.query.filter_by(phone=delegate_phone).first()
        if user:
            return redirect(
                url_for('factory_blueprint.route_error',
                        error="user with entered phone already exist!"))

        user = User(username=username,
                    email=email,
                    role=role,
                    password=password,
                    phone=delegate_phone,
                    account_status=1)
        db.session.add(user)

        fac = Factory.query.filter_by(name=factory_name).first()
        if fac:
            return redirect(
                url_for('factory_blueprint.route_error',
                        error="factory with entered name already exist!"))

        fac = Factory.query.filter_by(address=address).first()
        if fac:
            return redirect(
                url_for('factory_blueprint.route_error',
                        error="factory with entered address already exist!"))

        fac = Factory.query.filter_by(hotline=factory_hotline).first()
        if fac:
            return redirect(
                url_for('factory_blueprint.route_error',
                        error="factory with entered hot line already exist!"))
        _, file_extension = os.path.splitext(img.filename)
        url = upload_file_to_s3(img,
                                file_name=factory_name + file_extension,
                                folder='factory_logo')
        fac = Factory(name=factory_name,
                      delegate=user.id,
                      address=address,
                      hotline=factory_hotline,
                      logo=url)
        db.session.add(fac)
        db.session.commit()
        return redirect(url_for('factory_blueprint.index'))