net.prasenjit.auth.service.ClientService.java Source code

Java tutorial

Introduction

Here is the source code for net.prasenjit.auth.service.ClientService.java

Source

/*
 * Copyright (c) 2016 Prasenjit Purohit
 *
 *    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 net.prasenjit.auth.service;

import net.prasenjit.auth.domain.Client;
import net.prasenjit.auth.domain.User;
import net.prasenjit.auth.repository.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * Created by PRASENJIT-NET on 4/4/2016.
 *
 * @author PRASEN
 * @version $Id: $Id
 */
@Service
public class ClientService implements ClientDetailsService {
    @Autowired
    private ClientRepository clientRepository;

    /**
     * {@inheritDoc}
     */
    @Override
    @Transactional(readOnly = true)
    public Client loadClientByClientId(String clientId) throws ClientRegistrationException {
        Client client = clientRepository.findOne(clientId);
        if (client == null) {
            throw new ClientRegistrationException("Client '" + clientId + "' not found");
        }
        return client;
    }

    /**
     * <p>save.</p>
     *
     * @param client a {@link net.prasenjit.auth.domain.Client} object.
     * @return a {@link net.prasenjit.auth.domain.Client} object.
     */
    @Transactional
    public Client save(Client client) {
        if (!StringUtils.hasText(client.getClientId())) {
            client.setClientId(UUID.randomUUID().toString());
            client.setClientSecret(UUID.randomUUID().toString());
        }
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        client.setUser(user);

        return clientRepository.save(client);
    }
}