teleren/devto huggingface dataset:
Multiple OAuth2 Schemes FastAPI
Tags: fastapi, backend, restapi, oauth
Published: 2024-07-01 14:16:39

## Introduction
How do you create multiple OAuth2 token schemes in FastAPI and make sure they are usable in the SwaggerUI auto documentation?

I am building a REST API for a SaaS Loan Management System (LMS) to be used internally by company personnel. I have two kinds of users: 

1. **System users** - LMS software administrators.
2. **Company users** - personnel using the software. 

System users can create companies and the first company users. Assign admin role, to allow them to register other company users linked to the same company. 

I created two OAuth2 token schemes; `admin_oauth2` for system users and `user_oauth2` for company users. Separating the authentication models it made it easy to manage. I can create tokens for admins with a simple payload of expiration date and admin ID. And add extra data in the company users' token like the company ID and the user roles for easy role-based access control and authorization.

## Creating Multiple OAuth2 Schemes in FastAPI
To create multiple OAuth2 schemes, create two token dependencies; one for the admins, and another for users.

```python
...
user_oauth2 = OAuth2PasswordBearer(
    tokenUrl="/api/v1/login/access-token",
    scheme_name="user_oauth2",
)
UserTokenDep = Annotated[str, Depends(user_oauth2)]

admin_oauth2 = OAuth2PasswordBearer(
    tokenUrl="/api/v1/admin/login/access-token",
    scheme_name="admin_oauth2",
)
AdminTokenDep = Annotated[str, Depends(admin_oauth2)]
```
That will allow an API to have two OAuth2 authentications depending on the endpoint accessed. Notice the `scheme_name` argument in the scheme definition. That's an important detail when you have multiple OAuth2 schemes in the same API - that is, if you don't define the scheme name, the authentication token depends on the last endpoint you defined regardless of whether the operation depends on that token or the other token. I spent hours trying to figure out that simple detail. That's all there is to it, the rest are skill issues.

## Read Me
Hi there! I am Paul John, a recent software engineering graduate. I recently joined a backend, DevOps and Product Testing internship at [HNG Internship](https://hng.tech/internship) to put my learned skills to work and broaden my horizons in Software engineering. My goal is to be able to create a software product from scratch to the maintenance stage (the whole SDLC).

If anything, check out [HNG Premium](https://hng.tech/premium), it delivers added value to the Internship.

Adios!
Bumping the Node.js version to higher version
Tags: react, webdev, node
Published: 2024-07-01 14:06:07

Before bumping the Node.js version to higher version in your package.json, you should consider the following:

## Check Node.js Release Schedule:

The Node.js release schedule is available at https://nodejs.org/en/about/releases/. You should use a version that is currently maintained.

## Check Dependencies Compatibility:

 Ensure that all your dependencies are compatible with the new Node.js version. You can check the engines field in the package.json of your dependencies, or check their documentation.

## Update Your Development Environment: 
Make sure that your local development environment is running the same Node.js version. You can use a version manager like nvm to manage multiple Node.js versions on your machine.

There are some methods to check this but you also can use this script to check all packages' engine

```js
import fs from 'fs'
import { exec } from 'child_process'
const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'))

const allDependencies = { ...packageJson.dependencies, ...packageJson.devDependencies }

for (const dependency in allDependencies) {
  exec(`npm view ${dependency} engines`, (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`)
      return
    }
    console.log(`Engines for ${dependency}: ${stdout}`)
  })
}
```

## Update Your CI/CD Pipeline: 
If you have a continuous integration/continuous deployment (CI/CD) pipeline, make sure to update the Node.js version there as well.

## Inform Your Team: 
If you're working in a team, inform everyone about the Node.js version change so they can update their local environments.

## Test Your Application: 

After updating the Node.js version, thoroughly test your application to catch any potential issues caused by the version change.



Here's how you can update the Node.js version to `20` in your package.json:

```json
"engines": {
  "node": ">=20"
}
```

 
Thank you for taking the time to read the article. I would love to hear your approach and tips on upgrading the node. 
HASH
Unlocking Business Success: The Importance of Having a Website
Tags: business, websitedevelopment, digitalmarketing, smallbusiness
Published: 2024-07-01 13:52:25

### Why Every Business Needs a Website

In today's digital age, having a strong online presence is crucial for the success of any business. A key component of this presence is a well-designed and functional website. Whether you're a small local shop or a multinational corporation, here’s why having a business website is essential:

#### Origins of Business Websites

Business websites originate from the need to establish an online presence and connect with potential customers on the internet. They evolved as a digital storefront and communication hub for businesses of all sizes.

#### Benefits of Having a Business Website

1. **Enhanced Visibility and Reach:**
   A business website allows you to reach a global audience 24/7. It serves as a digital billboard that potential customers can discover through search engines, social media, and other online channels.

2. **Credibility and Trustworthiness:**
   A professionally designed website instills confidence in your brand. It acts as a platform to showcase your products, services, testimonials, and contact information, making it easier for customers to trust your business.

3. **Marketing and Branding Platform:**
   Websites provide robust tools for marketing strategies such as SEO (Search Engine Optimization), content marketing, and online advertising. They also serve as a central hub for brand identity, reflecting your business's values, mission, and unique selling propositions.

4. **Customer Engagement and Support:**
   Interactive features like contact forms, live chat support, and FAQs enable seamless customer interaction. This enhances customer service by providing instant access to information and support.

#### Choosing Between Types of Websites

- **Static vs. Dynamic Websites:**
  - **Static Websites:** Ideal for small businesses or startups with minimal content updates. They are cost-effective and easy to deploy but may lack interactive features.
  - **Dynamic Websites:** Suitable for businesses needing frequent updates and interactive elements like e-commerce, forums, or customer portals. They offer scalability and customization but require more maintenance.

#### Conclusion

In conclusion, a business website is not just a digital placeholder but a powerful tool for growth and success. It enables businesses to expand their reach, build credibility, and engage customers effectively. Whether you choose a static or dynamic website depends on your specific needs and business goals. Embrace the digital landscape and ensure your business thrives in the competitive market by establishing a strong online presence today.
SQL Course: Get Started.
Tags: sql, learning, join, query
Published: 2024-07-01 13:27:30

---
series: Learn SQL by building a social media database.
---

Learn SQL in a funny way by building a social media database. The database will contain users, profiles, posts with likes and users will also be able to follow each other.

I will reference to w3schools.com during this series so you can learn a bit more about the theory and this series will teach you how to put it into practice.

## Setup

I am using `SQLite` for this course. If you use another database it’s fine but maybe the syntax will be slightly different. But w3schools gives examples of different syntax. 

I am also using `Replit` for this tutorial as IDE. You can easily create an account and create a new Repl with the SQLite template. That makes it easy to set up and you can also code in your browser or on your phone or IPad so you can take this tutorial on the go. 

https://replit.com/

## What we will learn

* Creating Tables with primary and foreign keys. 
* One to one relationships.
* One to many relationships.
* Many to many relationships.
* Query data.
* Inner joins, left joins and self joins and nested joins.
FRONTEND TECHNOLOGIES
Published: 2024-07-01 05:38:35


Angular vs ReactJS

When choosing a particular framework or library, JavaScript has a wide range of options for front-end development. However, Angular and React secure their places at the top of the list as many developers consider them the best front-end development frameworks due to popularity.

React is a front-end JavaScript library that allows you to build user interfaces from reusable UI components. It allows developers to create seamless UX and complex UI.

While,

Angular is an open-source JavaScript front-end framework. It has interactive UIs with data binding.

Angular JS is used to build single-page applications using HTML and TypeScript. While, React JS is commonly used to create user interfaces for single-page applications from isolated components.

Also, React offers an easy debugging process. The code is reusable. It’s easy to learn because of its easy and simple design. It allows developers to migrate an app in React very easily. It supports both Android and iOS platforms. ReactJS is view-oriented. It has faster updates with both server-side and front-end support. It supports a React Native library that offers efficient performance.

Whereas, Angular extends HTML syntax. Angular lets you create reusable components. It offers a single routing option. It has interactive UIs with data binding. Angular extends HTML syntax. With directives, Angular lets you create reusable components.

React.js is mostly used to build interactive UI components with frequently variable data, whereas Angular.js is used to build complex enterprise apps like progressive web apps and single-page apps.

I Expect having the opportunity to use my skills and ability to work in HNG, I also expect to learn new things from my colleagues and mentors.

How I feel about React? I personally don't know ReactJS, I have never used it before. But, from what I read on it and it's various advantages and popularity, I believe it's simple, it will be easy to learn and it will be fun to work with it.

https://hng.tech/internship https://hng.tech/hire
Functions
Published: 2024-07-01 13:22:42


# Functions

- #### Function Declaration
```
    function log() {
        console.log('Hello world')
    }

    log();
```

- #### Function Expression
```
    const log = function () {
        console.log('Hello world);
    }

    log();
```

- #### Arrow Function
```
    const log = () => {
        console.log('Hello world');
    }

    log()
```

```
    const num1 = +prompt('num1: ', '');
    const option = prompt('option(+;-;*;/: ', '')
    const num2 = +prompt('num2: ', '');

    function addition(num1, num2) {
        console.log(num1 + num2)
    }

    function subtraction(num1, num2) {
        console.log(num1 - num2)
    }

    function multiplication(num1, num2) {
        console.log(num1 * num2)
    }

    function division(num1, num2) {
        if (num2 === 0) {
            console.log('Error: Division by zero is not allowed');
        } else {
            console.log(num1 / num2)
        }
    }

    function result(num1, option, num2) {
        console.log(num1, option, num2)
        if(option === '+') {
            addition(num1, num2);
        }

        if(option === '-') {
            subtraction(num1, num2);
        }

        if(option === '*') {
            multiplication(num1, num2);
        }

        if(option === '/') {
            division(num1, num2);
        }

        if(option !== '+' || option !== '-' || option !== '*' || option !== '/' ) {
            alert("Mavjud bo'lmagan amal! (+;-;*;/) shularni kiriting!");
        }
    }

    result(num1, option, num2);
```

# While Loop

```
    while(condition) {
        console.log(1);
    }
```
- condition false bo'lmaguncha loop qayta qayta aylanadi

```
    let count = 0;

    while(count <= 10) {
        console.log(count);
        count++;
    }
```

# For loop
```
    for(start, condition, increment) {

    }

    for(let i = 0; i < 10; i++) {
        console.log(i)
    }
```
Linux User Creation Bash Script
Tags: devops, bash, hng11, automation
Published: 2024-07-01 13:21:08


---

## Automated User and Group Management Script

## Introduction

Managing users and groups in a Linux environment can be a tedious task, especially when dealing with a large number of users. To streamline this process, we've created a bash script named `create_users.sh` that automates user and group creation, assigns users to specified groups, sets up home directories, generates random passwords, and logs all actions.

[Github repo Link](https://github.com/stephennwachukwu/HNG_task01)

## Features

- **Automated User and Group Creation**: Creates users and personal groups.
- **Group Assignment**: Assigns users to multiple groups as specified.
- **Random Password Generation**: Generates secure random passwords for each user.
- **Logging**: Logs all actions to `/var/log/user_management.log`.
- **Secure Password Storage**: Stores passwords securely in `/var/secure/user_passwords.csv`.


## Prerequisites

- Ubuntu (or a similar Linux distribution)
- Root or sudo access

## Script Breakdown

- **Logging**: The script logs all actions with timestamps to `/var/log/user_management.log` using the `log_action` function.
- **User and Group Creation**: 
  - The script reads the input file line by line.
  - Each line is split into a username and groups.
  - Personal groups (with the same name as the username) are created if they don't already exist.
  - Users are created if they don't already exist and are added to their respective groups.
- **Password Generation and Storage**:
  - The script generates a random password for each user using `openssl rand`.
  - Passwords are set for each user and stored securely in `/var/secure/user_passwords.csv` with appropriate permissions.

## Conclusion

This script simplifies the process of managing users and groups on a Linux system, making it efficient and error-free. It is particularly useful for large environments where user and group management is a frequent task.

For more information about the HNG Internship and opportunities it offers, please visit the [HNG Internship page](https://hng.tech/internship) and learn about the [premium services](https://hng.tech/premium) provided.

---
Analyzing Bus Accident Hotspots in Phoenix
Published: 2024-07-01 13:20:44

Downtown Phoenix
`Downtown Phoenix is a high-traffic area` with a dense network of streets and intersections, making it a common hotspot for bus accidents. The heavy concentration of vehicles, pedestrians, and cyclists increases the likelihood of collisions. The complexity of navigating crowded urban streets and frequent stops and turns creates challenging conditions for bus drivers.

Efforts to improve safety in downtown Phoenix include enhanced[ traffic signal systems, designated bus lanes, and increased](

1. url
) law enforcement presence. These measures aim to reduce congestion and minimize the risk of accidents, ensuring a safer environment for all road users.

Interstate 10 (I-10) Corridor
The I-10 corridor is one of the busiest highways in Phoenix, serving as a major route for local and long-distance traffic. High speeds, heavy traffic volume, and frequent lane changes significantly contribute to the risk of bus accidents in this area. Additionally, construction zones along the I-10 can further complicate driving conditions, increasing the likelihood of accidents.

To mitigate these risks, authorities have implemented speed limits, enhanced signage, and improved road infrastructure. These measures are designed to manage traffic flow and reduce accident risks. However, the dynamic nature of traffic patterns requires ongoing attention and adaptation.


Continuous monitoring and adjustments are essential to maintain safety on the I-10 corridor. Authorities need to regularly evaluate the effectiveness of current measures and make necessary changes to address emerging issues.

Central Avenue
Central Avenue is a major thoroughfare in Phoenix, known for its heavy traffic and numerous intersections. Buses navigating this busy street face challenges such as sudden stops, frequent lane changes, and interactions with pedestrians and cyclists. The high traffic volume and complex road layout make Central Avenue a hotspot for bus accidents.

Safety improvements on Central Avenue focus on better traffic signal coordination, dedicated bus lanes, and public awareness campaigns to educate road users about safe practices. These initiatives aim to enhance the safety and efficiency of bus travel along this critical route.

Roosevelt Street
Roosevelt Street, located in a lively area of Phoenix, is a common site for bus accidents. The street is heavily trafficked due to the presence of schools, businesses, and residential areas, leading to frequent pedestrian crossings. Bus drivers must navigate these busy sections, often with unexpected stops and distractions.

Efforts to improve safety on Roosevelt Street include the installation of pedestrian crosswalks, improved street lighting, and increased law enforcement patrols. These measures aim to create a safer environment for bus passengers and pedestrians.

```

```
How to make your website have Drag and Drop Files
Tags: react, webdev, typescript, javascript
Published: 2024-07-01 13:20:20

Have you had seen an application in your computer where you need to upload a file? And instead of clicking it you just open your folder and drag and drop it in the place and i suddenly accepts it?

And now that you are a making your project you want to implement it but how? 

## **This is How to do it:**


**Making the input** 
When making an input make sure to have label in it, Because the label is the one who are gonna be seen and we are gonna hide the input in this tutorial


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x900hbpd7r52e2ge767.jpg)

Make sure that the input has a hidden as a prop if you want the labels to be used and now show the inputs

**Design The Label**
if you want to have some sort of design then you can go design the label or even the input if it does not contain hidden in your code

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jkyfyjdosnfxb8bb9vth.jpg)

this is my design and yes im bad at designing LOL

**Lets Make the necessary function**

- handleFileChange - This is Responsible for the onChange Event of the files even though its hidden. this is what you will use as default without drag and drop.
- handleDrop - This is Responsible for the drop files by the users.
- handleDragOver -This is Responsible for preventing the default behaviour of the web when you drop files in the input.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jtf930tjw8tnnjhrh591.jpg)

This 3 function is necessary for handling the file input of the user whether they use click and just pick the files or Drag and Drop. 

**Lets now use the function in label and input**

Label
   - onDragOver and Will use handleDragOver function
   - onDrop and will use the handleDrop function

Input
   - onChange and will use handleFileChange function

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uw2yf0rjvbzx202va5z9.jpg)
  Now The code is finish isn't it easy?

**Conclusion**
   You probably see this kind of features in most application as it is now requirement for application because of how easy it is to implement and also how it can make your website more user friendly this features is great it is both easy and necessary for all web application that will handle file and also photos.

I hope you learn something new and i hope this article helps you
Analyzing Bus Accident Hotspots in Phoenix
Published: 2024-07-01 13:05:55

``Downtown Phoenix
` <a href="https://www.axios.com/local/phoenix/2023/08/25/study-downtown-phoenix-foot-traffic-pandemic">Downtown Phoenix is a high-traffic area</a>
with a dense network of streets and intersections, making it a common hotspot for bus accidents. The heavy concentration of vehicles, pedestrians, and cyclists increases the likelihood of collisions. The complexity of navigating crowded urban streets and frequent stops and turns creates challenging conditions for bus drivers.

Efforts to improve safety in downtown Phoenix include enhanced[ traffic signal systems, designated bus lanes, and increased](

1. url
) law enforcement presence. These measures aim to reduce congestion and minimize the risk of accidents, ensuring a safer environment for all road users.

Interstate 10 (I-10) Corridor
The I-10 corridor is one of the busiest highways in Phoenix, serving as a major route for local and long-distance traffic. High speeds, heavy traffic volume, and frequent lane changes significantly contribute to the risk of bus accidents in this area. Additionally, construction zones along the I-10 can further complicate driving conditions, increasing the likelihood of accidents.

To mitigate these risks, authorities have implemented speed limits, enhanced signage, and improved road infrastructure. These measures are designed to manage traffic flow and reduce accident risks. However, the dynamic nature of traffic patterns requires ongoing attention and adaptation.


Continuous monitoring and adjustments are essential to maintain safety on the I-10 corridor. Authorities need to regularly evaluate the effectiveness of current measures and make necessary changes to address emerging issues.

Central Avenue
Central Avenue is a major thoroughfare in Phoenix, known for its heavy traffic and numerous intersections. Buses navigating this busy street face challenges such as sudden stops, frequent lane changes, and interactions with pedestrians and cyclists. The high traffic volume and complex road layout make Central Avenue a hotspot for bus accidents.

Safety improvements on Central Avenue focus on better traffic signal coordination, dedicated bus lanes, and public awareness campaigns to educate road users about safe practices. These initiatives aim to enhance the safety and efficiency of bus travel along this critical route.

Roosevelt Street
Roosevelt Street, located in a lively area of Phoenix, is a common site for bus accidents. The street is heavily trafficked due to the presence of schools, businesses, and residential areas, leading to frequent pedestrian crossings. Bus drivers must navigate these busy sections, often with unexpected stops and distractions.

Efforts to improve safety on Roosevelt Street include the installation of pedestrian crosswalks, improved street lighting, and increased law enforcement patrols. These measures aim to create a safer environment for bus passengers and pedestrians.

```

```