net.przemkovv.sphinx.service.UserService.java Source code

Java tutorial

Introduction

Here is the source code for net.przemkovv.sphinx.service.UserService.java

Source

/*
 * The MIT License
 *
 * Copyright 2013 Przemyslaw Walkowiak <przemyslaw.walkowiak@put.poznan.pl>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package net.przemkovv.sphinx.service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import net.przemkovv.sphinx.dao.UserDAO;
import net.przemkovv.sphinx.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class UserService {

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

    @Autowired
    UserDAO userDAO;

    public User getUser(String email) {
        return userDAO.getUser(email);
    }

    @Transactional(readOnly = false)
    public void save(User user) {
        userDAO.save(user);
    }

    @Transactional(readOnly = false)
    //    @Secured({Role.UzytkownicyEdycja})
    public void updatePassword(User user, String password) {
        String passwordHash = createHash(password);
        user.setPassword(passwordHash);
        userDAO.update(user);
    }

    //    @Secured({Role.UzytkownicyEdycja})
    public void setPassword(User user, String password) {
        String passwordHash = createHash(password);
        user.setPassword(passwordHash);
    }

    @Transactional(readOnly = false)
    //    @Secured({Role.UzytkownicyZmianaHasla})
    public void changePassword(User user, String oldPassword, String newPassword) {
        String oldPasswordHash = createHash(oldPassword);
        String newPasswordHash = createHash(newPassword);
        if (user.getPassword().isEmpty() && oldPassword.isEmpty()) {
            user.setPassword(newPasswordHash);
        } else if (user.getPassword().equals(oldPasswordHash)) {
            user.setPassword(newPasswordHash);
        } else {
            throw new BadCredentialsException(
                    "Cannot change password. Invalid old password or no sufficient permissions.");
        }
        userDAO.update(user);

    }

    private String createHash(String data) {
        try {

            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(data.getBytes());
            byte byteData[] = digest.digest();
            //convert bytes to hex chars
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteData.length; i++) {
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException ex) {
            logger.debug("Cannot find MD5 algorithm");
        }
        return null;
    }

    public UserDetails getCurrentUserDetails() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            return (UserDetails) principal;
        } else {
            return null;
        }
    }

    public User getCurrentUser() {
        UserDetails userDetails = getCurrentUserDetails();
        if (userDetails != null) {
            return getUser(userDetails.getUsername());
        } else {
            return null;
        }
    }

    public boolean userExists(String email) {
        return userDAO.existsByEmail(email);
    }

}