sf-auth-middleware-gin/requirements.md
2026-02-06 17:44:51 -08:00

2.4 KiB

We need to create a new Go library that makes it easy to interface with sf-auth and Gin. There should be two components: 1. A middleware, 2. a prebuilt route. A sample of the Rust implementation looks like the following

use axum::{
    Router, response::Html, routing::get
};
use sf_auth_middleware_axum::{SfAuthLayer, SfUser};
use tower_sessions::{MemoryStore, SessionManagerLayer};

async fn root() -> Html<String> {
    Html(format!("<h1>Auth demo</h1><a href='/user_info'>Check my info</a>"))
}

async fn user_info(user: SfUser) -> Html<String> {
    Html(format!("<h1>Hello!</h1><br/>Username: {}<br />User ID: {}", user.username(), user.user_id()))
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();

    let session_store = MemoryStore::default();
    let session_layer = SessionManagerLayer::new(session_store);

    let app = Router::new()
        .route("/user_info", get(user_info))
        .layer(SfAuthLayer::new(|_req| "http://localhost:3000/auth_callback".to_string()))
        .route("/auth_callback", get(sf_auth_middleware_axum::create_auth_callback("/user_info")))
        .route("/", get(root))
        .layer(session_layer);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Middleware The middleware should check the session for an sf_user_id or sf_username. If they are missing, then we should redirect to https://snazzyfellas.com/api/redirect/authenticate?redirect_uri=%s where %s is some URL provided by the user of this library. The user should configure this URL to match the pre-built route in the next section.

Pre-built Route There should be a pre-built route that the user of the library can add to their Gin project that lets them handle the callback from the sf-auth api mentioned previously. It should also take in a URL that redirects to another page on the current server, and a relative path will work especially for examples. This endpoint should take in user_id, username, and key as query parameters. This key is one time use, and should be sent along with user_id in a POST request to https://snazzyfellas.com/api/redirect/validate . The response will return JSON with a valid boolean value and a string user_id value. If valid is true and user_id matches the user_id passed to the page, then set the username, user_id session variables. If they do not, then show an error. After setting the session variables, redirect to the URL provided by the user.