summaryrefslogtreecommitdiff
path: root/src/com/p4square/session/SessionCookieAuthenticator.java
blob: 0074b77fc5fff356c98a2bd8a1193639357130b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Copyright 2013 Jesse Morgan
 */

package com.p4square.session;

import org.apache.log4j.Logger;

import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.security.Authenticator;

/**
 *
 * @author Jesse Morgan <jesse@jesterpm.net>
 */
public class SessionCookieAuthenticator extends Authenticator {
    private static final Logger LOG = Logger.getLogger(SessionCookieAuthenticator.class);

    private static final String COOKIE_NAME  = "S";

    private final Sessions mSessions;

    public SessionCookieAuthenticator(Context context, boolean optional, Sessions sessions) {
        super(context, optional);

        mSessions = sessions;
    }

    protected boolean authenticate(Request request, Response response) {
        final String cookie = request.getCookies().getFirstValue(COOKIE_NAME);

        if (request.getClientInfo().isAuthenticated()) {
            // Request is already authenticated... create session if it doesn't exist.
            if (cookie == null) {
                Session s = mSessions.create(request.getClientInfo().getUser());
                response.getCookieSettings().add(COOKIE_NAME, s.getId());
            }

            return true;

        } else {
            // Check for authentication cookie
            if (cookie != null) {
                LOG.debug("Got cookie: " + cookie);

                Session s = mSessions.get(cookie);
                if (s != null) {
                    request.getClientInfo().setUser(s.getUser());
                    return true;
                }
            }

            return false;
        }
    }

}