org.apigw.authserver.web.controller.TokensController.java Source code

Java tutorial

Introduction

Here is the source code for org.apigw.authserver.web.controller.TokensController.java

Source

/**
 *   Copyright 2013 Stockholm County Council
 *
 *   This file is part of APIGW
 *
 *   APIGW is free software; you can redistribute it and/or modify
 *   it under the terms of version 2.1 of the GNU Lesser General Public
 *   License as published by the Free Software Foundation.
 *
 *   APIGW is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with APIGW; if not, write to the
 *   Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 *   Boston, MA 02111-1307  USA
 *
 */
package org.apigw.authserver.web.controller;

import org.apache.velocity.exception.ResourceNotFoundException;
import org.apigw.authserver.svc.repository.AuthorizationGrantRepository;
import org.apigw.authserver.types.domain.CertifiedClientPermission;
import org.apigw.authserver.types.domain.AuthorizationGrant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Extended functionality for managing tokens
 *
 * @author Christian Hilmersson
 *
 */
@Controller
@SessionAttributes
@RequestMapping(value = "/oauth/tokens")
public class TokensController {

    private static final Logger log = LoggerFactory.getLogger(TokensController.class);

    @Autowired
    private AuthorizationGrantRepository authorizationGrantRepository;
    protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

    @RequestMapping(value = "/{token}/status", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> getTokenStatus(@PathVariable("token") String token) {
        log.debug("getTokenStatus(...)");
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetails user = (UserDetails) principal;
        String clientId = user.getUsername();
        log.debug("The logged in client is {}", clientId);
        AuthorizationGrant grant = authorizationGrantRepository.findByAccessTokenAndClientIdJoinRoles(token,
                clientId);
        if (grant == null || !clientId.equals(grant.getClientId())) {
            throw new ResourceNotFoundException("Couldn't find a grant for the given token.");
        }
        Map<String, Object> response = new HashMap<String, Object>();
        addFormattedDate(response, "accessTokenExpires", grant.getAccessTokenExpires(), sdf);
        response.put("accessToken", grant.getAccessToken());
        addFormattedDate(response, "issueDate", grant.getIssueDate(), sdf);
        if (grant.getGrantedPermissions() != null && grant.getGrantedPermissions().size() != 0) {
            log.debug("Found {} assigned roles.", grant.getGrantedPermissions().size());
            List<String> scopes = new ArrayList<String>();
            for (CertifiedClientPermission asR : grant.getGrantedPermissions()) {
                log.debug("Adding scope {}", asR.getPermissionName());
                scopes.add(asR.getPermissionName());
            }
            log.debug("Added all scopes");
            response.put("scope", scopes);
        } else {
            response.put("scope", "");
        }
        log.debug("response:{}", response);
        return response;
    }

    private void addFormattedDate(Map<String, Object> map, String name, Date date, SimpleDateFormat format) {
        if (date != null) {
            map.put(name, format.format(date));
        } else {
            map.put(name, "");
        }
    }

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException e) {
        log.info("ResourceNotFound: {}", e.getMessage());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "text/plain");
        return new ResponseEntity<String>("Resource not found!", headers, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.class)
    public void handleException(Exception e) throws Exception {
        log.error("An error was caught by the exception handler.", e);
        throw e;
    }
}