com.threewks.thundr.user.controller.AuthorisedInterceptor.java Source code

Java tutorial

Introduction

Here is the source code for com.threewks.thundr.user.controller.AuthorisedInterceptor.java

Source

/*
 * This file is a component of thundr, a software library from 3wks.
 * Read more: http://www.3wks.com.au/thundr
 * Copyright (C) 2015 3wks, <thundr@3wks.com.au>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.threewks.thundr.user.controller;

import org.apache.commons.lang3.StringUtils;

import com.threewks.thundr.http.exception.ForbiddenException;
import com.threewks.thundr.request.Request;
import com.threewks.thundr.request.Response;
import com.threewks.thundr.route.controller.Interceptor;
import com.threewks.thundr.session.Session;
import com.threewks.thundr.session.SessionService;
import com.threewks.thundr.user.Roles;
import com.threewks.thundr.user.User;
import com.threewks.thundr.view.View;

public class AuthorisedInterceptor extends BaseAuthenticationFilterceptor implements Interceptor<Authorised> {

    public AuthorisedInterceptor(SessionService<?> sessionService) {
        super(sessionService);
    }

    @SuppressWarnings("unchecked")
    @Override
    public View before(Authorised annotation, Request req, Response resp) {
        Session session = getSession(req, resp);
        if (session != null && session.isAuthenticated()) {
            User user = session.getUser();
            if (user != null) {
                Roles roles = user.getRoles();
                String[] all = annotation.all();
                String[] any = annotation.any();
                boolean hasAll = all == null || all.length == 0 || roles.hasRoles(all);
                boolean hasAny = any == null || any.length == 0 || roles.hasAnyRole(any);
                if (hasAll && hasAny) {
                    return null;
                }
            }
        }
        String redirect = StringUtils.trimToNull(annotation.redirect());
        if (redirect != null) {
            return redirectToRouteOrPath(redirect);
        }
        throw new ForbiddenException("Insufficient authorisation");
    }

    @Override
    public <T> T after(Authorised annotation, Object result, Request req, Response resp) {
        return null;
    }

    @Override
    public <T> T exception(Authorised annotation, Exception e, Request req, Response resp) {
        return null;
    }
}