Skip to content

Fathom & SQL DB & Hash password / Best practices #16

Description

@ziguane

Hi all !
I need help...

If I want to store passwords hashs in an SQL database, using a lib like jBCrypt what should I modify in a standard fathom project ?

I tried to implement a FormAuthenticationHandler (good idea ???) but i don't know how to use (smartly) the authenticate instruction (Account account = authenticate(username, password);) with jBCrypt in the method handle.

`@Override
public void handle(Context context) {

    // redirect if already authenticated
    if (isAuthenticated(context)) {
        // touch the session to prolong it's life
        context.touchSession();
        redirectRequest(context);
        return;
    }

    if ("GET".equals(context.getRequestMethod())) {
        // show the form login page

        context.render(AuthConstants.LOGIN_TEMPLATE);

    } else if ("POST".equals(context.getRequestMethod())) {
        // validateCredentials the credentials
        String username = context.getParameter(AuthConstants.USERNAME_PARAMETER).toString();
        String password = context.getParameter(AuthConstants.PASSWORD_PARAMETER).toString();
        boolean rememberMe = context.getParameter(AuthConstants.REMEMBER_ME_PARAMETER).toBoolean(false);


    	
        Account account = authenticate(username, password);

        if (account != null) {
            // Recreate the session to prevent session fixation
            context.recreateSession();

            Cookie c = new Cookie("fsession", username);
            c.setHttpOnly(true);
            c.setMaxAge(-1);
            context.getResponse().cookie(c);

            setupContext(context, account);

            if (rememberMe) {
                // set a cookie
                Cookie cookie = new Cookie(AuthConstants.REMEMBER_ME_COOKIE, username);
                cookie.setHttpOnly(true);
                cookie.setMaxAge((int) TimeUnit.DAYS.toSeconds(365));
                context.getResponse().cookie(cookie);
            }

            // redirect to the original destination or to the root
            redirectRequest(context);

        } else {
            // authentication failed, set the error message and redirect to *self*
            String message = messages.getWithDefault("fathom.invalidCredentials", "Invalid Credentials", context);
            context.flashError(message);
            context.redirect(context.getRequestUri());
        }

    } else {
        // unsupported http method
        throw new StatusCodeException(405, "Only GET and POST are supported!");
    }

}`

Thank in advance !

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions