Authentication Tutorial

A complete login flow: options, a login view, and the events that wire it together.

Build a login form and wire it to the framework’s built-in authentication, with a protected main view.

1. Configure the application

import { Application } from "/lib/altseven/dist/a7.js";

export const myApp = new Application( {
	name: "myapp",
	remote: {
		loginURL: "/api/auth/login",
		logoutURL: "/api/auth/logout",
		refreshURL: "/api/auth/refresh",
		useTokens: true,
		tokenType: "X-Token"
	},
	security: {
		enabled: true,
		userArgs: { userID: "" }
	}
} );

With security.enabled, await myApp.init() performs the auth check: it calls the refresh endpoint and sets myApp.authenticated and myApp.user. Your startup function can branch on the result.

2. Structure the app around the login state

export let loginForm;
export let main;

export async function application() {
	try {
		await myApp.init();

		loginForm = LoginForm( { id: "loginForm", selector: "#loginForm" } );
		main = Main( { id: "main", selector: "#main" } );

		if( myApp.authenticated ) {
			showApp();
		} else {
			showLogin();
		}
	} catch( e ) {
		console.error( "App init failed:", e );
	}
}

function showLogin() {
	// toggle mount-point visibility (plain DOM, not view state — these are
	// static containers in index.html)
	document.querySelector( "#loginForm" ).style.display = "block";
	document.querySelector( "#main" ).style.display = "none";
}

function showApp() {
	document.querySelector( "#loginForm" ).style.display = "none";
	document.querySelector( "#main" ).style.display = "block";
	main.setState( { user: myApp.user } );
}

3. The login view

import { myApp } from "./app.js";
import { View } from "/lib/altseven/dist/a7.js";

export function LoginForm( props ) {

	const loginForm = new View( props );

	loginForm.state = { username: "", password: "", message: "" };

	loginForm.template = function() {
		const state = loginForm.getState();
		return `
		<form data-onsubmit="handleLogin">
			<h2>Sign in</h2>
			${ state.message ? `<p class="error">${ state.message }</p>` : "" }
			<input type="text" name="username" value="${ state.username }"
				placeholder="Username" autocomplete="username">
			<input type="password" name="password" value=""
				placeholder="Password" autocomplete="current-password">
			<button type="submit">Sign in</button>
		</form>`;
	};

	loginForm.eventHandlers = {
		handleLogin: function( event ) {
			event.preventDefault();
			const form = event.target;
			loginForm.setState( { message: "" } );

			myApp.events.publish( "auth.login", {
				username: form.elements.username.value,
				password: form.elements.password.value,
				success: function( json ) {
					showApp();
				},
				failure: function( json ) {
					loginForm.setState( {
						message: json.message || "Login failed",
						username: form.elements.username.value
					} );
				}
			} );
		}
	};

	myApp.ui.register( loginForm );
	return loginForm;
}

The auth.login publisher (built into the framework) POSTs to loginURL with HTTP Basic auth headers. On { success: true, user } it stores the token and the user, then invokes your success; on { success: false } it invokes your failure with the JSON body.

4. Success and failure as routes or events

Instead of functions, success/failure can name an event topic or a route:

myApp.events.publish( "auth.login", {
	username, password,
	success: "auth.loginSuccess",     // event topic...
	failure: "auth.loginFailure"
} );
myApp.events.subscribe( "auth.loginSuccess", function( json ) {
	showApp();
} );

…or, when the router is configured, a route path — the router opens it and the mapped event fires:

myApp.events.publish( "auth.login", {
	username, password,
	success: "/",      // router destination
	failure: "/login"
} );

5. The back end contract

A minimal Node/Express implementation of the three endpoints:

// POST /api/auth/login
//   Authorization: Basic base64(user:pass)   (set by the framework)
//   Body: { "rememberMe": false }
app.post( "/api/auth/login", ( req, res ) => {
	const [ user, pass ] = basicAuthCredentials( req );
	if( !checkCredentials( user, pass ) ) {
		return res.json( { success: false, message: "Invalid credentials" } );
	}
	res.set( "X-Token", issueToken( user ) );       // framework reads this header
	res.json( { success: true, user: { userID: 7, name: user } } );
} );

// GET /api/auth/refresh  (token attached by the framework)
app.get( "/api/auth/refresh", ( req, res ) => {
	const user = validateToken( req.header( "X-Token" ) );
	if( !user ) return res.status( 401 ).end();
	res.json( { authenticated: true, user } );       // 401 → authenticated: false
} );

// POST /api/auth/logout
app.post( "/api/auth/logout", ( req, res ) => {
	revokeToken( req.header( "X-Token" ) );
	res.json( { success: true } );
} );

6. Logout

myApp.events.publish( "auth.logout", {
	success: function( json ) {
		showLogin();
	}
} );

On success the framework invalidates the session (token cleared, user reset) before invoking your handler.

Common pitfalls

  • success/failure strings depend on the router. With a router configured, plain strings are treated as route destinations; without one, they are event topics. Pass functions when you want to be explicit.
  • The login view keeps re-rendering while typing. Don’t setState() on every keystroke from the password field; read input values from event.target.elements in the submit handler (as above).
  • A 401 from refresh at startup is normal for logged-out visitors — myApp.authenticated is simply false; it is not an error condition.