source: trunk/grails-app/services/dbnp/authentication/AuthenticationService.groovy @ 983

Last change on this file since 983 was 983, checked in by robert@…, 10 years ago

New type of authentication and authorization added to the rest controller. See ticket 118

File size: 4.3 KB
Line 
1/**
2 * AuthenticationService
3 *
4 * Is used for keeping track of the logged in user
5 *
6 * @author      robert@isdat.nl (Robert Horlings
7 * @since       20101021
8 * @package     dbnp.authentication
9 *
10 * Revision information:
11 * $Rev$
12 * $Author$
13 * $Date$
14 */
15package dbnp.authentication
16
17import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser
18
19class AuthenticationService {
20    def SpringSecurityService
21    static final int expiryTime = 60; // Number of minutes a remotely logged in user remains active
22
23    boolean transactional = true
24
25    public boolean isLoggedIn() {
26        return SpringSecurityService.isLoggedIn();
27    }
28
29    public SecUser getLoggedInUser() {
30      def principal = SpringSecurityService.getPrincipal()
31
32      // If the user is logged in, the principal should be a GrailsUser object.
33      // If the user is not logged in, the principal is the 'anonymous username'
34      // i.e. a string
35      if( principal instanceof GrailsUser ) {
36          return SecUser.findByUsername( principal.username );
37      }
38
39      return null;
40    }
41
42    /**
43     * Logs a user in for a remote session
44     */
45    public boolean logInRemotely( String consumer, String token, SecUser user ) {
46        // Make sure there is no other logged in user anymore
47        logOffRemotely( consumer, token )
48
49        def SAUser = new SessionAuthenticatedUser( consumer: consumer, token: token, secUser: user, expiryDate: createExpiryDate() )
50
51        return SAUser.save(flush: true)
52    }
53   
54    public boolean logOffRemotely( String consumer, String token ) {
55        def user = getSessionAuthenticatedUser(consumer, token)
56       
57        if( user )
58            user.delete()
59       
60        return true
61    }
62
63    /**
64     * Checks whether a user is logged in from a remote consumer with the
65     * given token
66     */
67    public boolean isRemotelyLoggedIn( String consumer, String token ) {
68        // Remove expired users, otherwise they will be kept in the database forever
69        removeExpiredTokens()
70
71        // Check whether a user exists
72        def user = getSessionAuthenticatedUser(consumer, token)
73
74        // Check whether the user is logged in. Since we don't want to return a
75        // user, we explicitly return true or false
76        if( user ) {
77                        // The expiry date should be reset
78                        updateExpiryDate( user )
79
80            return true
81                } else {
82            return false
83                }
84    }
85
86    /**
87     * Returns the user that is logged in remotely
88     */
89    public SecUser getRemotelyLoggedInUser( String consumer, String token ) {
90        // Remove expired users, otherwise they will be kept in the database forever
91        removeExpiredTokens()
92
93        // Check whether a user exists
94        def user = getSessionAuthenticatedUser(consumer, token)
95
96        return user ? user.secUser : null
97    }
98
99    /**
100     * Removes all tokens for remote logins that have expired
101     */
102    protected boolean removeExpiredTokens() {
103        SessionAuthenticatedUser.executeUpdate("delete SessionAuthenticatedUser u where u.expiryDate < :expiryDate", [ expiryDate: new Date() ])
104    }
105
106    /**
107         * Returns the currently logged in user from the database or null if no user is logged in
108         */
109        protected SessionAuthenticatedUser getSessionAuthenticatedUser( String consumer, String token ) {
110        def c = SessionAuthenticatedUser.createCriteria()
111        def result = c.get {
112                and {
113                        eq( "consumer", consumer)
114                        eq( "token", token)
115                        gt( "expiryDate", new Date())
116                }
117        }
118
119        if( result )
120            return result
121        else
122            return null
123    }
124
125        /**
126         * Returns the expiry date for a user that is active now.
127         */
128        protected Date createExpiryDate() {
129                // Compute expiryDate
130                long now = new Date().getTime();
131                return new Date( now + AuthenticationService.expiryTime * 60 * 1000 );
132
133        }
134
135        /**
136         * Resets the expiry date of the given user. This should be called every time
137         * an action occurs with this user. That way, if (in case of a timeout of 60 minutes)
138         * he logs in and returns 50 minutes later, he will keep a timeout value of
139         * 60 minutes, instead of only 10 minutes.
140         */
141        protected boolean updateExpiryDate( SessionAuthenticatedUser user ) {
142                user.expiryDate = createExpiryDate()
143                return user.save( flush: true )
144        }
145}
Note: See TracBrowser for help on using the repository browser.