server

package
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

README

SureSQL Backend

SureSQL is a robust SQL database abstraction service that provides a RESTful API for accessing and manipulating SQL databases. It's designed to be a secure, reliable, and easy-to-use interface for applications that need to interact with SQL databases.

Table of Contents

Architecture Overview

SureSQL acts as a middleware layer between client applications and the underlying SQL database system. The current implementation supports RQLite as the database backend, with potential for future support of additional database systems.

Key components:

  • RESTful API server with JWT-based authentication
  • Connection pooling for improved performance
  • Middleware for security and logging
  • ORM (Object-Relational Mapping) for simplified data operations

Features

  • Secure Authentication: API key and token-based authentication
  • Connection Pooling: Efficient management of database connections
  • Parameterized Queries: Protection against SQL injection
  • Token Refresh: Support for token refresh to maintain session validity
  • Detailed Logging: Comprehensive logging of all operations
  • Database Status: Get information about the database status and node configuration
  • Structured Response Format: Consistent response structure for all API calls

Configuration

SureSQL is configured via environment files:

  • .env.dev - Development configuration
  • .env.simplehttp - Server configuration

The main configuration options, this is used to connect to the DBMS include:

  • DB_HOST, DB_PORT: Database server connection details
  • DB_USERNAME, DB_PASSWORD: Database credentials
  • DB_SSL: Whether to use SSL for database connections
  • DB_API_KEY, DB_CLIENT_ID: API key and client ID for authentication
  • DB_CONSISTENCY: Consistency level for distributed database operations
  • DB_OPTIONS: Options for the DBMS
  • DB_HTTP_TIMEOUT, DB_RETRY_TIMEOUT, DB_MAX_RETRIES: Connection parameters

Information regarding SureSQL service that will be returned to the client is in the DB itself. These settings are also in the environment:

  • SURESQL_HOST, SURESQL_PORT: SureSQL server connection details
  • SURESQL_IP: SureSQL server IP (which are not used at this moment)
  • SURESQL_SSL: Whether to use SSL for database connections (always true)
  • SURESQL_DBMS: The DBMS used by SureSQL (default is RQLite) Currently the environment takes the precedence, especially if the settings in DB table value is empty. Some of the boolean settings definitely overwritten by environment variables.

Authentication

SureSQL uses a two-level authentication system:

  1. API Key Authentication: Every request must include the API key and client ID in the headers
  2. Token Authentication: After initial authentication, operations use a token-based system

The API key and client ID must be included in the headers for all requests:

API_KEY: your-api-key
CLIENT_ID: your-client-id

For authenticated endpoints, the token must be included in the Authorization header:

Authorization: Bearer your-token

API Endpoints

Authentication and Connection
POST /db/connect

Authenticates a user and creates a new database connection.

Request Body:

{
  "username": "your-username",
  "password": "your-password"
}

Response:

{
  "status": 200,
  "message": "Authentication successful",
  "data": {
    "token": "your-auth-token",
    "refresh_token": "your-refresh-token",
    "token_expired_at": "2023-01-01T12:00:00Z",
    "refresh_expired_at": "2023-01-02T12:00:00Z",
    "user_id": "1"
  }
}
POST /db/refresh

Refreshes an authentication token.

Request Body:

{
  "refresh": "your-refresh-token"
}

Response:

{
  "status": 200,
  "message": "Token refreshed successfully",
  "data": {
    "token": "your-new-auth-token",
    "refresh_token": "your-new-refresh-token",
    "token_expired_at": "2023-01-01T12:00:00Z",
    "refresh_expired_at": "2023-01-02T12:00:00Z",
    "user_id": "1"
  }
}
Database Operations

All database operation endpoints require a valid authentication token.

POST /db/api/sql

Executes one or more SQL statements.

Request Body:

{
  "statements": ["SQL statement 1", "SQL statement 2"],
  "param_sql": [
    {
      "query": "INSERT INTO table (column1, column2) VALUES (?, ?)",
      "values": ["value1", 2]
    }
  ]
}

Response:

{
  "status": 200,
  "message": "SQL executed successfully",
  "data": {
    "results": [
      {
        "error": null,
        "timing": 0.005,
        "rows_affected": 1,
        "last_insert_id": 123
      }
    ],
    "execution_time": 0.005,
    "rows_affected": 1
  }
}
POST /db/api/query

Queries data from a table with optional conditions.

Request Body:

{
  "table": "users",
  "condition": {
    "field": "age",
    "operator": ">",
    "value": 18,
    "order_by": ["name ASC"],
    "limit": 10
  },
  "single_row": false
}

Response:

{
  "status": 200,
  "message": "Query executed successfully",
  "data": {
    "records": [
      {
        "table_name": "users",
        "data": {
          "id": 1,
          "name": "John Doe",
          "age": 30
        }
      }
    ],
    "execution_time": 0.003,
    "count": 1
  }
}
POST /db/api/querysql

Executes SQL queries and returns the results.

Request Body:

{
  "statements": ["SELECT * FROM users WHERE age > 18"],
  "param_sql": [
    {
      "query": "SELECT * FROM users WHERE age > ?",
      "values": [18]
    }
  ],
  "single_row": false
}

Response:

{
  "status": 200,
  "message": "SQL executed successfully",
  "data": [
    {
      "records": [
        {
          "table_name": "users",
          "data": {
            "id": 1,
            "name": "John Doe",
            "age": 30
          }
        }
      ],
      "execution_time": 0.003,
      "count": 1
    }
  ]
}
POST /db/api/insert

Inserts one or more records into the database.

Request Body:

{
  "records": [
    {
      "table_name": "users",
      "data": {
        "name": "Jane Smith",
        "age": 25
      }
    }
  ],
  "queue": false,
  "same_table": true
}

Response:

{
  "status": 200,
  "message": "Successfully inserted 1 records",
  "data": {
    "results": [
      {
        "error": null,
        "timing": 0.004,
        "rows_affected": 1,
        "last_insert_id": 124
      }
    ],
    "execution_time": 0.004,
    "rows_affected": 1
  }
}
GET /db/api/status

Retrieves the status of the database connection.

Response:

{
  "status": 200,
  "message": "Status peers vs config matched",
  "data": {
    "url": "http://localhost:4001",
    "version": "0.0.1",
    "dbms": "rqlite",
    "dbms_driver": "direct-rqlite",
    "start_time": "2023-01-01T00:00:00Z",
    "uptime": "24h0m0s",
    "dir_size": 1024,
    "db_size": 2048,
    "node_id": "1",
    "is_leader": true,
    "leader": "http://localhost:4001",
    "mode": "rw",
    "nodes": 1,
    "node_number": 1,
    "max_pool": 25,
    "peers": {
      "1": {
        "url": "http://localhost:4001",
        "is_leader": true,
        "mode": "rw",
        "nodes": 1,
        "node_number": 1
      }
    }
  }
}
POST /db/api/getschema

Retrieves the database schema information.

Response:

{
  "status": 200,
  "message": "Schema get successfully",
  "data": [
    {
      "type": "table",
      "name": "users",
      "tbl_name": "users",
      "rootpage": 2,
      "sql": "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
      "hidden": false
    }
  ]
}

Usage Examples

Connect to the Database
const response = await fetch('http://your-suresql-server/db/connect', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id'
  },
  body: JSON.stringify({
    username: 'your-username',
    password: 'your-password'
  })
});

const data = await response.json();
const token = data.data.token;
// Save token for subsequent requests
Refresh Token
const response = await fetch('http://your-suresql-server/db/refresh', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id'
  },
  body: JSON.stringify({
    refresh: 'your-refresh-token'
  })
});

const data = await response.json();
const newToken = data.data.token;
// Update the saved token
Execute SQL Statements

Basic example with a single SQL statement:

const response = await fetch('http://your-suresql-server/db/api/sql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    statements: ["CREATE TABLE if not exists test (id INTEGER PRIMARY KEY, value TEXT)"]
  })
});

const data = await response.json();
console.log(data);

Example with parameterized SQL:

const response = await fetch('http://your-suresql-server/db/api/sql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    param_sql: [
      {
        query: "INSERT INTO test (value) VALUES (?)",
        values: ["test value"]
      }
    ]
  })
});

const data = await response.json();
console.log(data);
Query Data

Simple query to get all records from a table:

const response = await fetch('http://your-suresql-server/db/api/query', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    table: "test"
  })
});

const data = await response.json();
console.log(data);

Query with conditions:

const response = await fetch('http://your-suresql-server/db/api/query', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    table: "test",
    condition: {
      field: "id",
      operator: ">",
      value: 5,
      order_by: ["id DESC"],
      limit: 10
    }
  })
});

const data = await response.json();
console.log(data);

Complex query with nested conditions:

const response = await fetch('http://your-suresql-server/db/api/query', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    table: "users",
    condition: {
      logic: "OR",
      nested: [
        {
          field: "age",
          operator: ">",
          value: 30
        },
        {
          logic: "AND",
          nested: [
            {
              field: "status",
              operator: "=",
              value: "active"
            },
            {
              field: "role",
              operator: "=",
              value: "admin"
            }
          ]
        }
      ],
      order_by: ["name ASC"],
      limit: 20
    }
  })
});

const data = await response.json();
console.log(data);
SQL Query

Execute a SQL query and get the results:

const response = await fetch('http://your-suresql-server/db/api/querysql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    statements: ["SELECT * FROM users WHERE role = 'admin'"]
  })
});

const data = await response.json();
console.log(data);

Parameterized SQL query:

const response = await fetch('http://your-suresql-server/db/api/querysql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    param_sql: [
      {
        query: "SELECT * FROM users WHERE role = ? AND status = ?",
        values: ["admin", "active"]
      }
    ]
  })
});

const data = await response.json();
console.log(data);
Insert Data

Insert a single record:

const response = await fetch('http://your-suresql-server/db/api/insert', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    records: [
      {
        table_name: "users",
        data: {
          name: "John Smith",
          age: 35,
          role: "user",
          status: "active"
        }
      }
    ]
  })
});

const data = await response.json();
console.log(data);

Insert multiple records into the same table:

const response = await fetch('http://your-suresql-server/db/api/insert', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    records: [
      {
        table_name: "users",
        data: {
          name: "Alice Johnson",
          age: 28,
          role: "user",
          status: "active"
        }
      },
      {
        table_name: "users",
        data: {
          name: "Bob Williams",
          age: 42,
          role: "admin",
          status: "active"
        }
      }
    ],
    same_table: true
  })
});

const data = await response.json();
console.log(data);

Insert records into different tables:

const response = await fetch('http://your-suresql-server/db/api/insert', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    records: [
      {
        table_name: "users",
        data: {
          name: "Charlie Brown",
          age: 32,
          role: "user",
          status: "active"
        }
      },
      {
        table_name: "posts",
        data: {
          title: "My First Post",
          content: "Hello, world!",
          user_id: 1
        }
      }
    ],
    same_table: false
  })
});

const data = await response.json();
console.log(data);
Get Database Status
const response = await fetch('http://your-suresql-server/db/api/status', {
  method: 'GET',
  headers: {
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  }
});

const data = await response.json();
console.log(data);
Get Schema
const response = await fetch('http://your-suresql-server/db/api/getschema', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'API_KEY': 'your-api-key',
    'CLIENT_ID': 'your-client-id',
    'Authorization': `Bearer ${token}`
  }
});

const data = await response.json();
console.log(data);

Internal API

SureSQL also provides an internal API accessible only with basic authentication using the internal configuration credentials. This API is intended for administrative purposes.

Internal API endpoints:

  • /suresql/iusers (GET, POST, PUT, DELETE) - Manage users
  • /suresql/schema (GET) - Get database schema information
  • /suresql/dbms_status (GET) - Get DBMS status information

Error Handling

All endpoints return a consistent error response format:

{
  "status": 400, // HTTP status code
  "message": "Error message",
  "data": null // or error details
}

Common error status codes:

  • 400: Bad Request - Invalid input or parameters
  • 401: Unauthorized - Missing or invalid authentication
  • 404: Not Found - Resource not found
  • 500: Internal Server Error - Server-side error

Each error response includes a descriptive message to help diagnose the issue.

Documentation

Index

Constants

View Source
const (
	DECRYPT_FILLER          = "."
	TOKEN_STRING            = "token"
	TOKEN_LENGTH_MULTIPLIER = 3 // Controls token length/complexity

)

Constant for auth related like token settings

View Source
const (
	DEFAULT_HTTP_ENVIRONMENT = "./.env.suresql"
	LOG_RAW_QUERY            = false // TODO : this one if on, currently only logging the results, instead of the queries.

)

Define constants for token expiration and generation

View Source
const (
	SUCCESS_EVENT = "success"
	ERROR_EVENT   = "error"
)
View Source
const (
	API_KEY_STRING     = "API_KEY"
	CLIENT_ID_STRING   = "CLIENT_ID"
	TOKEN_TABLE_STRING = "token"
)
View Source
const (
	DEFAULT_INTERNAL_API = "/suresql"
)

Variables

This section is empty.

Functions

func APIKeyClientIDHeader

func APIKeyClientIDHeader() simplehttp.MiddlewareFunc

func AreSameTable

func AreSameTable(records []orm.DBRecord) bool

AreSameTable checks if all records are for the same table

func CopySettingsFromSureSQL added in v0.0.2

func CopySettingsFromSureSQL(cnode suresql.SureSQLNode, config *simplehttp.Config)

if DB settings is not there, get from environment. DB's settings table always wins

func CreateServer

func CreateServer(cnode suresql.SureSQLNode) simplehttp.Server

func DBLogging

func DBLogging(db suresql.SureSQLDB, entry AccessLogTable) error

func DecodeToken

func DecodeToken(tokenstring string, config *suresql.SureSQLDBMSConfig) (string, error)

NOTE: maybe change this to just return empty string if error, then do checking if token=="" instead of error

func HandleConnect

func HandleConnect(ctx simplehttp.Context) error

HandleConnect authenticates a user and returns tokens

func HandleCreateUser

func HandleCreateUser(ctx simplehttp.Context) error

HandleCreateUser creates a new user in the system

func HandleDBMSStatus

func HandleDBMSStatus(ctx simplehttp.Context) error

HandleGetSchema only for internal

func HandleDBStatus

func HandleDBStatus(ctx simplehttp.Context) error

HandleDBStatus returns the current database status

func HandleDeleteUser

func HandleDeleteUser(ctx simplehttp.Context) error

HandleDeleteUser deletes a user from the system

func HandleGetSchema

func HandleGetSchema(ctx simplehttp.Context) error

HandleGetSchema only for internal

func HandleInsert

func HandleInsert(ctx simplehttp.Context) error

HandleInsert processes record insertion requests

func HandleListUsers

func HandleListUsers(ctx simplehttp.Context) error

HandleListUsers retrieves all users from the system (or filtered by username)

func HandleQuery

func HandleQuery(ctx simplehttp.Context) error

HandleQuery processes data query requests

func HandleRefresh

func HandleRefresh(ctx simplehttp.Context) error

HandleRefresh refreshes an existing token

func HandleSQLExecution

func HandleSQLExecution(ctx simplehttp.Context) error

HandleSQLExecution processes SQL execution requests It is protected by both API Key (from AuthMiddleware) and Token (from TokenValidationMiddleware)

func HandleSQLQuery

func HandleSQLQuery(ctx simplehttp.Context) error

HandleSQLExecution processes SQL execution requests It is protected by both API Key (from AuthMiddleware) and Token (from TokenValidationMiddleware)

func HandleUpdateUser

func HandleUpdateUser(ctx simplehttp.Context) error

HandleUpdateUser updates an existing user

func InitTokenMaps

func InitTokenMaps()

InitTokenMaps initializes the token maps with default TTLs

func ListTableNames

func ListTableNames(records []orm.DBRecord) string

Helper function to get a comma-separated list of table names NOTE: not used yet, maybe later for logging

func MiddlewareAPIKeyHeader

func MiddlewareAPIKeyHeader() simplehttp.Middleware

AuthMiddleware verifies API key and client ID from request headers

func MiddlwareTokenCheck

func MiddlwareTokenCheck() simplehttp.Middleware

TokenValidationMiddleware verifies that a valid token is present

func RegisterInternalRoutes

func RegisterInternalRoutes(server simplehttp.Server)

Add these functions to your RegisterRoutes function in handler.go

func RegisterRoutes

func RegisterRoutes(server simplehttp.Server)

RegisterRoutes sets up all the routes for the SureSQL API

func TokenValidationFromTTL

func TokenValidationFromTTL() simplehttp.MiddlewareFunc

Types

type AccessLogTable

type AccessLogTable struct {
	ID            int       `json:"id,omitempty"              db:"id"`
	Username      string    `json:"username,omitempty"        db:"username"`
	ActionType    string    `json:"action_type,omitempty"     db:"action_type"`
	Occurred      time.Time `json:"occurred,omitempty"        db:"occurred"`
	Table         string    `json:"table_name,omitempty"      db:"table_name"`
	RawQuery      string    `json:"raw_query,omitempty"       db:"raw_query"`
	Result        string    `json:"result,omitempty"          db:"result"`
	ResultStatus  string    `json:"result_status,omitempty"   db:"result_status"`
	Error         string    `json:"error,omitempty"           db:"error"`
	Duration      float64   `json:"duration,omitempty"        db:"duration"`
	Method        string    `json:"method,omitempty"          db:"method"`
	NodeNumber    int       `json:"node_number,omitempty"     db:"node_number"`
	Note          string    `json:"note,omitempty"            db:"note"`
	Description   string    `json:"description,omitempty"     db:"description"`
	ClientIP      string    `json:"client_ip,omitempty"       db:"client_ip"`
	ClientBrowser string    `json:"client_browser,omitempty"  db:"client_browser"`
	ClientDevice  string    `json:"client_device,omitempty"   db:"client_device"`
}

func (*AccessLogTable) DBLogging

func (l *AccessLogTable) DBLogging(db *suresql.SureSQLDB) error

Save the logentry to log table

func (AccessLogTable) TableName

func (l AccessLogTable) TableName() string

type Credentials

type Credentials struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func DecryptCredentials

func DecryptCredentials(data string, apiKey, clientID string) (*Credentials, error)

type EncryptedCredentials

type EncryptedCredentials struct {
	Data string `json:"data"`
}

============= NOTE: this are not used at the moment, for future development where we encrypt the ============= data that is passed between request/response

If we want to encrypt the credential for DB connect, encapsulated in just a string 'data' Maybe the encrypt from client is using PGP hence the Front-END will encrypt using public key And Backend decrypt with PrivateKey, Then the encrypted "data" is SureSQLConfig json

type HandlerState

type HandlerState struct {
	Context             simplehttp.Context
	Header              *simplehttp.RequestHeader // Please make sure that the HeaderParser middleware is used! If not it's nil.
	Label               string                    // This is used for logging, it's like the title/function name
	User                string                    // Mostly user that call make the request, could be also user that connect to DB?
	LogMessage          string                    // for success event logs
	ErrorMessage        string                    // for error event logs + Err?
	ResponseMessage     string                    // for handler response (API/Endpoint response)
	Status              int                       // http status usually
	Err                 error                     // original error
	Data                interface{}
	DBLogging           bool
	ConsoleLogging      bool
	DBLoggingEvent      string              // success,error - can be multiple. Which event is logged
	ConsoleLoggingEvent string              // success,error - can be multiple. Which event is logged
	TableNames          string              // table in DB that is related, if applicable
	TimerID             int64               // if using timer, ie from Meda metrics
	Duration            float64             // if using timer, ie from Meda metrics
	Token               *suresql.TokenTable // for specific handlers that requires token
	LogTable            AccessLogTable      // TODO: put them here but somewhat abstract?
}

Standardized handler state. NOTE: maybe next time move this to simplehttp. This is easier way to make end-points Which will always have: - binding the request parameter/body/file attachment? - logic - logging (optional) : can be console/log-files OR insert into DB - response back to caller

func NewHandlerState

func NewHandlerState(ctx simplehttp.Context, user, label, table string) HandlerState

This is the configuration for logging for the project This is state status for basic handlers that do not require status

func NewHandlerTokenState

func NewHandlerTokenState(ctx simplehttp.Context, label, table string) HandlerState

This is the state status for handlers that requires token.

func NewMiddlewareState

func NewMiddlewareState(ctx simplehttp.Context, name string) HandlerState

This is the configuration for logging for the middleware

func (*HandlerState) IsErrorLoggedInConsole

func (h *HandlerState) IsErrorLoggedInConsole() bool

Readibility for the state logging configuration

func (*HandlerState) IsErrorLoggedInDB

func (h *HandlerState) IsErrorLoggedInDB() bool

func (*HandlerState) IsSuccessLoggedInConsole

func (h *HandlerState) IsSuccessLoggedInConsole() bool

func (*HandlerState) IsSuccessLoggedInDB

func (h *HandlerState) IsSuccessLoggedInDB() bool

func (*HandlerState) LogAndResponse

func (h *HandlerState) LogAndResponse(message string, data interface{}, logAgain bool) error

Return response based on context, message and data is used for logging (not response) logAgain if want to run the logging once more and return (if not yet called)

func (*HandlerState) OnlyLog

func (h *HandlerState) OnlyLog(message string, data interface{}, restartTimer bool) error

Implement this method according to the project logTable AND console logging Separate the Logging part and Response part (though it can be combined to make it faster) because sometimes the HandlerState is only for logging before returning anything. Like in the handler it has multiple log entries then at the end send back response

func (*HandlerState) SaveStopTimer

func (h *HandlerState) SaveStopTimer() float64

Stopping the timer if not already stopped. This function is saved to be called multiple times!

func (*HandlerState) SetError

func (h *HandlerState) SetError(msg string, err error, status int) *HandlerState

For chaining calls, this message in parameter is used for response

func (*HandlerState) SetSuccess

func (h *HandlerState) SetSuccess(msg string, data interface{}) *HandlerState

For chaining calls, this message parameter is for response

type TokenStoreStruct

type TokenStoreStruct struct {
	TokenMap        *medattlmap.TTLMap // For access tokens
	RefreshTokenMap *medattlmap.TTLMap // For refresh tokens
}

Mini Redis like Key-Value storage based on MedaTTLMap

var (
	// Instead of Redis, we use ttlmap is lighter
	// TokenMap        *medattlmap.TTLMap // For access tokens
	// RefreshTokenMap *medattlmap.TTLMap // For refresh tokens
	TokenStore TokenStoreStruct
)

Global variables

func NewTokenStore

func NewTokenStore(exp, rexp time.Duration) TokenStoreStruct

func (TokenStoreStruct) GetAll

func (t TokenStoreStruct) GetAll() (map[string]interface{}, map[string]interface{})

func (TokenStoreStruct) RefreshTokenExist

func (t TokenStoreStruct) RefreshTokenExist(token string) (*suresql.TokenTable, bool)

Check if tokenExist, if it is, return the value of the TokenMap[token] - which is interface{} type

func (TokenStoreStruct) SaveToken

func (t TokenStoreStruct) SaveToken(token suresql.TokenTable)

Check if tokenExist, if it is, return the value of the TokenMap[token] - which is interface{} type

func (TokenStoreStruct) TokenExist

func (t TokenStoreStruct) TokenExist(token string) (*suresql.TokenTable, bool)

Check if tokenExist, if it is, return the value of the TokenMap[token] - which is interface{} type

type UserTable

type UserTable struct {
	ID        int       `json:"id,omitempty"           db:"id"`
	Username  string    `json:"username,omitempty"     db:"username"`
	Password  string    `json:"password,omitempty"     db:"password"` // hashed
	RoleName  string    `json:"role_name,omitempty"    db:"role_name"`
	CreatedAt time.Time `json:"created_at,omitempty"   db:"created_at"`
}

UserTable struct representing a user from the database

func (UserTable) TableName

func (u UserTable) TableName() string

type UserUpdateRequest

type UserUpdateRequest struct {
	Username    string `json:"username"`                // Required to identify the user
	NewUsername string `json:"new_username,omitempty"`  // Optional new username
	NewPassword string `json:"new_password,omitempty"`  // Optional new password
	NewRoleName string `json:"new_role_name,omitempty"` // Optional new role
}

UserUpdateRequest represents the data for updating a user

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL