Blog

  • ask

    .ask

    Overview

    .ask is an anonymous question-asking platform similar to NGL, designed to be self-hosted for maximum control and privacy. It leverages Cloudflare’s network for fast and reliable performance, ensuring that your platform is always accessible. With a focus on security and user control, .ask allows you to manage your data independently. Its intuitive interface makes it simple to ask and answer questions anonymously, making it an ideal solution for both personal and community use.

    Features

    • Anonymous Questions: Users can ask questions anonymously without revealing their identity.
    • Self-Hosted: Complete control over your data and privacy by hosting the platform yourself.
    • Cloudflare Integration: Utilizes Cloudflare’s network for fast and reliable performance.
    • Intuitive Interface: Easy-to-use interface for asking and answering questions.
    • Social Share Ready: Answered will be generated into socialmedia shareable card which you can directly share right from the app.
    • Security Focused: Ensures data security with JWT authentication.
    • Customizable: Customize the platform to fit your needs
    • Community Friendly: Ideal for both personal use and community engagement.
    • Open Source: Contributions are welcome, and the project is licensed under GPL 3.0.

    Deploy

    Requirements

    1. Login to cloudflare, create a worker project named ask-api and create another pages project named ask-web

    2. Generate a Cloudflare api token following this link: https://link.shovon.me/wrangler-token

    3. Crate an account on NeonDB and get the connection string. Follow this guide if needed: https://link.shovon.me/neon-string

    4. Create a JWT secret from here (length 32): https://link.shovon.me/gen-jwt or run this in terminal node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

    Deploy With GitHub Actions

    1. Create a new repo using this template

    2. Goto the repo Settings -> Secrets and variables -> Actions. On Repository secrets section add these secrets

    Name Value Requirement
    CLOUDFLARE_API_TOKEN Token generated from requirements step 2 Required
    NEON_DATABASE_URL DB URL string from requirements step 3 Required
    JWT_SECRET JWT secret from requirements step 4 Required
    DEFAULT_USER Default username for login Required
    DEFAULT_PASSWORD Default password for login Required
    API_CUSTOM_DOMAIN Custom domain for ask api Optional

    1. Goto the Actions tab on the repo, select Deploy API and Web action, select Run workflow, branch main, Run workflow

    Manual Deployment

    1. Clone this repo locally and run pnpm install

    2. Open apps/api/wrangler.toml, if you are going to use a custom domain for the short link, uncomment line 4 and replace {{CUSTOM_DOMAIN}} with your custom domain.

    3. Create a .env file in apps/api/ and fill in NEON_DATABASE_URL, DEFAULT_USER and DEFAULT_PASSWORD

    4. Put the Neon database string on worker secret using: pnpm db:set

    5. Put the JWT secret on worker using: pnpm jwt:secret:set

    6. Run pnpm worker:deploy:api to deploy the api

    7. Create a .env file in apps/web/ and fill in NEXT_PUBLIC_WORKER with the custom domain or the worker url got from previous command

    8. Run pnpm pages:deploy:web to deploy the web client

    Contributing

    We welcome contributions! Please follow these steps:

    1. Fork the repository.
    2. Create a new branch:
    git checkout -b feature-branch
    1. Make your changes and commit them:
    git commit -m "Description of changes"
    1. Push to the branch:
    git push origin feature-branch
    1. Create a pull request.

    License

    This project is licensed under the GPL 3.0 License. See the COPYING file for details.

    Contact

    For any questions or feedback, please open an issue

    Visit original content creator repository
    https://github.com/ajshovon/ask

  • ENCM509-Labs

    ENCM 509 – Fundamentals of Biometric Systems Design Labs

    Python Jupyter NumPy Matplotlib SciPy Pandas scikit-learn TensorFlow

    Lab 1

    Introduction to libraries such as NumPy, Matplotlib, and SciPy

    Lab 2

    The purpose of this lab is to utilize statistical analysis to distinguish between “genuine” and “imposter” written signatures. Before applying statistical analysis, we will be collecting written signatures using the Wacom Intuos tablet. We’ll use this tablet to capture coordinate and pressure values at 200 points/sec as the pen moves across the tablet. The tablet is also capable of recognizing 1024 levels of pressure which will be especially useful in statistical analysis later on. In addition, we’ll also utilize the software SigGet to collect and convert the data to CSV files collected by the tablet. Throughout the lab we will utilize these CSV file samples to plot histograms, 2D and 3D colormaps, as well as normal distributions of both velocity and pressure and the calculation of both mean $(\mu)$ and standard deviation $(\sigma)$ in order to understand and compare trends in the distribution/dispersion of the data between both “genuine” and “imposter” written signatures to see how they differ.

    Lab 3

    The purpose of this lab is to understand biometric-based verification between genuine and imposter signatures for 1:1 matching. In the previous lab, we utilized values such as pressure, time, and coordinates, however, in this lab, we will separate the data into 2 simple classes and train the data based on the EM algorithm. After training the data, we will also utilize the Gaussian Mixture Model (GMM) to calculate log-likelihood scores in order to distinguish the classes of genuine and imposter signatures, essentially “verifying” if the signature is genuine or not. In addition, we will also use the log-likelihood score to calculate both the mean $(\mu)$ and standard deviation $(\sigma)$ of both the imposter and genuine scores in order to plot normal distributions, illustrating how they vary with one another.

    Lab 4

    In this lab we will be focusing on image pre-processing and feature extraction of fingerprints. We will be collecting fingerprints using the Digital Persona UareU 4500, and because the quality of data is affected by many factors, we will collect both good and bad quality fingerprints for analysis. Throughout the lab we will conduct a number of image processing techniques such as normalization and segmentation as well as pre-processing and de-noising techniques such as contrast enhancement (histogram equalization) and the Wiener filter. After applying these processing techniques, we will then calculate the number of Minutiae (ridge endings and bifurcations) and Singularities (points of cores, deltas) in order to assess their impact on the image details of the fingerprints.

    Lab 5

    In this lab we will be focusing on image processing and fingerprint matching. We will be using fingerprints collected by using the Digital Persona UareU 4500. We will be focusing on two main matching algorithms, matching based on Minutiae count (ridge ending and bifurcation), and matching based on scores obtained by Gabor filtering. In addition, we will also change the parameters of Gabor filtering such as the angle and frequency in order to see if it has a visual impact on the processed fingerprint image. Lastly, after running both types of matching algorithms, we will also select thresholds in order to see their impact on the number of true positive matches and false negative matches.

    Lab 6

    In this lab, we will explore facial recognition via Principal Component Analysis (PCA), using the AT&T Database of Faces. Employing Python and Jupyter Notebook, our focus will be on face detection, image processing, and classification through PCA feature extraction and Euclidean Distance matching. We will adjust PCA parameters to study their impact on facial representation and experiment with threshold settings to analyze their effects on true positive and false negative match rates. This practical approach aims to deepen our understanding of biometric verification within facial recognition, blending theoretical concepts with hands-on experience.

    Lab 7

    In this lab, we will undertake the task of hand gesture recognition using data collected by the Ultra Leap developed by Leap Motion. After the data is collected, we will be utilizing deep learning in order to regonize different hand gestures. More specifically, we will utilize a classifier, Long Short-term Memory (LSTM) which is a deep learning model for time-series analysis. Throughout the lab, we will prepare our data, preprocess it, create our model, and performing classification while also changing specific parameters before classification such as the testing set size, number of LSTM layers, and the dropout probability in order to see their effects on accuracy, etc.

    Lab 8

    In this lab, we explore Bayesian Networks (BNs) for machine reasoning using PyAgrum. We’ll construct BNs that mimic real scenarios, like the Diamond Princess infection outbreak. The lab involves setting up network structures and conditional probability tables (CPTs). We’ll perform inference to understand how factors like age and gender influence susceptibility. Exercises in Jupyter Notebook will guide us through these processes. By manipulating BNs, insights into probabilistic decision-making will be gained. We aim to show BNs as a robust framework for reasoning under uncertainty. This practical approach will enhance our comprehension of BNs’ applications. Ultimately, we’ll learn to make informed decisions based on probabilistic models.

    Visit original content creator repository https://github.com/MushtabaA/ENCM509-Labs
  • beresin-express-backend-app

    Hoppscotch
    # beresin-express-backend-app

    Backend of BeresIn

    This is an Express.js project, written in TypeScript, with a PostgreSQL database using Knex.js for query building.

    The project provides a backend for the BeresIn platform, featuring user authentication, admin and user services management, and category CRUD operations, with a focus on secure data handling and a well-structured API.

    Authors

    Meet Beresin Team

    Product Owner:

    UI/UX Design:

    • Danny Kurniawan
    • Azmi Nadhia Asyarifa

    Fullstack Website:

    Frontend Mobile:

    Tech Stack

    • Programming Language / Superset: Typescript
    • Runtime Environment: Node.js
    • Framework: Express
    • Query Builder: Knex
    • RDBMS: PostgreSQL
    • Authentication / Authorization: JWT ### Installation Guide for beresindev-beresin-express-backend-app

    Step 1: Clone the Project

    # Clone the repository from GitHub
    git clone https://github.com/beresindev/beresindev-beresin-express-backend-app.git
    
    # Change into the project directory
    cd beresindev-beresin-express-backend-app

    Step 2: Install Dependencies

    # Install all required npm packages
    npm install
    # or
    yarn install
    # or
    pnpm install
    # or
    bun install

    Step 3: Configure Environment Variables

    1. Copy the example environment file to create a local environment file:

      cp .env.local.example .env.local
    2. Update the .env.local file with your specific configuration:

    DB_NAME=TOBEMODIFIED
    DB_HOST=TOBEMODIFIED
    DB_PORT=TOBEMODIFIED
    DB_USER=TOBEMODIFIED
    DB_PASSWORD=TOBEMODIFIED
    PORT=TOBEMODIFIED
    
    JWT_SECRET=TOBEMODIFIED

    Step 4: Knex Migrations

    Rollback Migrations (Optional if you need to reset):

    npx knex migrate:rollback --specific 20241101145250_create_category_services_table.ts
    npx knex migrate:rollback --specific 20241101145251_create_service_table.ts

    Run Migrations:

    npx knex migrate:up 20241101074044_create_users_table.ts --knexfile knexfile.ts
    npx knex migrate:up 20241101145250_create_category_services_table.ts --knexfile knexfile.ts
    npx knex migrate:up 20241101145223_create_service_table.ts --knexfile knexfile.ts
    npx knex migrate:up 20241101145304_create_sub_category_table.ts --knexfile knexfile.ts

    Step 5: Seed Database

    # Populate the database with an admin user
    npx knex seed:run --specific=create_admin_user.ts

    Step 6: Start the Application

    # Start the Express server
    npm start
    # Access the API at http://localhost:3000

    This guide provides full setup instructions for the backend application using Express, JWT for authentication, Knex for database migrations, and PostgreSQL as the database. Ensure PostgreSQL is configured and running.## Deployment

    To deploy this project run

    1. Copy .env.example into .env

    cp .env.example .env

    2. Generate JWT_SECRET

    openssl rand -base64 32

    Output must be like this: 3y9KcY0Dl1KzT9frFyM7hO0NBWwO3F5yPiB3uF9xUho=

    3. Update src/index.ts for production

    import dotenv from 'dotenv';
    import app from './app';
    
    dotenv.config({ path: '.env' });
    
    const PORT = parseInt(process.env.PORT || '3000', 10); // Konversi PORT ke number
    const HOST = '0.0.0.0'; // Dengarkan di semua alamat IP agar dapat diakses secara publik
    
    app.listen(PORT, HOST, () => {
    	console.log(`Server running on http://${HOST}:${PORT}`);
    });

    4. add in package.json

    "scripts": {
        "start": "node dist/index.js"
    }

    5. Rename Configuration ecosystem.config.js.example into ecosystem.config.js

    The ecosystem.config.js file is used with PM2 (a process manager for Node.js applications) to manage and automate various aspects of running your application in production. Then fill as needed.

    module.exports = {
      apps: [
        {
          name: "beresin-express-backend-app",
          script: "dist/index.js",
          env: {
            DB_HOST: "TOBEMODIFIED",
            DB_USER: "TOBEMODIFIED",
            DB_PASSWORD: "TOBEMODIFIED",
            DB_NAME: "TOBEMODIFIED",
            DB_PORT: TOBEMODIFIED,
            PORT: TOBEMODIFIED,
          },
          env_production: {
            NODE_ENV: "production"
          }
        }
      ]
    };

    6. Install dependencies for production

    To run Node.js applications (including compiled TypeScript applications) on a VPS continuously, you can use PM2, which is designed to run Node.js applications in production mode, keeping them running even after a server crash or restart. Here are the complete steps:

    7. Install PM2

    npm install -g pm2

    8. Compile the application to JavaScript first:

    npx tsc

    9. using TypeScript and the entry point file is directly in src/index.js, run:

    pm2 start dist/index.js --name "my-app"

    10. To ensure the application continues running after a VPS restart, enable the PM2 startup feature:

    pm2 startup

    API Reference

    0. Miscellaneous

    Endpoint: GET /profile

    Parameter Type Description
    None No parameters required

    Health check to verify database connection, size, latency, and errors.

    Example Response:

    {
      "status": "success",
      "message": "Database connected successfully",
      "database": {
        "ready": true,
        "size": "9329 kB",
        "latency": "31 ms"
      }
    }

    1. Authentication

    Endpoint: POST /v1/auth/login

    Parameter Type Description
    email string Required. User’s email
    password string Required. User’s password

    Example Request Body:

    {
      "email": "firstadmin@mail.com",
      "password": "Admin123,"
    }

    Example Response:

    {
      "status": "success",
      "message": "Login successful",
      "token": "your_jwt_token",
      "user": {
        "id": 1,
        "username": "admin",
        "email": "firstadmin@mail.com",
        "role": "admin"
      }
    }

    Endpoint: POST /v1/auth/register

    Parameter Type Description
    username string Required. User’s username
    name string Required. User’s full name
    email string Required. User’s email
    phone string Required. User’s phone
    password string Required. User’s password

    Example Request Body:

    {
      "username": "testuser2",
      "name": "Test User 2",
      "email": "testuser2@example.com",
      "phone": "123456789",
      "password": "testpassword"
    }

    Example Response:

    {
      "status": "success",
      "message": "User registered successfully",
      "token": "your_jwt_token",
      "user": {
        "id": 3,
        "username": "testuser2",
        "name": "Test User 2",
        "email": "testuser2@example.com",
        "phone": "123456789",
        "role": "User",
        "created_at": "2024-11-02T18:49:15.231Z",
        "updated_at": "2024-11-02T18:49:15.231Z"
      }
    }

    2. Admin

    Endpoint: GET /v1/admin/services

    Displays all services regardless of status (accept, pending, decline).

    Parameter Type Description
    api_key string Required. Admin API key

    Example Response:

    {
      {
        "id": 1,
        "created_at": "2024-11-06T05:20:14.398Z",
        "updated_at": "2024-11-06T05:20:14.398Z",
        "user_id": 2,
        "isSubscription": false,
        "name_of_service": "Title_4",
        "category_id": 3,
        "description": "Desc_4",
        "status": "pending",
        "images": [
          "services/uploads/images/1730873116083-new_logo_beresin.png",
          "services/uploads/images/1730873116084-old_logo_beresin.png"
        ] 
      ]
    }

    Endpoint: PATCH /v1/admin/services/:id/status

    Parameter Type Description
    api_key string Required. Admin API key
    status string Required. Status: accept, decline, or pending

    Example Request Body:

    {
      "status": "accept"
    }

    Example Response:

    {
      "status": "success",
      "service": {
        "id": 1,
        "created_at": "2024-11-01T18:36:42.777Z",
        "updated_at": "2024-11-01T18:36:42.777Z",
        "user_id": 2,
        "isSubscription": true,
        "name_of_service": "Jasa Design",
        "category_id": 1,
        "description": "Jasa design web dan aplikasi",
        "status": "accept"
      }
    }

    Endpoint: DELETE /v1/admin/services/:id

    Parameter Type Description
    api_key string Required. Admin API key

    Example Response:

    {
      "status": "success",
      "message": "Service deleted successfully"
    }

    Endpoint: GET /v1/admin/category

    Parameter Type Description
    api_key string Required. Admin API key

    Example Response:

    {
      "status": "success",
      "category": [
        {
          "id": 1,
          "name_of_category": "Technology"
        },
        {
          "id": 2,
          "name_of_category": "Household"
        },
        {
          "id": 3,
          "name_of_category": "Uncategories"
        }
      ]
    }

    Endpoint: POST /v1/admin/category

    Parameter Type Description
    api_key string Required. Admin API key
    name_of_category string Required. Category name

    Example Request Body:

    {
      "name_of_category": "Technology"
    }

    Example Response:

    {
      "status": "success",
      "category": {
        "id": 1,
        "name_of_category": "Technology"
      }
    }

    Endpoint: PUT /v1/admin/category/:id

    Parameter Type Description
    api_key string Required. Admin API key
    name_of_category string Required. New category name

    Example Request Body:

    {
      "name_of_category": "Uncategories"
    }

    Example Response:

    {
      "status": "success",
      "category": {
        "id": 3,
        "name_of_category": "Uncategories"
      }
    }

    Endpoint: DELETE /v1/admin/category/:id

    Parameter Type Description
    api_key string Required. Admin API key

    Example Response:

    {
      "status": "success",
      "message": "Category deleted successfully"
    }

    Endpoint: GET /admin/users

    Parameter Type Description
    Bearer string Required. Admin JWT

    Retrieves a list of all users.

    Example Response:

    {
      "status": "success",
      "users": [
        {
          "id": 1,
          "created_at": "2024-11-01T17:39:05.344Z",
          "updated_at": "2024-11-01T17:39:05.344Z",
          "username": "admin",
          "name": "Administrator",
          "email": "firstadmin@mail.com",
          "phone": "6285156644103",
          "password": "$2b$10$VecX3hAWsU/PrHIneJkmOuCe145VdQ1pqnnNqemJq/xpu9PE2N6vu",
          "role": "admin"
        },
        {
          "id": 2,
          "created_at": "2024-11-01T17:51:43.312Z",
          "updated_at": "2024-11-07T09:06:18.308Z",
          "username": "testuser",
          "name": "Test User",
          "email": "testuser@mail.com",
          "phone": "081235595153",
          "password": "$2b$10$sL/dFpk.K2qI6Ep88g3AtuSiBqNHAwe45Jh.eqOMnSn3gTcVZ/216",
          "role": "User"
        }
      ]
    }

    Endpoint: POST /admin/users

    Parameter Type Description
    Bearer string Required. Admin JWT
    username string Required. Username
    name string Required. Full name
    email string Required. Email
    phone string Required. Phone
    password string Required. Password
    role string Required. User role

    Example Request Body:

    {
      "username": "newuser",
      "name": "New User",
      "email": "newuser@example.com",
      "phone": "1234567890",
      "password": "password123",
      "role": "User"
    }

    Example Response:

    {
      "status": "success",
      "message": "User created successfully",
      "user": {
        "id": 9,
        "created_at": "2024-11-07T17:29:40.276Z",
        "updated_at": "2024-11-07T17:29:40.276Z",
        "username": "newuser",
        "name": "New User",
        "email": "newuser@example.com",
        "phone": "1234567890",
        "password": "$2b$10$Pauozt5F6Tp.Xqn5jwRkieIj4DCiXAV2tXLZFIISGgHYrBI4bVRJW",
        "role": "User"
      }
    }

    Endpoint: PUT /admin/users/:id

    Parameter Type Description
    Bearer string Required. Admin JWT
    username string Required. New username
    name string Required. New name
    email string Required. New email
    phone string Required. New phone
    password string Required. New password
    role string Required. New role

    Example Request Body:

    {
      "username": "testuser3",
      "name": "Test User 3",
      "email": "testuser3@mail.com",
      "phone": "08123345445789",
      "password": "testpassword",
      "role": "User"
    }

    Example Response:

    {
      "status": "success",
      "message": "User updated successfully",
      "user": {
        "id": 9,
        "created_at": "2024-11-07T17:29:40.276Z",
        "updated_at": "2024-11-07T17:31:25.751Z",
        "username": "testuser3",
        "name": "Test User 3",
        "email": "testuser3@mail.com",
        "phone": "08123345445789",
        "password": "$2b$10$tWFd84.ayz7YAjQJAW1BJu3tppdBnoLvrpzIntEQeUrnTrLeq/W3O",
        "role": "User"
      }
    }

    Endpoint: DELETE /admin/users/:id

    Parameter Type Description
    Bearer string Required. Admin JWT

    Deletes a user and their related data.

    Example Response:

    {
      "status": "success",
      "message": "User 'Test User 3' and related services and images deleted successfully"
    }

    3. User

    Endpoint: GET /user/profile

    Parameter Type Description
    Bearer string Required. User JWT

    Retrieves profile information of the authenticated user.

    Example Response:

    {
      "status": "success",
      "message": "User profile retrieved successfully",
      "user": {
        "id": 6,
        "username": "seconduser",
        "name": "Second User",
        "email": "second@example.com",
        "phone": "086289789612",
        "role": "User",
        "created_at": "2024-11-07T09:11:15.577Z",
        "updated_at": "2024-11-07T09:11:15.577Z"
      }
    }

    Endpoint: DELETE /user/deleteAccount

    Parameter Type Description
    Bearer string Required. User JWT

    Deletes the user account and all related data.

    Example Response:

    {
      "status": "success",
      "message": "Account and all related content deleted successfully"
    }

    Endpoint: GET /v1/user/services

    Parameter Type Description
    api_key string Required. User API key

    Returns all services belonging to the authenticated user, unique to each user.

    Example Response:

    {
      "status": "success",
      "services": [
        {
          "id": 1,
          "created_at": "2024-11-01T18:36:42.777Z",
          "updated_at": "2024-11-01T18:36:42.777Z",
          "user_id": 2,
          "isSubscription": true,
          "name_of_service": "Jasa Design",
          "category_id": 1,
          "description": "Jasa design web dan aplikasi",
          "status": "accept",
          "images": [
            "services/uploads/images/1730568201772-WhatsApp Image 2024-11-02 at 17.58.44.jpeg",
            "services/uploads/images/1730568201773-ttd-halim.png"
          ]
        }
      ]
    }

    Endpoint: POST /user/services

    Parameter Type Description
    Bearer string Required. User JWT
    name_of_service string Required. Name of the service
    category_id integer Required. ID of the category
    description string Required. Description of the service
    images String Required. Images of the service

    Note: This endpoint requires multipart/form-data for file upload. The images field accepts up to 2 image files.

    Example Request Body:

    {
      "name_of_service": "Jasa Mengajar Next.js",
      "category_id": 3,
      "description": "Mengajar Coding dari Javascript dasar, Typescript, hingga React.Js",
      "images": ["Background.png", "BeresIn Flow.png"]
    }

    Example Response:

    {
      "status": "success",
      "service": {
        "id": 11,
        "created_at": "2024-11-04T09:44:53.352Z",
        "updated_at": "2024-11-04T09:44:53.352Z",
        "user_id": 2,
        "isSubscription": false,
        "name_of_service": "Jasa Mengajar Next.js",
        "category_id": 3,
        "description": "Mengajar Coding dari Javascript dasar, Typescript, hingga React.Js",
        "status": "pending",
        "images": [
          {
            "id": 13,
            "image": "services/uploads/images/1730713493349-Background.png",
            "service_id": 11
          },
          {
            "id": 14,
            "image": "services/uploads/images/1730713493349-BeresIn Flow.png",
            "service_id": 11
          }
        ]
      }
    }

    Endpoint: PUT /user/services/:id

    Parameter Type Description
    Bearer string Required. User JWT
    name_of_service string Required. Name of the service
    category_id integer Required. ID of the category
    description string Required. Description of the service
    images String Optional. Updated images of the service

    Note: This endpoint also requires multipart/form-data for file upload. The images field accepts up to 2 image files.

    Example Request Body:

    {
      "name_of_service": "Jasa Perbaikan Laptop",
      "category_id": 1,
      "description": "Service and repair for laptops, including software and hardware issues",
      "images": ["laptop-repair1.png", "laptop-repair2.png"]
    }

    Example Response:

    {
      "status": "success",
      "service": {
        "id": 2,
        "created_at": "2024-11-02T19:19:18.752Z",
        "updated_at": "2024-11-07T19:19:18.752Z",
        "user_id": 3,
        "isSubscription": true,
        "name_of_service": "Jasa Perbaikan Laptop",
        "category_id": 1,
        "description": "Service and repair for laptops, including software and hardware issues",
        "status": "accept",
        "images": [
          {
            "id": 15,
            "image": "services/uploads/images/1730713493349-laptop-repair1.png",
            "service_id": 2
          },
          {
            "id": 16,
            "image": "services/uploads/images/1730713493349-laptop-repair2.png",
            "service_id": 2
          }
        ]
      }
    }

    Endpoint: DELETE /user/services/:id

    Parameter Type Description
    Bearer string Required. User JWT

    Deletes a specified service belonging to the authenticated user.

    Example Response:

    {
      "status": "success",
      "message": "Service deleted successfully"
    }

    Endpoint: GET /user/category

    Parameter Type Description
    api_key string Required. User API key

    Example Response:

    {
      "status": "success",
      "category": [
        {
          "id": 1,
          "name_of_category": "Technology"
        },
        {
          "id": 2,
          "name_of_category": "Household"
        },
        {
          "id": 3,
          "name_of_category": "Uncategories"
        }
      ]
    }

    4. Public

    Endpoint: GET /services/all

    Only services with status: accept are displayed.

    Parameter Type Description
    None No parameters required

    Example Response:

    {
      "status": "success",
      "services": [
        {
          "id": 1,
          "created_at": "2024-11-01T18:36:42.777Z",
          "updated_at": "2024-11-01T18:36:42.777Z",
          "user_id": 2,
          "isSubscription": true,
          "name_of_service": "Jasa Design",
          "category_id": 1,
          "description": "Jasa design web dan aplikasi",
          "status": "accept",
          "images": [
            "services/uploads/images/1730568201772-WhatsApp Image 2024-11-02 at 17.58.44.jpeg",
            "services/uploads/images/1730568201773-ttd-halim.png"
          ],
          "phone": "081235595153"
        }
      ]
    }

    Endpoint: GET /category

    Parameter Type Description
    None No parameters required

    Example Response:

    {
      "status": "success",
      "category": [
        {
          "id": 1,
          "name_of_category": "Technology"
        },
        {
          "id": 2,
          "name_of_category": "Household"
        },
        {
          "id": 3,
          "name_of_category": "Uncategories"
        }
      ]
    }

    Used By

    This project is used by the following companies:

    Support

    For support, email teambersin@gmail.com.

    Visit original content creator repository https://github.com/beresindev/beresin-express-backend-app
  • decsetter

    Decorator @property setter

    tests Coverage Status

    Setting DecoratorProperty as the metaclass adds a @decorator_property decorator to the body of the function. decorator_property behaves just like python’s builtin property, but it provides an additional interface for interacting with the property via a decorator.

    Usage

    A typical usage is for setting properties of instances which are also functions. Here is a minimal working example:

    from decsetter import DecoratorProperty
    
    class ClassWithFunctions(metaclass=DecoratorProperty):
        def __init__(self):
            self._function_foo = None
    
        @decorator_property
        def function_foo(self):
            return self._function_foo
    
        @function_foo.setter(decorator=True)
        def function_foo(self, value):
            self._function_foo = value
    
    # Instantiate the class
    cwf = ClassWithFunctions()
    
    # Set cwf.function_foo to `my_function`
    # with normal @property this would not work
    @cwf.function_foo
    def my_function(x):
        print("hello from my_function")
        return x ** 2
    
    print(cwf.function_foo(4))

    You can also use the @<function_name>.decor decorator to specify your own decorator callback. This way you can add side-effects to the decorator (you could even make it not set the value but do something completely different). In this case the decorator prints "hello from decor" at decoration time.

    ...
    
    @function_foo.setter
    def function_foo(self, value):
        self._function_foo = value
    
    @function_foo.decor
    def function_foo(self):
        def decor(fun):
            print("hello from decor")
            self._function_foo = fun
            return fun
        return decor
    
    ...

    Note that, similarly to decorators with arguments, the function decorated with @function_foo.decor has to return the decorator. The internal property _function_foo is set by reference to the instance of the class encapsulated in the closure of decor.

    The decorator does not have to be a setter. In the following example the decorator of an integer property incr decorates the function to run incr number of times while incrementing its input.

    from decsetter import DecoratorProperty
    from functools import wraps
    
    class FunctionRepeater(metaclass=DecoratorProperty):
        """Decorator of property 'incr' runs the wrapped function n times"""
    
        def __init__(self, incr=1):
            self._incr = incr
    
        @decorator_property
        def incr(self):
            return self._incr
    
        @incr.setter
        def incr(self, value):
            self._incr = value
    
        @incr.decor
        def incr(self):
            def outer_wrapper(fun):
                @wraps(fun)
                def inner_wrapper(x, **kwargs):
                    return tuple(fun(x + i, **kwargs) for i in range(self._incr))
    
                return inner_wrapper
    
            return outer_wrapper

    It can be used as follows:

    repeat = FunctionRepeater(3)
    
    @repeat.incr
    def square(x):
        return x ** 2
    
    square(1) # -> (1, 4, 9)
    square(3) # -> (9, 16, 25)

    The decorated square keeps a reference to instance of FunctionRepeater such that if the value of

    repeat.incr = 5
    square(3) # -> (9, 16, 25, 36, 49)

    Sharp corners

    This of course doesn’t work since cwf is not initialised at the time of decoration.

    ...
    @cwf.function_foo
    def my_function(x):
        print("hello from my_function")
        return x ** 2
    
    # ^ Throws NameError: name 'cwf' is not defined
    
    cwf = ClassWithFunctions()

    If you want to define your function before instantiating the class, just use normal way of setting properties:

    def my_function(x):
        print("hello from my_function")
        return x ** 2
    
    cwf = ClassWithFunctions()
    cwf.function_foo = my_function
    cwf.function_foo(1)

    Dev

    Run coverage locally:

    coverage run --omit="test_*.py" -m pytest && coverage html && open htmlcov/index.html 
    
    Visit original content creator repository https://github.com/MarcinKonowalczyk/decsetter
  • tensorflow-lstm-sin

    TensorFlow LSTM sin(t) Example

    Single- and multilayer LSTM networks with no additional output nonlinearity based on aymericdamien’s TensorFlow examples and Sequence prediction using recurrent neural networks.

    Experiments with varying numbers of hidden units, LSTM cells and techniques like gradient clipping were conducted using static_rnn and dynamic_rnn. All networks have been optimized using Adam on the MSE loss function.

    Experiment 1

    Given a single LSTM cell with 100 hidden states, predict the next 50 timesteps given the last 100 timesteps.

    The network is trained on a sine of 1 Hz only using random shifts, thus fails on generalizing to higher frequencies (2 Hz and 3 Hz in the image); in addition, the network should be able to simply memoize the shape of the input. It was optimized with a learning rate of 0.001 for 200000 iterations and batches of 50 examples.

    Experiment 2

    Given a single LSTM cell with 150 hidden states, predict the next 50 timesteps given the last 100 timesteps.

    The network is trained on sines of random frequencies between 0.5 .. 4 Hz using random shifts. Prediction quality is worse than for the 1 Hz only experiment above, but it generalizes to the 2 Hz and 3 Hz tests. It was optimized with a learning rate of 0.001 for 300000 iterations and batches of 50 examples.

    At loss 0.614914, the prediction looks like this:

    Experiment 3

    Given a single LSTM cell with 150 hidden states, predict the next 50 timesteps given the last 25 timesteps.

    The network is trained on sines of random frequencies between 0.5 Hz and 4 Hz using random shifts. Prediction quality is worse than for the 1 Hz only experiment above, but it generalizes to the 2 Hz and 3 Hz tests. It was optimized with a learning rate of 0.0005 for 500000 iterations and batches of 50 examples.

    The following image shows the output at loss 0.177742:

    The following is the network trained to predict the next 100 timesteps given the previous 25 timesteps; the parameters are otherwise unchanged.

    This is the result at loss 0.257725:

    Experiment 4

    Same as the last experiment, however using 500 hidden states and gradient clipping for the optimizer as described here:

    adam = tf.train.AdamOptimizer(learning_rate=learning_rate)
    gradients = adam.compute_gradients(loss)
    clipped_gradients = [(tf.clip_by_value(grad, -0.5, 0.5), var) for grad, var in gradients]
    optimizer = adam.apply_gradients(clipped_gradients)

    Losses get as low as 0.069027 within the given iterations, but vary wildly. This is at loss 0.422188:

    Experiment 5

    This time, the dynamic_rnn() function is used instead of rnn(), drastically improving the startup time. In addition, the single LSTM cell has been replaced with 4 stacked LSTM cells of 32 hidden states each.

    lstm_cells = [rnn.LSTMCell(n_hidden, forget_bias=1.0) 
                  for _ in range(n_layers)]
    stacked_lstm = rnn.MultiRNNCell(lstm_cells)
    outputs, states = tf.nn.dynamic_rnn(stacked_lstm, x, dtype=tf.float32, time_major=False)

    The output still uses linear regression:

    output = tf.transpose(outputs, [1, 0, 2])
    pred = tf.matmul(output[-1], weights['out']) + biases['out']

    The network is trained with learning rate 0.001 for at least 300000 iterations (with the additional criterion that the loss should be below 0.15).

    The following picture shows the performance at loss 0.138701 at iteration 375000.

    When using only 10 hidden states, training takes much longer given a learning rate of 0.001 and reaches a loss of about 0.5 after ~1200000 iterations, where convergence effectively stops.

    The following used 10 hidden states and a base learning rate of 0.005 in combination with a step policy that reduced the learning rate by a factor of 0.1 every 250000 iterations. Similar to the previous experiment, optimization was stopped after at least 300000 iterations have passed and the loss was below 0.2.

    The picture shows the outcome after 510000 iterations at a loss of 0.180995:

    Experiment 6

    Much like the last experiment, this one uses 10 hidden states per layer in a 4 layer deep recurrent structure. Instead of using LSTM layers, however, this one uses GRUs.

    Because the loss did not go below 0.3, training was stopped after 1000000 iterations.

    Visit original content creator repository https://github.com/sunsided/tensorflow-lstm-sin
  • Benchmark_script_for_VPS

    VPS Benchmark Tool Collection

    This document summarizes commonly used VPS performance testing scripts, covering CPU, disk, network, stress testing, and more. Works on Linux systems like Ubuntu/Debian/CentOS.

    CPU Benchmark script for VPS

    Execute benchmark testing automatically and show detailed results online. Powered by Geekbench.
    Works on Linux like Ubuntu, centOS, debian and etc.
    Best for testing VPS, cloud server…

    How to run

    In the command line, paste the following and enter.

    curl -L -o gk5.sh https://rebrand.ly/gk5 && bash gk5.sh
    

    How long will the test cost?

    Depends on CPU, around 1~5 minutes

    Sample results

    Geekbench 5 Test Items

    Single-Core & Multi-Core: AES-XTS, Text Compression, Image Compression, Navigation, HTML5, SQLite, PDF Rendering, Text Rendering, Machine Learning

    Network Speedtest for VPS

    Originally from https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py

    How to run

    In the command line, paste the following and enter.

    curl -L https://rebrand.ly/speed-cli | python3 -
    

    Output:

    Retrieving speedtest.net configuration...
    Retrieving speedtest.net server list...
    Testing from Comcast Cable (x.x.x.x)...
    Selecting best server based on ping...
    Hosted by FiberCloud, Inc (Seattle, WA) [12.03 km]: 44.028 ms
    Testing download speed........................................
    Download: 32.29 Mbit/s
    Testing upload speed..........................................
    Upload: 5.18 Mbit/s
    

    🧰 Other Famous Benchmark & Testing Tools


    🔧 General Benchmark Scripts

    LemonBench – Comprehensive Benchmark Script

    Supports CPU, memory, disk, network, and system information testing.

    curl -fsL https://ilemonra.in/LemonBenchIntl | bash -s fast

    SuperBench – Optimized for China Network

    Suitable for testing speed from mainland China, disk I/O, and basic performance.

    bash <(curl -Lso- https://git.io/superbench)

    YABS (Yet Another Benchmark Script) – Minimalist Style

    Quickly tests disk I/O, Geekbench scores, and network bandwidth.

    curl -sL yabs.sh | bash

    🌐 Network Performance Tools

    Speedtest CLI – Official CLI Tool

    Global speed test tool providing upload, download, and latency stats.

    sudo apt-get install curl
    curl -s https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh | sudo bash
    sudo apt-get install speedtest

    🧠 CPU / Memory Stress Tools

    stress-ng – CPU, Memory, and I/O Stress Test

    Allows configurable stress types and duration for stability testing.

    sudo apt install -y stress-ng
    stress-ng --cpu 4 --io 2 --vm 2 --timeout 60s

    💽 Disk I/O Test Tools

    fio – Comprehensive Disk Benchmark Tool

    Supports read/write modes, I/O depth, concurrency, and more.

    sudo apt install -y fio
    fio --name=test --size=1G --filename=testfile --bs=4k --rw=randrw --ioengine=libaio --iodepth=64 --runtime=60 --numjobs=4 --group_reporting

    🛰️ Visual Traceroute Tools

    BestTrace – Visual Traceroute Utility

    Supports IP geolocation and is ideal for analyzing international routing paths.

    wget https://cdn.ipip.net/17mon/besttrace4linux.zip
    unzip besttrace4linux.zip
    chmod +x besttrace
    ./besttrace -q 1 <ip-address>

    🎮 GPU Stress Test (Web-based)

    Web-based GPU stress test using WebGL, no installation needed.
    Open your browser and visit: https://cznull.github.io/vsbm

    Visit original content creator repository https://github.com/mikeyang01/Benchmark_script_for_VPS
  • Benchmark_script_for_VPS

    VPS Benchmark Tool Collection

    This document summarizes commonly used VPS performance testing scripts, covering CPU, disk, network, stress testing, and more. Works on Linux systems like Ubuntu/Debian/CentOS.

    CPU Benchmark script for VPS

    Execute benchmark testing automatically and show detailed results online. Powered by Geekbench.
    Works on Linux like Ubuntu, centOS, debian and etc.
    Best for testing VPS, cloud server…

    How to run

    In the command line, paste the following and enter.

    curl -L -o gk5.sh https://rebrand.ly/gk5 && bash gk5.sh
    

    How long will the test cost?

    Depends on CPU, around 1~5 minutes

    Sample results

    Geekbench 5 Test Items

    Single-Core & Multi-Core: AES-XTS, Text Compression, Image Compression, Navigation, HTML5, SQLite, PDF Rendering, Text Rendering, Machine Learning

    Network Speedtest for VPS

    Originally from https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py

    How to run

    In the command line, paste the following and enter.

    curl -L https://rebrand.ly/speed-cli | python3 -
    

    Output:

    Retrieving speedtest.net configuration...
    Retrieving speedtest.net server list...
    Testing from Comcast Cable (x.x.x.x)...
    Selecting best server based on ping...
    Hosted by FiberCloud, Inc (Seattle, WA) [12.03 km]: 44.028 ms
    Testing download speed........................................
    Download: 32.29 Mbit/s
    Testing upload speed..........................................
    Upload: 5.18 Mbit/s
    

    🧰 Other Famous Benchmark & Testing Tools


    🔧 General Benchmark Scripts

    LemonBench – Comprehensive Benchmark Script

    Supports CPU, memory, disk, network, and system information testing.

    curl -fsL https://ilemonra.in/LemonBenchIntl | bash -s fast

    SuperBench – Optimized for China Network

    Suitable for testing speed from mainland China, disk I/O, and basic performance.

    bash <(curl -Lso- https://git.io/superbench)

    YABS (Yet Another Benchmark Script) – Minimalist Style

    Quickly tests disk I/O, Geekbench scores, and network bandwidth.

    curl -sL yabs.sh | bash

    🌐 Network Performance Tools

    Speedtest CLI – Official CLI Tool

    Global speed test tool providing upload, download, and latency stats.

    sudo apt-get install curl
    curl -s https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh | sudo bash
    sudo apt-get install speedtest

    🧠 CPU / Memory Stress Tools

    stress-ng – CPU, Memory, and I/O Stress Test

    Allows configurable stress types and duration for stability testing.

    sudo apt install -y stress-ng
    stress-ng --cpu 4 --io 2 --vm 2 --timeout 60s

    💽 Disk I/O Test Tools

    fio – Comprehensive Disk Benchmark Tool

    Supports read/write modes, I/O depth, concurrency, and more.

    sudo apt install -y fio
    fio --name=test --size=1G --filename=testfile --bs=4k --rw=randrw --ioengine=libaio --iodepth=64 --runtime=60 --numjobs=4 --group_reporting

    🛰️ Visual Traceroute Tools

    BestTrace – Visual Traceroute Utility

    Supports IP geolocation and is ideal for analyzing international routing paths.

    wget https://cdn.ipip.net/17mon/besttrace4linux.zip
    unzip besttrace4linux.zip
    chmod +x besttrace
    ./besttrace -q 1 <ip-address>

    🎮 GPU Stress Test (Web-based)

    Web-based GPU stress test using WebGL, no installation needed.
    Open your browser and visit: https://cznull.github.io/vsbm

    Visit original content creator repository https://github.com/mikeyang01/Benchmark_script_for_VPS
  • Timepicker

    Grudus Timepicker

    npm downloads dependencies dev dependencies license

    Material design timepicker written in Javascript (without any external dependencies – no jQuery, no Bootstrap, only one file!) See https://grudus.github.io/Timepicker/ for more usage!

    How it looks?

    By default picker uses blue-white theme:

    Normal


    But you can change its colors by overriding some of default configuration:
    defaultConfig = {
        headerBackground: "#1976D2",
        headerColor: "#c7d6e1",
        headerSelected: "#ffffff",
        wrapperBackground: "#f0fff0",
        footerBackground: "#f0fff0",
        submitColor: "#1976D2",
        cancelColor: "#1976D2",
        clockBackground: "#CFD8DC",
        clockItemColor: "#212121",
        clockItemInnerColor: "#212121",
        handColor: "#1976D2"
    };

    How custom theme can look:

    brave


    But you can also create more user-friendly view – create your own dark theme:

    dark


    How to get it?

    You can include all in single html file! Just add

    <head>
      <link href="https://rawgit.com/grudus/Timepicker/master/dist/index.css" type="text/css" rel="stylesheet">
    </head>
    <body>
      <button onclick="Timepicker.showPicker()">Show picker</button>
    </body>
    <script type="text/javascript" src="https://rawgit.com/grudus/Timepicker/master/dist/grudus-timepicker.es5.js"></script>

    Or, you can download it from npm

    npm install --save grudus-timepicker

    Then, include index.css into your project (e.g. add <link href="https://github.com/grudus/node_modules/grudus-timepicker/dist/index.css" rel="stylesheet" type="text/css"> into your html file)

    And lastly, somewhere in your code put

    import Timepicker from "path/to/grudus-timepicker/dist/grudus-timepicker.js";
    
    // ...
    
     Timepicker.showPicker({
                time: new Date(),
                onSubmit: (time) => {
                    //some action ...
                },
                headerColor: "#ff0000"       
                // more color configuration ...
            })

    You can set initial time by passing time field in argument. time may be a Date object, an object {hours: 12, minutes: 44} or a string in format HH:mm. If you want to learn more, visit customization section

    Visit original content creator repository https://github.com/grudus/Timepicker
  • nspawn

    nspawn

    Package Version Python Versions

    Containers with systemd-nspawn

    Features:

    Install

    To install python package:

    sudo pip install nspawn
    

    Build Script

    To build an image, provide and invoke executable build.py script, for example:

    For available build options run ./build.py --help

    Setup Script

    To setup a machine, provide and invoke executable setup.py script, for example:

    For available setup options run ./setup.py --help

    Machine Service

    To review provisioned, generated and running machine service, run:

    machinectl
    systemctl status <machine>
    cat /etc/systemd/system/<machine>.service
    

    for example, demo generated services:

    Machine Resources

    Location of machine files and folders:

    /etc/systemd/system/<machine>.service
    /var/lib/machines/<machine>
    /var/lib/nspawn/runtime/<machine>
    

    Machine Management

    To interact with live machine:

    • for machines registered with machinectl
    • for machines with systemd init, such as archlinux
    # start interactive shell:
    sudo machinectl shell <machine> 
    
    # invoke command with args:
    sudo machinectl shell <machine> /bin/command arg1 arg2 ... 
    
    • for machines not registered with machinectl
    • for machines without systemd init, such as alpine linux
    # start interactive shell:
    ./setup.py --action=nsenter 
    
    • alternatively, use package-provided nspawn-enter command:
    # start interactive shell:
    nspawn-enter <machine> 
    
    # invoke command with args:
    nspawn-enter <machine> "command arg1 arg2 ..." 
    

    Configuration

    Available configuration options are described in config.ini file.

    Use config/path_list option to control configuration override file list.

    Image Server

    Package comes with provisioning command nspawn-hatch which can build and setup local http/https image server.

    # review available services:
    nspawn-hatch list
    
    # provision image server service:
    nspawn-hatch update image-server
    
    # verify image server machine status:
    machinectl
    

    Image server settings:

    Image syncer settings (replicate to Amazon AWS S3):

    Build DSL

    Build DSL is used in build.py, is activated by from nspawn.build import * and provides keywords:

        'TOOL',
        'IMAGE',
        'PULL',
        'EXEC',
        'WITH',
        'FETCH',
        'COPY',
        'CAST',
        'RUN',
        'SH',
        'PUSH',
    

    Setup DSL

    Setup DSL is used in setup.py, is activated by from nspawn.setup import * and provides keywords:

        'TOOL',
        'IMAGE',
        'MACHINE',
        'WITH',
        'EXEC',
        'COPY',
        'CAST',
        'RUN',
        'SH',
    

    DSL Syntax

    TOOL

    Expose build/setup utility functions:

    TOOL.<function>(...)
    

    IMAGE()

    Declare image identity:

    IMAGE("http://host/path/package.tar.gz")
    IMAGE(url="http://host/path/package.tar.gz")
    

    PULL()

    Provision dependency image:

    PULL("http://host/path/package.tar.gz")
    PULL(url="http://host/path/package.tar.gz")
    

    EXEC()

    Declare image entry point executable i.e. COMMAND [ARGS...]:

    EXEC(['/usr/bin/env', 'sh', '-c', 'echo "hello-kitty"'])
    EXEC(command=['/usr/bin/env', 'sh', '-c', 'echo "hello-kitty"'])
    

    WITH()

    Customize machine features using nspawn container settings:

    WITH(
        SettingName1='setting 1 value a',
        SettingName2='setting 2 value b',
        ...,
    )
    

    COPY()

    Copy local resources:

    • when used in build.py: target is in the image
    • when used in setup.py: target is on the host
    COPY("/etc")
    COPY(path="/etc")
    COPY(source="/root/input.md", target="/root/output.md")
    

    CAST()

    Template local resources:

    • when used in build.py: target is in the image
    • when used in setup.py: target is on the host
    CAST("/root/readme.md", variable="template varialbe", ...)
    CAST(path="/root/readme.md", variable="template varialbe", ...)
    CAST(source="/root/input.md", target="/root/output.md", variable="template varialbe", ...)
    

    Template uses python/jinja format, i.e:

    this template variable will be substituted: {{variable}}
    

    FETCH()

    Download and extract remote resource:

    FETCH( # use when source and target are the same
       url="http://server/package.tar.gz", # url for remote resource
       path="/common-path", # path inside the package source and image target
    )
    FETCH( # use when source and target are different
       url="http://server/package.tar.gz", # url for remote resource
       source="/package-path", # path inside the package extract
       target="/opt/resource", # path inside the build image target
    )
    

    RUN()

    Invoke command, with target depending on the context:

    • when used in build.py: invoke inside the image
    • when used in setup.py: invoke on the host
    RUN(['/usr/bin/env', 'ls', '-las'])
    RUN(command=['/usr/bin/env', 'ls', '-las'])
    

    SH()

    Invoke shell script, with target depending on the context:

    • when used in build.py: invoke inside the image
    • when used in setup.py: invoke on the host
    SH("ls -las")
    SH(script="ls -las")
    

    Note:

    • SH(script) is equivalent to RUN(command=['/usr/bin/env', 'sh', '-c', script])

    PUSH()

    Publish image result to the declared url:

    PUSH()
    

    MACHINE()

    Declare machine service:

    MACHINE('machine-name')
    MACHINE(name='machine-name')
    MACHINE(name='machine-name', template='/path/to/service/template/machine.service')
    

    Provide inline service unit changes:

    MACHINE(
        name='machine-name',
        # extra entries for [Unit] section
        unit_conf=[
            "Description=hello-world",  # override description
        ],
        # extra entries for [Service] section
        service_conf=[
            "CPUQuota=10%",  # throttle processor usage
        ],
        # extra entries for [Install] section
        install_conf=[
            "WantedBy=machines.target",  # inject unit dependency
        ],
    )
    

    Design custom service templates based on package-provided defaults, for example:

    Visit original content creator repository https://github.com/random-python/nspawn
  • jwe

    JWE

    Build Status Code Climate Test Coverage

    A ruby implementation of the RFC 7516 JSON Web Encryption (JWE) standard.

    Installing

    gem install jwe

    Usage

    This example uses the default alg and enc methods (RSA-OAEP and A128CBC-HS256). It requires an RSA key.

    require 'jwe'
    
    key = OpenSSL::PKey::RSA.generate(2048)
    payload = "The quick brown fox jumps over the lazy dog."
    
    encrypted = JWE.encrypt(payload, key)
    puts encrypted
    
    plaintext = JWE.decrypt(encrypted, key)
    puts plaintext #"The quick brown fox jumps over the lazy dog."

    This example uses a custom enc method:

    require 'jwe'
    
    key = OpenSSL::PKey::RSA.generate(2048)
    payload = "The quick brown fox jumps over the lazy dog."
    
    encrypted = JWE.encrypt(payload, key, enc: 'A192GCM')
    puts encrypted
    
    plaintext = JWE.decrypt(encrypted, key)
    puts plaintext #"The quick brown fox jumps over the lazy dog."

    This example uses the ‘dir’ alg method. It requires an encryption key of the correct size for the enc method

    require 'jwe'
    
    key = SecureRandom.random_bytes(32)
    payload = "The quick brown fox jumps over the lazy dog."
    
    encrypted = JWE.encrypt(payload, key, alg: 'dir')
    puts encrypted
    
    plaintext = JWE.decrypt(encrypted, key)
    puts plaintext #"The quick brown fox jumps over the lazy dog."

    This example uses the DEFLATE algorithm on the plaintext to reduce the result size.

    require 'jwe'
    
    key = OpenSSL::PKey::RSA.generate(2048)
    payload = "The quick brown fox jumps over the lazy dog."
    
    encrypted = JWE.encrypt(payload, key, zip: 'DEF')
    puts encrypted
    
    plaintext = JWE.decrypt(encrypted, key)
    puts plaintext #"The quick brown fox jumps over the lazy dog."

    This example sets an extra plaintext custom header.

    require 'jwe'
    
    key = OpenSSL::PKey::RSA.generate(2048)
    payload = "The quick brown fox jumps over the lazy dog."
    
    # In this case we add a copyright line to the headers (it can be anything you like
    # just remember it is plaintext).
    encrypted = JWE.encrypt(payload, key, copyright: 'This is my stuff! All rights reserved')
    puts encrypted

    Available Algorithms

    The RFC 7518 JSON Web Algorithms (JWA) spec defines the algorithms for encryption and key management to be supported by a JWE implementation.

    Only a subset of these algorithms is implemented in this gem. Striked elements are not available:

    Key management:

    • RSA1_5
    • RSA-OAEP (default)
    • RSA-OAEP-256
    • A128KW
    • A192KW
    • A256KW
    • dir
    • ECDH-ES
    • ECDH-ES+A128KW
    • ECDH-ES+A192KW
    • ECDH-ES+A256KW
    • A128GCMKW
    • A192GCMKW
    • A256GCMKW
    • PBES2-HS256+A128KW
    • PBES2-HS384+A192KW
    • PBES2-HS512+A256KW

    Encryption:

    • A128CBC-HS256 (default)
    • A192CBC-HS384
    • A256CBC-HS512
    • A128GCM
    • A192GCM
    • A256GCM

    License

    The MIT License

    • Copyright © 2016 Francesco Boffa

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    Visit original content creator repository https://github.com/RubyOnWorld/jwe