예제 #1
0
async def get_mine(
    request: Request,
    current_user: schemas.HotelScope = Depends(get_current_active_user),
    db: Session = Depends(get_db)):
    log_info(logging, "hello please loge me in..........")
    log_info(logging, current_user)
    return current_user
예제 #2
0
def get_current_active_user(current_user: schemas.HotelScope = Security(get_current_google_user, scopes=["user", "owner"])):
    # , current_google_user: User = Depends(get_current_google_user)
    """
    """
    print("the current active user is.......")
    print(current_user)
    qrl.log_info(logging,current_user)
    return current_user
예제 #3
0
def delete_menu(db: Session, menu_id):
    try:
        db.query(models.Menu).filter(models.Menu.id == menu_id).delete()
        db.commit()
        qrl.log_info(logging, f'deleted records of menu records :{menu_id}')
        return status.HTTP_200_OK
    except:
        qrl.log_exception(logging, status.HTTP_404_NOT_FOUND)
        return HTTPException(status.HTTP_404_NOT_FOUND)
예제 #4
0
async def get_current_google_user(security_scopes: SecurityScopes,
                                  token: str = Depends(oauth2_scheme),
                                  db: Session = Depends(get_db)):
    credentials_exception = HTTPException(
        status_code=HTTP_403_FORBIDDEN,
        detail="Could not validate credentials")
    #db = get_db()
    print(token)
    qrl.log_info(logging, db)
    qrl.log_info(logging, token)

    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = f"Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )

    if token is not None:
        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
            print("the payload is.................")
            print(payload)
            print("-----------------------------------")
            #qrl.log_info(logging, payload.__dict__)
            email: str = payload.get("sub")
            if email is None:
                raise credentials_exception
            token_scopes = payload.get("scopes", [])
            print(token_scopes)
            print(payload.get('scopes'))
            token_data = schemas.TokenData(scopes=token_scopes, username=email)
        except (JWTError, ValidationError):
            return credentials_exception
        print("I am the current_user")
        print(email)
        if email is not None:
            authenticated_user = crud.authenticate_user_email(db, email)
            print(authenticated_user.id)
            if authenticated_user.position == 'owner':
                hotel_names = crud.get_hotels_by_username(
                    db, authenticated_user.id)
                print(hotel_names)
                return schemas.HotelScope(email=authenticated_user.email,
                                          position=authenticated_user.position,
                                          hotels=hotel_names)
            else:
                return schemas.HotelScope(email=authenticated_user.email,
                                          position=authenticated_user.position,
                                          hotels=[])
예제 #5
0
def add_hotel_to_favourite(db: Session, user_id, hotel_id):
    try:
        db_fav_hotel = models.CustomerFavMenu(user_id=user_id,
                                              hotel_id=hotel_id)
        qrl.log_info(f'user_id: {user_id} and hotel_id: {hotel_id}')
        db.add(db_fav_hotel)
        db.commit()
        db.refresh(db_fav_hotel)
        return db_fav_hotel
    except Exception as e:
        qrl_log_exception(logging, repr(e))
        return repr(e)
예제 #6
0
async def check_user_and_make_token(request: Request,
                                    db: Session = Depends(get_db)):
    formdata = await request.form()
    print(request)
    print(formdata)
    print("the scopes are .......")
    #print(formdata.scopes)
    print(formdata["username"], formdata["password"])
    authenticated_user = authenticate_user(db, formdata["username"],
                                           formdata["password"])
    print(authenticated_user)
    if authenticated_user is None:
        raise HTTPException(status_code=401,
                            detail="Invalid username or password")

    access_token_expires = timedelta(hours=ACCESS_TOKEN_EXPIRE_HOURS)
    log_info(logging, authenticated_user.email)

    user_scope = authenticated_user.position  # if isinstance(authenticated_user.position, list) else [authenticated_user.position]
    print("the user scope is........")
    print(user_scope)
    access_token = create_access_token(data={
        "sub": authenticated_user.email,
        "scopes": user_scope
    },
                                       expires_delta=access_token_expires)

    #################### SUCCESSFULLY LOGED IN USING CUSTOM DETAILS ######################
    #crud.logged_in(authenticated_user.id,"custom",request)

    token = jsonable_encoder(access_token)
    print("token is----------------------")
    print(token)
    response = JSONResponse({"access_token": token, "token_type": "bearer"})

    response.set_cookie(
        key=COOKIE_AUTHORIZATION_NAME,
        value=f"Bearer {token}",
        domain=COOKIE_DOMAIN,
        httponly=True,
        max_age=10800,  # 3 hours
        expires=10800,  # 3 hours
    )
    print(response.__dict__)
    return response
예제 #7
0
def insert_into_hotel_menu(db: Session, menu_items, user_id: int):

    print(menu_items)
    item = {}
    item['hotel_id'] = user_id
    item['items'] = menu_items
    print(item)
    qr_code = qrcode.QRCode(version=1, box_size=10, border=4)
    qr_code.add_data(menu_items)
    qr_code.make(fit=True)
    print('----------------------')
    dir_path = '/'.join(os.path.abspath(os.getcwd()).split('\\'))
    print(dir_path)
    folders = [x[0] for x in os.walk(dir_path)]
    print(folders)
    print('----------------------')
    qr_image = qr_code.make_image(fill='black', back_color='yellow')
    qr_image.save(dir_path + '/' + 'qr_menus' + '/' + str(item['hotel_id']) +
                  '_' + "menu.png")
    qr_path = dir_path + '/' + 'qr_menus' + '/' + str(
        item['hotel_id']) + '_' + "menu.png"
    print(qr_image)

    print(os.getcwd())
    try:
        db_menu_item = models.Menu(hotel_id=user_id,
                                   items=menu_items,
                                   qr_menu_path=qr_path)
        qrl.log_info(
            logging,
            f'hotel_id: {user_id},\nmenu_items: {menu_items},\nqr_menu_path:{qr_path}'
        )
        print(db_menu_item)
        db.add(db_menu_item)
        db.commit()
        db.refresh(db_menu_item)
        return db_menu_item
    except Exception as e:
        qrl.log_exception(logging, repr(e))
        return repr(e)
예제 #8
0
# -*- coding: utf-8 -*-
"""
Created on Fri Dec  4 18:43:52 2020

@author: Ravi Varma Injeti
@contributor: KrishNa
"""

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from qr_logger import create_or_get_logger, log_info

# SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
filename = 'database.log'
logging = create_or_get_logger(filename)
username = '******'
password = '******'
ip_address = 'localhost'
port = '5432'
db = 'mymenu'
#SQLALCHEMY_DATABASE_URL = f"postgresql://{username}:{password}@{ip_address}:{port}/{db}"
SQLALCHEMY_DATABASE_URL = "postgres://*****:*****@ec2-54-90-13-87.compute-1.amazonaws.com:5432/db0n84qslnukga"
log_info(logging, SQLALCHEMY_DATABASE_URL)
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()