DEV Community

Tom Liang
Tom Liang

Posted on • Updated on


User validation with Passport.js and fp-ts

I had a first try on using fp-ts to do user validation with passport.js.

import argon2 from "argon2";
import * as E from "fp-ts/lib/Either";
import { flow, pipe } from "fp-ts/lib/function";
import * as O from "fp-ts/lib/Option";
import * as TE from "fp-ts/lib/TaskEither";
import * as passport from "passport";
import * as PassportLocal from "passport-local";
import logger from "./logger";
import {
} from "../db/entities/user_profile";

const verifyPassport: PassportLocal.VerifyFunction = (
    userName: string,
    password: string,
) => {
    const onUserFound = (optionUser: O.Option<UserProfile>) => {
        const onSome = (user: UserProfile) => () =>
                .verify(user.userPassword, password)
                .then((valid) =>
                        ? E.right(user)
                        : E.left(new Error(`invalid user name or password`))
        const onNone = () =>
            TE.left(new Error(`user name ${userName} doesn't exist`));
        return pipe(optionUser, O.match(onNone, onSome));
        UserProfileRepository.findOneByUserName /*returns TE.TaskEither<Error, O.Option<UserProfile>> */,
            ({ message }) => done(null, false, { message }),
            (user) => done(null, user)

Enter fullscreen mode Exit fullscreen mode

Latest comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!