Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User Auth Template #26

Merged
merged 12 commits into from
Oct 23, 2024
Merged

User Auth Template #26

merged 12 commits into from
Oct 23, 2024

Conversation

Brayden
Copy link
Owner

@Brayden Brayden commented Oct 17, 2024

Purpose

Bindable Microservices. This contribution is the first in this direction where templates are provided out of the box to help kickstart development in a few simple steps, in a way that you can have ownership to control and modify application logic to fit the needs of your project. As the first exploratory template, we're introducing basic user authentication.

  • Create new user accounts with username or email and a password
  • Login to accounts to create new sessions
  • New sessions provide a token where you can verify user validity in future requests

When it comes to making subsequent requests with authentication, you will need to check the users session is valid & active yourself. We did not implement this by default out of the box due to the unknowing of how each application will handle the middleware aspects. However, an example/available isSessionValid function is available for you to reference on how to verify sessions.

The objective with StarbaseDB is to provide essential tooling developers need as close to their database as possible without any additional effort. We believe Bindable Microservices is a step in that direction.

Tasks

Execute SQL statements in migration.sql to create required tables

This will create the tables and constraints for user signup/login, and sessions. You can do this in the Studio user interface or by hitting your query endpoint in your StarbaseDB instance.

CREATE TABLE IF NOT EXISTS auth_users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT COLLATE NOCASE,
    password TEXT NOT NULL,
    email TEXT COLLATE NOCASE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP DEFAULT NULL,
    email_confirmed_at TIMESTAMP DEFAULT NULL,
    UNIQUE(username),
    UNIQUE(email),
    CHECK ((username IS NOT NULL AND email IS NULL) OR (username IS NULL AND email IS NOT NULL) OR (username IS NOT NULL AND email IS NOT NULL))
);

CREATE TRIGGER IF NOT EXISTS prevent_username_email_overlap 
BEFORE INSERT ON auth_users
BEGIN
    SELECT CASE 
        WHEN EXISTS (
            SELECT 1 FROM auth_users 
            WHERE (NEW.username IS NOT NULL AND (NEW.username = username OR NEW.username = email))
               OR (NEW.email IS NOT NULL AND (NEW.email = username OR NEW.email = email))
        )
    THEN RAISE(ABORT, 'Username or email already exists')
    END;
END;

CREATE TABLE IF NOT EXISTS auth_sessions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    session_token TEXT NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP DEFAULT NULL,
    FOREIGN KEY (user_id) REFERENCES auth_users (id)
);

Add service bindings to wrangler.toml

[[services]]
binding = "AUTH"
service = "starbasedb_auth"
entrypoint = "AuthEntrypoint"

Add AUTH to Env interface in ./src/index.ts

AUTH: {
    handleAuth(pathname: string, verb: string, body: any): Promise<Response>;
}

Add routing logic in default export in ./src/index.ts

if (pathname.startsWith('/auth')) {
    const body = await request.json();
    return await env.AUTH.handleAuth(pathname, request.method, body);
}

Deploy template project to Cloudflare

cd ./templates/auth
npm i && npm run deploy

Deploy updates to StarbaseDB to Cloudflare

cd ../..
npm run deploy

NOTE: You will want to deploy your new service worker for authentication before deploying updates to your StarbaseDB instance, because the StarbaseDB instance will rely on the authentication worker being available (see the service bindings we added in the wrangler.toml file for reference).

Verify

Before

After

wrangler.toml Outdated Show resolved Hide resolved
@Brayden Brayden self-assigned this Oct 23, 2024
@Brayden Brayden added the enhancement New feature or request label Oct 23, 2024
@Brayden Brayden changed the title WIP: User Auth Template User Auth Template Oct 23, 2024
@Brayden Brayden marked this pull request as ready for review October 23, 2024 18:46
@Brayden Brayden merged commit 7f50602 into main Oct 23, 2024
@Brayden Brayden deleted the bwilmoth/template-auth branch October 23, 2024 19:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant