Flint DartFlint Dart

🔐 Authentication in Flint Dart

Flint Dart provides built-in support for authentication with the Auth middleware. You can protect your routes and access user information easily with the following methods:

Auth.login

This method handles user login by verifying credentials and issuing tokens. Typically used in your login route.

import 'package:flint_dart/flint_dart.dart';

Future<void> login(Request req, Response res) async {
  final data = await req.json();
  final email = data['email'];
  final password = data['password'];

  final user = await User.findByEmail(email);
  if (user == null || !user.verifyPassword(password)) {
    res.status(401).json({'error': 'Invalid credentials'});
    return;
  }

  final token = Auth.login(user);
  res.json({'token': token});
}

Auth.user

Returns the authenticated user from the request context. Use this inside route handlers to get the current logged-in user.

import 'package:flint_dart/flint_dart.dart';

Future<void> profile(Request req, Response res) async {
  final user = Auth.user(req);
  if (user == null) {
    res.status(401).json({'error': 'Unauthorized'});
    return;
  }

  res.json({'id': user.id, 'email': user.email, 'name': user.name});
}

Auth.check

Middleware to protect routes by checking if the user is authenticated. Returns a 401 response if not authenticated.

import 'package:flint_dart/flint_dart.dart';

class AuthCheckMiddleware extends Middleware {
  @override
  Handler handle(Handler next) {
    return (Request req, Response res) async {
      if (!Auth.check(req)) {
        res.status(401).json({'error': 'Unauthorized'});
        return;
      }
      await next(req, res);
    };
  }
}

Using Auth Middleware

You can apply AuthCheckMiddleware to routes or route groups to protect them.

void registerUserRoutes(Flint app) {
  final authCheck = AuthCheckMiddleware();

  app.get('/profile', authCheck.handle((req, res) async {
    final user = Auth.user(req);
    res.json({'user': user});
  }));

  app.post('/login', login);
}

Auth.loginWithGoogle

Authenticate users with Google OAuth by providing either an idToken or code. Validates input and returns authentication data or errors.

Future<void> loginWithGoogle(Request req, Response res) async {
  try {
    final body = await req.json();

    // Validate input fields
    await Validator.validate(body, {
      "idToken": "string",
      "code": "string",
      "callbackPath": "string"
    });

    // Call Auth.loginWithGoogle with provided parameters
    final Map<String, dynamic> authResult = await Auth.loginWithGoogle(
      idToken: body['idToken'],
      code: body['code'],
      callbackPath: body['callbackPath'],
    );

    res.json({
      "status": "success",
      "data": authResult,
    });
  } on ArgumentError catch (e) {
    res.status(400).json({"status": "error", "message": e.message});
  } on ValidationException catch (e) {
    res.status(400).json({"status": "error", "message": e.errors});
  } catch (e) {
    res.status(401).json({"status": "error", "message": e.toString()});
  }
}