io.github.autsia.crowly.security.CrowlyAuthenticationManager.java Source code

Java tutorial

Introduction

Here is the source code for io.github.autsia.crowly.security.CrowlyAuthenticationManager.java

Source

/*
 * Copyright 2014 Dmytro Titov
 *
 * 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 io.github.autsia.crowly.security;

import io.github.autsia.crowly.model.CrowlyRole;
import io.github.autsia.crowly.model.CrowlyUser;
import io.github.autsia.crowly.repositories.UserRepository;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Created by Dmytro on 01.01.14 at 18:24
 * Project: crowly
 */
@Component("crowlyAuthenticationManager")
public class CrowlyAuthenticationManager implements AuthenticationManager {

    private static final Logger logger = Logger.getLogger(CrowlyAuthenticationManager.class);

    private UserRepository userRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private Pair<String, String> superUserCredentials;

    @PostConstruct
    protected void init() {
        try {
            CrowlyUser superUser = userRepository.findByEmail(superUserCredentials.getLeft());
            if (superUser == null) {
                superUser = new CrowlyUser();
                superUser.setEmail(superUserCredentials.getLeft());
                superUser.setPassword(superUserCredentials.getRight());
                superUser.setRoles(Collections.singletonList("ROLE_ADMIN"));
                superUser.setAccountNonExpired(true);
                superUser.setAccountNonLocked(true);
                superUser.setCredentialsNonExpired(true);
                superUser.setEnabled(true);
                userRepository.save(superUser);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public String getCurrentUserEmail() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (String) authentication.getPrincipal();
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        try {
            CrowlyUser dbUser = userRepository.findByEmail(authentication.getName());
            if (bCryptPasswordEncoder.matches(authentication.getCredentials().toString(), dbUser.getPassword())) {
                return new UsernamePasswordAuthenticationToken(authentication.getName(),
                        authentication.getCredentials(), getAuthorities(dbUser));
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        throw new BadCredentialsException(authentication.getName());
    }

    public Collection<? extends GrantedAuthority> getAuthorities(CrowlyUser user) {
        List<String> roles = user.getRoles();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }

    public void addUser(CrowlyUser user) throws AuthenticationException {
        String email = user.getEmail();
        if (userRepository.findByEmail(email) != null) {
            throw new BadCredentialsException(email + " is already used by another person.");
        }
        user.setRoles(Collections.singletonList(CrowlyRole.ROLE_USER.name()));
        user.setEnabled(true);
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setCredentialsNonExpired(true);
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Autowired
    public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Autowired
    public void setSuperUserCredentials(Pair<String, String> superUserCredentials) {
        this.superUserCredentials = superUserCredentials;
    }
}