Example #1
0
    def post():

        # Get refresh token.
        refresh_token = request.json.get('refresh_token')

        # Get if the refresh token is in blacklist.
        ref = Blacklist.query.filter_by(refresh_token=refresh_token).first()

        # Check refresh token is existed.
        if ref is not None:

            # Return invalidated token.
            return {'status': 'invalidated'}

        try:
            # Generate new token.
            data = refresh_jwt.loads(refresh_token)

        except Exception as why:
            # Log the error.
            logging.error(why)

            # If it does not generated return false.
            return False

        # Create user not to add db. For generating token.
        user = User(email=data['email'])

        # New token generate.
        token = user.generate_auth_token(False)

        # Return new access token.
        return {'access_token': token}
Example #2
0
def create_sale_record():
    """ Creates a new sale record"""
    user = User()
    data = request.get_json()
    date_sold = datetime.now()
    price = product.fetch_product_price(data['product_name'])
    current_user = user.fetch_current_user()
    total_amount = int(price) * int(data['product_quantity'])
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token) is False:
        return jsonify({"message": "Permission Denied, Not an Attendant"}), 400
    valid = validate.validate_sale(data)
    try:
        if valid == "Sale_valid":
            if product.check_if_product_exists(data['product_name']) is False:
                return jsonify({"message": "Product does not exist"}), 400
            if int(price) != int(data['price']):
                return jsonify({"message": "Enter correct price"}), 400
            if product.compute_stock_balance(data['product_quantity'],
                                             data['product_name']) is False:
                return jsonify(
                    {"message":
                     "Stock balance less than requested quantity"}), 400
            salerecord.make_a_sale(total_amount, current_user,
                                   data['product_name'],
                                   data['product_quantity'], price, date_sold)
            product.reduce_stock_after_sale(data['product_quantity'],
                                            data['product_name'])
            return jsonify({"message": "record created successfully"}), 201
        return jsonify({"message": valid}), 400
    except ValueError:
        return jsonify({"message": "Invalid"})
Example #3
0
async def change_username(new_username: NewUsername,
                          user: User = Depends(get_current_user)):
    """
    Endpoint that allows a User to change his Username
    It takes a new username, it checks that the
    new username satisfies the requirements.
    Returns:
    200 OK              message : You have changed your username succesfully,
    401 UNAUTHORIZED    detail : Could not validate credentials,
    409 CONFLICT        detail : nickname not available
    422 BAD ENTITY      detail : The new username doesen't satisfies the requirements,
    503 SERVICE UNAVAILABLE detail : Something went wrong on the database
    """
    email = user['email']
    try:
        with db_session:
            uname = new_username.username
            exists = db.exists("select * from DB_user where username = $uname")
    except:
        raise HTTPException(status_code=503,
                            detail="Service unavailable, try again soon")
    if exists:
        raise HTTPException(status_code=409,
                            detail="Nickname already registered")
    else:
        with db_session:
            user = db.DB_User.get(email=email)
            user.set(username=new_username.username)
            commit()
    return {"message": "You have changed your nickname succesfully"}
def logout():
    """Logs out a user"""
    user = User()
    user_token = request.headers['Authorization']
    token = user_token.split(" ")[1]
    if user.blacklist_token(token):
        return jsonify({"message": "log out successful"}), 200
Example #5
0
async def change_psw(new_password_request: NewPassword,
                     user: User = Depends(get_current_user)):
    """
    Endpoint that allows a User to change his password
    It takes the old password and the new one, it checks that the
    new password satisfies the requirements.
    Returns:
    200 OK              message : You have changed your password succesfully,
    401 UNAUTHORIZED    detail : Could not validate credentials,
    401 UNAUTHORIZED    detail : Wrong old password,
    422 BAD ENTITY      detail : The new password doesen't satisfies the requirements,
    503 SERVICE UNAVAILABLE detail : Something went wrong on the database
    """

    if not verify_password(new_password_request.old_pwd,
                           user['hashed_password']):
        raise HTTPException(status_code=401, detail="Wrong old password")
    email = user['email']
    try:
        new_hash = get_password_hash(new_password_request.new_pwd)
        with db_session:
            user = db.DB_User.get(email=email)
            user.set(hashed_password=new_hash)
            commit()
    except Exception as e:
        print(e)
        raise HTTPException(status_code=503,
                            detail="Service unavailable, try again soon")
    return {"message": "You have changed your password succesfully"}
Example #6
0
def create_product():
    """Creates a new product"""
    user = User()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token):
        return jsonify({"message": "Permission Denied, Not Admin"}), 400
    data = request.get_json()
    product = Product()
    valid = validate.validate_product(data)
    try:
        if valid == "Valid":
            if product.check_if_product_exists(data['product_name']):
                return jsonify({"message": "Product already exists"})
            if category.check_if_category_exists(data['category_name'])\
                    is False:
                return jsonify({"message": "This category does not exist"})
            product.add_new_product(data)
            return jsonify({"message": "Product added successfully"}), 201
        return jsonify({"message": valid}), 400
        created_token.remove(data_token)
    except ValueError:
        return jsonify({"message": "Invalid fields"}), 400
def fetch_users():
    """ Fetches all registered users"""
    user = User()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token):
        return jsonify({"message": "Permission Denied, Not Admin"}), 400
    all_users = user.fetch_all_users()
    return jsonify({"Users": all_users}), 200
Example #8
0
def fetch_sale_orders():
    """This endpoint fetches all sale records"""
    user = User()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token):
        return jsonify({"message": "Permission Denied, Not Admin"}), 400
    fetched_sales = salerecord.view_all_sales()
    return jsonify({"Sales": fetched_sales}), 200
def assigns_token(data):
    user = User()
    if user.fetch_password():
        token = jwt.encode(
            {
                'user': data['username'],
                'exp': datetime.utcnow() + timedelta(hours=24),
                'roles': user.get_role()
            }, secret_key)
        return jsonify({'token': token.decode('UTF-8')}), 200
    return jsonify(
        {"message": "User either not registered or forgot password"}), 400
Example #10
0
def delete_product(product_id):
    user = User()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token):
        return jsonify({"message": "Permission Denied, Not Admin"}), 400
    product = Product()
    if product_id == 0 or product.check_if_id_exists(product_id):
        return jsonify({"message": "Index out of range"}), 400
    product.delete_product(product_id)
    return jsonify({"message": "product successfully removed"}), 200
def update_role(employee_id):
    """Updates the user role"""
    user = User()
    data = request.get_json()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token):
        return jsonify({"message": "Permission Denied, Not Admin"}), 400
    if employee_id == 0:
        return jsonify({"message": "Index is out of range"}), 400
    if data['role'] != 'Admin' and data['role'] != 'Attendant':
        return jsonify({"message": "role can only be Admin or Attendant"}), 400
    user.update_user_role(data['role'], employee_id)
    return jsonify({'message': "role successfully updated"}), 200
def create_super_admin():

    # Check if admin is existed in db.
    user = User.query.filter_by(email='test_username').first()

    # If user is none.
    if user is None:

        # Create admin user if it does not existed.
        user = User(username='******', password='******',
                    email='*****@*****.**', user_role='sa')

        # Add user to session.
        db.session.add(user)

        # Commit session.
        db.session.commit()

        # Print admin user status.
        print("Super admin was set.")

    else:

        # Print admin user status.
        print("Super admin already set.")
def create_test_user(username=None, password=None, email=None, user_role=None):

    # Check if admin is existed in db.
    user = User.query.filter_by(email='test_username').first()

    # If user is none.
    if user is None:

        # Create admin user if it does not existed.
        # user = User(username=username, password=password, email=email, user_role=user_role)
        user = User(username='******', password='******', email='*****@*****.**',
                    user_role='user')

        # Add user to session.
        db.session.add(user)

        # Commit session.
        db.session.commit()

        # Print admin user status.
        print("Test user was set.")

    else:

        # Print admin user status.
        print("User already set.")
def fetch_single_user(employee_id):
    """ Returns a single user"""
    user = User()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token):
        return jsonify({"message": "Permission Denied, Not Admin"}), 400
    try:
        if employee_id != 0:
            single_user = user.fetch_single_user(employee_id)
            return jsonify({"Record": single_user}), 200
        return jsonify({"message": "Index out of range!"}), 400
    except Exception:
        return jsonify({"message": "user not found"}), 404
Example #15
0
def get_single_record(sale_id):
    user = User()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if user.fetch_current_user() != salerecord.fetch_user_from_sale(sale_id)\
            and validate.check_permission(token):
        return jsonify({"message": "Not authorised to view this sale!"})
    try:
        if sale_id != 0 or salerecord.check_sale_id_exists(sale_id):
            single_sale = salerecord.view_sale_by_id(sale_id)
            return jsonify({"Record": single_sale}), 200
        return jsonify({"message": "Index out of range!"}), 400
    except Exception:
        return jsonify({"message": "Sale not found"}), 404
Example #16
0
def modify_product(product_id):
    """Updates a product"""
    user = User()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token):
        return jsonify({"message": "Permission Denied, Not Admin"}), 400
    product = Product()
    if product_id == 0 or product.check_if_id_exists(product_id):
        return jsonify({"message": "Index is out of range"}), 400
    data = request.get_json()
    valid = validate.validate_product(data)
    if valid == "Valid":
        product.update_product(product_id, data['product_quantity'],
                               data['product_name'], data['price'])
        return jsonify({'message': "successfully updated"}), 200
    return jsonify({"message": valid}), 400
def register_user():
    """ registers a user"""
    user = User()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token):
        return jsonify({"message": "Permission Denied, Not Admin"}), 400
    data = request.get_json()
    is_valid = validate.validate_user(data)
    try:
        if is_valid == "is_valid":
            if user_obj.check_for_existing_user(data['email']):
                return jsonify({"message": "Email already exists, login"})
            user_obj.add_user(data)
            return jsonify({"message": "User registered successfully"}), 201
        return jsonify({"message": is_valid}), 400
    except Exception:
        return jsonify({"message": "Username already exists, login"}), 400
Example #18
0
def create_category():
    """Creates a new category"""
    user = User()
    fetched_token = request.headers['Authorization']
    token = fetched_token.split(" ")[1]
    if user.validate_token(token):
        return jsonify({"message": "Token blacklisted, login again"}), 400
    if validate.check_permission(token):
        return jsonify({"message": "Permission Denied, Not Admin"}), 400
    data = request.get_json()
    category_valid = validate.validate_category(data)
    created_at = datetime.now()
    try:
        if category_valid == "category_valid":
            new_category.add_new_category(data['category_name'], created_at)
            return jsonify({"message":
                            "Category successfully created"}), 201
        else:
            return jsonify({"message": category_valid}), 400
    except Exception:
        return jsonify({"message": " Category exists already"}), 400
Example #19
0
    def post():

        try:
            # Get username, password and email.
            username, password, email = request.json.get('username').strip(), request.json.get('password').strip(), \
                                        request.json.get('email').strip()
        except Exception as why:

            # Log input strip or etc. errors.
            logging.info("Username, password or email is wrong. " + str(why))

            # Return invalid input error.
            return error.INVALID_INPUT_422

        # Check if any field is none.
        if username is None or password is None or email is None:
            return error.INVALID_INPUT_422

        # Get user if it is existed.
        user = User.query.filter_by(email=email).first()

        # Check if user is existed.
        if user is not None:
            return error.ALREADY_EXIST

        # Create a new user.
        user = User(username=username, password=password, email=email)

        # Add user to session.
        db.session.add(user)

        # Commit session.
        db.session.commit()

        # Return success if registration is completed.
        return {'status': 'registration completed.'}
from flask import request, jsonify, Blueprint
from api.validators import Validate
from api.models.user_models import User
from flasgger import swag_from
from datetime import datetime, timedelta
from functools import wraps
from config import secret_key
import jwt

user = Blueprint('user', __name__)
user_obj = User()
validate = Validate()


def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        if 'Authorization' in request.headers:
            token = request.headers['Authorization']
        if not token:
            return jsonify({"message": "Missing Token"}), 403
            jwt.decode(token, secret_key)
        return f(*args, **kwargs)

    return decorated


@user.route('/api/v2/auth/signup', methods=['POST'])
@swag_from('../apidocs/users/create_user.yml')
@token_required