Пример #1
0
async def profile(request):

    if "username" not in request.session:
        logger.error(
            f"user page access without being logged in from {request.client.host}"
        )
        raise HTTPException(status_code=403)

    username = request.path_params["username"]
    # can_edit = check_can_edit(request, username)

    query = users.select().where(users.c.username == username)
    profile_user = await database.fetch_one(query)
    if profile_user is None:
        raise HTTPException(status_code=403)

    repo_data = await github_calls.get_repo_list(username)
    user_data = await github_calls.get_user_info(username)
    user_events = await github_calls.get_user_events(username)
    status_code = 200
    template = "profile.html"
    context = {
        "request": request,
        "owner": username,
        "profile_user": profile_user,
        "repo_data": repo_data,
        "user_data": user_data,
        "user_events": user_events,
    }
    return templates.TemplateResponse(template,
                                      context,
                                      status_code=status_code)
Пример #2
0
async def email_check(email: str):

    # check if unique email
    email_address = email.lower()
    query = users.select().where(users.c.email == email_address)
    logger.info(f"validating email: {email_address}")
    result = await fetch_one_db(query)
    logger.debug(f"query result = {result}")
    return result
Пример #3
0
async def callback(request):
    from main import github_client, github_api_client

    # Obtain an access token.
    code = request.query_params.get("code", "")
    url = "/login/oauth/access_token"
    data = {
        "client_id": settings.GITHUB_CLIENT_ID,
        "client_secret": settings.GITHUB_CLIENT_SECRET,
        "code": code,
    }
    headers = {"accept": "application/json"}
    response = await github_client.post(url, data=data, headers=headers)
    logger.debug(response.request.url)
    response.raise_for_status()
    data = response.json()
    #  Make a request to the API.
    url = "/user"
    headers = {
        "authorization": f'token {data["access_token"]}',
    }
    response = await github_api_client.get(url, headers=headers)
    logger.debug(response.request.url)
    response.raise_for_status()
    data = response.json()

    # Log the user in, and redirect back to the homepage.
    query = users.select().where(users.c.github_id == data["id"])
    user = await fetch_one_db(query=query)
    if user is None:

        query = users.insert()
        values = {
            "created_at": datetime.datetime.now(),
            "last_login": datetime.datetime.now(),
            "username": data["login"],
            "github_id": data["id"],
            "is_admin": False,
            "name": data["name"],
            "avatar_url": data["avatar_url"],
        }
    else:
        query = users.update().where(users.c.github_id == data["id"])
        values = {
            "last_login": datetime.datetime.now(),
            "username": data["login"],
            "name": data["name"],
            "avatar_url": data["avatar_url"],
        }
    await execute_one_db(query=query, values=values)

    request.session["username"] = data["login"]
    request.session["realname"] = data["name"]
    request.session["avatar_url"] = data["avatar_url"]
    url = request.url_for("profile", username=data["login"])
    logger.info(f'logging {request.session["username"]} and send to profile page')
    return RedirectResponse(url, status_code=303)
Пример #4
0
async def user_name_check(user_name: str):

    # check if unique user_name
    user_name = user_name.lower()
    query = users.select().where(users.c.user_name == user_name)
    logger.info(f"validating user_name: {user_name}")
    result = await fetch_one_db(query)
    logger.debug(f"LOOK AT THIS query result = {result}")
    return result
Пример #5
0
async def create_admin():

    await asyncio.sleep(0.5)

    if settings.ADMIN_CREATE.lower() == "true":
        check_query = users.select()
        check_result = await fetch_all_db(query=check_query)
        logger.debug(str(check_result))

        if len(check_result) == 0:

            hashed_pwd = encrypt_pass(settings.ADMIN_USER_KEY)
            values = {
                # input fields
                "first_name": "admin",
                "last_name": "istrator",
                "last_login": datetime.datetime.now(),
                "user_name": settings.ADMIN_USER_NAME.lower(),
                "password": hashed_pwd,
                "email": settings.ADMIN_USER_EMAIL,
                "address": "123 Maple St",
                "city": "Clearwater",
                "state": "Florida",
                "country": "USA",
                "postal": "33761",
                "phone": "727-456-7890",
                "mobile_phone":"727-456-7890",
                # system created fields
                "user_id": str(uuid.uuid4()),
                "date_created": datetime.datetime.now(),
                "is_active": True,
                "is_admin": True,
                "from_config": True,
                "first_login": True,
            }
            logging.debug(values)
            query = users.insert()
            logging.warning("Creating Admin account")
            try:
                db_result = await execute_one_db(query=query, values=values)
                logging.debug(type(db_result))
            except Exception as e:
                logger.warning(
                    f"An error occurred trying to update {settings.ADMIN_USER_NAME.lower()}"
                )
                return "error"

        else:
            logger.warning(
                "Skipping first account setup as there are existing users. DISABLE create ADMIN_CREATE for security."
            )
Пример #6
0
async def valid_login(user_name: str, pwd: str):
    # get user user_name
    user_name = user_name.lower()
    logger.debug(f"checking if {user_name} has valid id")
    query = users.select().where(users.c.user_name == user_name)
    logger.info(f"fetch user_name: {user_name}")
    user_data = await fetch_one_db(query)
    logger.debug(f"LOOK AT THIS query result = {user_data}")

    if user_data == None:
        result = False

        return result

    result = verify_pass(pwd, user_data["password"])
    logger.info(f"password validity is {result}")
    return result
Пример #7
0
async def user_info(user_name: str):
    """[summary]

    Arguments:
        user_name {str} -- [description]

    Returns:
        [type] -- [description]
    """
    query = users.select().where(users.c.user_name == user_name)
    logger.info(query)

    try:
        result = await fetch_one_db(query=query)

        return result

    except Exception as e:
        logger.warning(f"An error occurred trying to update {user_name}")
        return "error"
Пример #8
0
async def login(request):
    logger.debug(f"request")
    form = await forms.AccountLoginForm.from_formdata(request)
    form_data = await request.form()

    if await form.validate_on_submit():
        logger.critical(form_data)
        user_name = form_data["user_name"]
        user_name = user_name.lower()
        pwd = form_data["password"]
        logger.debug(f"user_name: {user_name}, pwd: {pwd}")

        result = await form_validators.valid_login(pwd=pwd,
                                                   user_name=user_name)
        logger.debug(f"loging valid = {result}")

        # user_name = user_name.lower()
        logger.debug(f"checking if {user_name.lower()} has valid login")
        query = users.select().where(users.c.user_name == user_name)
        logger.info(f"fetch user_name: {user_name}")
        user_data = await fetch_one_db(query)
        logger.debug(f"LOOK AT THIS query result = {user_data}")

        last_login_values = {"last_login": datetime.datetime.now()}
        last_login_query = users.update().where(users.c.user_name == user_name)
        await execute_one_db(query=last_login_query, values=last_login_values)
        logger.info(f"updating last login for {user_name}")
        if result == False:
            client_host = request.client.host
            fail_values: dict = {
                "id": str(uuid.uuid4()),
                "date_created": datetime.datetime.now(),
                "user_name": user_name,
                "ip_address": client_host,
            }
            fail_query = user_login_failures.insert()
            await execute_one_db(query=fail_query, values=fail_values)
            logger.warning(
                f"User login failure for {user_name} from {client_host}")
            form.user_name.errors.append(f"user_name or Password is invalid")

        elif user_data["is_active"] == False:
            form.user_name.errors.append(
                f"The user id is not active or been approved for login")
        else:
            # get user user_name

            request.session["user_name"] = user_data["user_name"]
            request.session["updated"] = str(datetime.datetime.utcnow())
            request.session["admin"] = user_data["is_admin"]
            request.session[
                "realname"] = f'{user_data["first_name"]} {user_data["last_name"]}'
            logger.info(
                f'logger {request.session["user_name"]} and send to profile page'
            )
            return RedirectResponse(url="/", status_code=303)

    template = f"{page_url}/login.html"
    context = {"request": request, "form": form}
    logger.info(f"page accessed: /user/login")
    return templates.TemplateResponse(template, context)
Пример #9
0
async def user_data(use_name: str):

    query = users.select().where(users.c.user_name == use_name)
    result = await fetch_one_db(query=query)
    return result