menu

Search By Label

Imagine a busy restaurant. A Denial-of-Service (DoS) attack is like someone calling in a ton of fake orders overwhelming the kitchen. The real customers can't get their food because the kitchen is stuck dealing with the fakes.

In the computer world, DoS attacks try to overwhelm a website or online service with fake traffic, like those fake orders. This overload prevents real users from accessing the service. It's like the restaurant being too busy with the fakes to serve real customers.

DoS attacks are usually temporary, but they can be disruptive and costly.

In 2008, Leonard Richardson proposed the following maturity model for web APIs:
  • Level 0: Define one URI, and all operations are POST requests to this URI.
  • Level 1: Create separate URIs for individual resources.
  • Level 2: Use HTTP methods to define operations on resources.
  • Level 3: Use hypermedia (HATEOAS, described below).

Level 3 corresponds to a truly RESTful API according to Fielding's definition. In practice, many published web APIs fall somewhere around level 2.

We use pass in Python functions as a placeholder for empty code.
It basically tells Python to do nothing in that specific spot. It's useful for:

  • Marking incomplete functions: When you're defining a function but haven't written its logic yet, pass prevents errors.
  • Skipping code sections: Within a function, pass can be used to intentionally skip a block of code if a certain condition isn't met.
In IPython 7.3 and later, there is a magic %pip and %conda command that will run in the current kernel.

%pip install geocoder

In earlier versions, you need to use sys to fix the problem like in the answer by FlyingZebra1

import sys
!{sys.executable} -m pip install geocoder
To get a value and the index of this element into an array is useful this method, for example:

[11,22,31,224,44].each_with_index { |val,index| puts "index: #{index} for #{val}" if val < 30}
  index: 0 for 11
  index: 1 for 22
  => [11, 22, 31, 224, 44]
What is a JSON Web Token?

A JSON Web Token is an internet standard defined by the Internet Engineering Task Force (IETF) as a: "compact, URL-safe means of representing claims to be transferred between two parties" so, go ahead with the configuration.

Build the Rails app:
rails new jwt_rails_api --api


Add the gems:
gem 'jwt', '~> 2.7'
gem "bcrypt", "~> 3.1.7"

Generate User and Product Models
rails g model User username:string password:string
rails g model Product name:string description:text

After running our migration with rails db:migrate, our setup with models is complete, and our schema, found in db/schema.rb, should now look similar to this:

ActiveRecord::Schema[7.0].define(version: 2024_03_26_224534) do
  create_table "products", force: :cascade do |t|
    t.string "name"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string "username"
    t.string "password_digest"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
end


Build a jwt Gem Wrapper

Our wrapper class is found in app/lib/json_web_token.rb and looks like this:

class JsonWebToken
  JWT_SECRET = Rails.application.secrets.secret_key_base

  def self.encode(payload, exp = 12.hours.from_now)
    payload[:exp] = exp.to_i

    JWT.encode(payload, JWT_SECRET)
  end

  def self.decode(token)
    body = JWT.decode(token, JWT_SECRET)[0]

    HashWithIndifferentAccess.new(body)
  end
end

At this point, you can already test this class in your Rails console:

data = {"name"=>"Juanequex"}

JsonWebToken.encode(data)
# => "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiQXBwU2lnbmFsIiwiZXhwIjoxNjg1NDI0MjI5fQ.zWJyFHH8Pa6phBOU99XgtRntyfZQSOTX4TdwOxFY9gY"

JsonWebToken.decode(JsonWebToken.encode(data))
# => {"name"=>"Juanequex", "exp"=>1685424262}


Back to the User Model
Now will be a good time to visit our User model at app/models/user.rb. All we need to do here is add the has_secure_password class method:

class User < ApplicationRecord
  has_secure_password
end

Creating a Sample User and Product in Rails is possible through the Rails console or configuring your seeds.
User.create(username: "juanequex", password: "password")
Product.create(name: "Rad Ruby", description: "A book collection of Ruby tips")



Using JWTs in Rails Controllers

 A good place to start is the ApplicationController at app/controllers/application_controller.rb:

class ApplicationController < ActionController::API
  before_action :authenticate

  rescue_from JWT::VerificationError, with: :invalid_token
  rescue_from JWT::DecodeError, with: :decode_error

  private

  def authenticate
    authorization_header = request.headers['Authorization']
    token = authorization_header.split(" ").last if authorization_header
    decoded_token = JsonWebToken.decode(token)

    User.find(decoded_token[:user_id])
  end

  def invalid_token
    render json: { invalid_token: 'invalid token' }
  end

  def decode_error
    render json: { decode_error: 'decode error' }
  end
end

Next, we need an AuthenticationController to which users can send requests and get a signed JSON Web Token from our server. This controller should be placed at app/controllers/authentication_controller.rb and may look like this:

class AuthenticationController < ApplicationController
  skip_before_action :authenticate

  def login
    user = User.find_by(username: params[:username])
    authenticated_user = user&.authenticate(params[:password])

    if authenticated_user
      token = JsonWebToken.encode(user_id: user.id)
      expires_at = JsonWebToken.decode(token)[:exp]

      render json: { token:, expires_at: }, status: :ok
    else
      render json: { error: 'unauthorized' }, status: :unauthorized
    end
  end
end


Testing Our Ruby Application with a Protected Resource
Let's create a controller with rails g controller Product index so we have something like:
class ProductsController < ApplicationController
  before_action :authenticate

  def index
    @products = Product.all

    render json: @products
  end
end

Of course, we need a route to access these controllers. Our config/routes.rb should look something like:
Rails.application.routes.draw do
  post 'login', to: "authentication#login"
  get 'products', to: "products#index"
end


Let's try getting a JWT with a user that doesn't exist:
curl -H "Content-Type: application/json" -X POST -d '{"username":"manny","password":"password"}' http://localhost:3000/login


We should get the following response:
{"error":"unauthorized"}


Now try the same with a user that we created earlier:
curl -H "Content-Type: application/json" -X POST -d '{"username":"juanequex","password":"password"}' http://localhost:3000/login


This should give us a signed JSON web token that could look like this:
{"token":"eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE2ODU0NTEyMTR9.1UEYAbmFOSF93yp9pJqNEzkdHr3rVqutPNZWRIPDYkY","expires_at":1685432077}

Let's keep this token for a second and try accessing a product resource with a bad token (I changed a random character in the token):
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE2ODU0NTEyMTR9.1UEYAbmFOSF93yp9pJqNEzkdHr3rVqutPNZWRIPZYkY" http://localhost:3000/products

output:
{"decode_error":"decode error"}



However, if we make the same request to access the product resource with the valid token we got from the server previously, We're granted access to the product resource:

[{"id":1,"name":"Rad Ruby","description":"A book collection of Ruby tips","created_at":"2024-03-26T19:33:30.826Z","updated_at":"2024-03-26T19:33:30.826Z"}]

That's it! We've successfully secured our Ruby application with a JSON web token!
Rails 7 fresh apps ships with Turbo to speed up your application while dramatically reducing the amount of JavaScript that you will need to write.

Turbo lets your server deliver HTML directly as an alternative to the prevailing front-end frameworks that reduce the server side of your Rails application to little more than a JSON API.

Turbo has our back and has a built-in replacement for the browser's default progress bar, and we can style it to meet our application's design system!

set this style:
// app/assets/stylesheets/components/_turbo_progress_bar.scss

.turbo-progress-bar {
  background: linear-gradient(to right, var(--color-primary), var(--color-primary-rotate));
}

// app/assets/stylesheets/application.sass.scss

// All the previous code
@import "components/turbo_progress_bar";

debug step:
# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Add this line to see the progress bar long enough
  # and remove it when it has the expected styles
  before_action -> { sleep 1 } # this is only to debug the progress bar, it can be removed.
You can adjust output from this with the --progress option:
  --progress string         Set type of progress output (auto, plain, tty). Use plain to show container output
                            (default "auto")

Adding --progress=plain will show the output of the run commands that were not loaded from the cache. This can also be done by setting the BUILDKIT_PROGRESS 

variable:
export BUILDKIT_PROGRESS=plain


If you are debugging a build, and the steps have already been cached, add --no-cache to your build to rerun the steps and redisplay the output:
docker build --progress=plain --no-cache ...


If you don't want to use buildkit, you can revert to the older build engine by exporting DOCKER_BUILDKIT=0 in your shell, e.g.:
DOCKER_BUILDKIT=0 docker build ...


or
export DOCKER_BUILDKIT=0
docker build ...


Source: https://stackoverflow.com/questions/64804749/why-is-docker-build-not-showing-any-output-from-commands
It seems that what you actually expect from the numbers is:
8.9 > 8.10 and this is true with the decimal numbers, but when talking about the version of a software this is not true because each number after the dot have individual meaning resulting that the version 8.9 < 8.10 
You can use the sed command in the terminal to replace all occurrences of any Regex in specific files.

Here's the command:
sed -i '' 's/@import/@use/g' *.scss

Running this command in the terminal you will replace all occurrences of @import with @use in your .scss
The WebpackBar plugin provides an improved progress bar and displays file names in real time.

image.png 30.7 KB

Implementation:
const WebpackBar = require('webpackbar');

module.exports = {
    // Otras configuraciones...
    plugins: [
        new WebpackBar()
    ]
};

You can get more information about the progress of your Webpack bundle by adding the flag --progress

Example:
npx webpack --config ./webpack.config.core.js --progress
To see the current version of any package installed in your project from the console, you can use the following npm command:

npm list webpack

This command will display the version of the package installed locally in your project along with its dependencies.
Look for the package entry in the output to see the version number.
In Ruby on Rails, the find_or_initialize_by method is a convenient way to find a record in a database based on certain conditions and, if not found, initialize a new instance of the model with those conditions set.

# Example usage
@user = User.find_or_initialize_by(email: 'example@example.com')

It's the process of organizing data in a relational database to reduce redundancy and improve data integrity.

Importance:
  • Minimize Redundancy: Eliminate duplicate data, reducing storage space.
  • Avoid Update Anomalies: Prevent inconsistencies when updating data.
  • Simplify Queries: Simplify data retrieval and improve query performance.
  • Enhance Data Integrity: Ensure accurate and consistent data.