net.navasoft.madcoin.backend.services.rest.impl.SessionService.java Source code

Java tutorial

Introduction

Here is the source code for net.navasoft.madcoin.backend.services.rest.impl.SessionService.java

Source

/*******************************************************************************
 * Copyright 2014 Juan Diego Navarre Gonzalez
 * 
 * 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.navasoft.madcoin.backend.services.rest.impl;

import java.util.Calendar;
import java.util.Date;

import javax.crypto.BadPaddingException;

import net.navasoft.madcoin.backend.AllowedChannels;
import net.navasoft.madcoin.backend.UserTypes;
import net.navasoft.madcoin.backend.annotations.ProcessedField;
import net.navasoft.madcoin.backend.annotations.ProcessorService;
import net.navasoft.madcoin.backend.annotations.helper.Precedence;
import net.navasoft.madcoin.backend.model.controller.exceptions.AlreadyOnSourceException;
import net.navasoft.madcoin.backend.model.controller.exceptions.NonexistentEntityException;
import net.navasoft.madcoin.backend.model.controller.exceptions.PreexistingEntityException;
import net.navasoft.madcoin.backend.model.entities.impl.EndUserTypes;
import net.navasoft.madcoin.backend.model.entities.impl.EndUsers;
import net.navasoft.madcoin.backend.model.entities.impl.EndUsersPK;
import net.navasoft.madcoin.backend.model.entities.impl.ServiceProviders;
import net.navasoft.madcoin.backend.model.entities.impl.ServiceProvidersPK;
import net.navasoft.madcoin.backend.services.controller.exception.impl.ControllerExceptionFactory;
import net.navasoft.madcoin.backend.services.rest.ISessionService;
import net.navasoft.madcoin.backend.services.security.BCrypt;
import net.navasoft.madcoin.backend.services.vo.request.SuccessRequestVO;
import net.navasoft.madcoin.backend.services.vo.response.SessionSuccessResponseVO;
import net.navasoft.madcoin.backend.services.vo.response.SuccessResponseVO;
import net.navasoft.madcoin.backend.services.vo.response.impl.AllowedGender;
import net.navasoft.madcoin.backend.services.vo.response.impl.AppSignupSuccessResponseVO;
import net.navasoft.madcoin.backend.services.vo.response.impl.ProviderInfoSuccessResponseVO;
import net.navasoft.madcoin.backend.services.vo.response.impl.UserInfoSuccessResponseVO;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * net.navasoft.madcoin.backend.services.rest.impl Class class SessionService.
 * Description:
 * 
 * @author Juan Diego Navarre Gonzalez - (${authorMail})
 * @version 1.0
 * @since 31/08/2014 07:37:50 PM
 */
@Component(value = "SessionService")
@ProcessorService
public class SessionService implements ISessionService {

    /**
     * authentication manager.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @Autowired
    @Qualifier(value = "authenticationManager")
    private AuthenticationManager authenticationManager;

    /**
     * authentication provider.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @Autowired
    @Qualifier(value = "prov_authenticationManager")
    private AuthenticationManager authenticationProvider;

    /**
     * token generator.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @Autowired
    @Qualifier(value = "tokenutils")
    private TokenUtils tokenGenerator;

    /**
     * accessor.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @Autowired
    @Qualifier("endUsersDao")
    private IDataAccess<EndUsers> accessor;

    /**
     * accessor.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @Autowired
    @Qualifier("dataAccessProvider")
    private IDataAccess<ServiceProviders> accessorProvider;

    /**
     * requesting user.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "requestingUser")
    private String requestingUser;

    /**
     * password provided.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "passwordProvided")
    private String passwordProvided;

    /**
     * generated token.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "generatedToken")
    private String generatedToken;

    /**
     * request address.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_OPTIONAL, possibleVariables = "requestAddress")
    private String requestAddress;

    /**
     * birth age.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = Date.class, precedence = Precedence.COMPLEX_REQUIRED, possibleVariables = "birthAge")
    private Date birthAge;

    /**
     * email.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "email")
    private String email;

    /**
     * first_names.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "first_names")
    private String first_names;

    /**
     * last_names.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "last_names")
    private String last_names;

    /**
     * mobile.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "mobile")
    private String mobile;

    /**
     * gender.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = AllowedGender.class, precedence = Precedence.BASIC_OPTIONAL, possibleVariables = "gender")
    private AllowedGender gender;

    /**
     * type.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = UserTypes.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "type")
    private UserTypes type;

    /**
     * model.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "model")
    private String model;

    /**
     * operative system.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "operativeSystem")
    private String operativeSystem;

    /**
     * serial.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "serial")
    private String serial;

    /**
     * version.
     * 
     * @since 31/08/2014, 07:37:50 PM
     */
    @ProcessedField(expectedType = String.class, precedence = Precedence.BASIC_REQUIRED, possibleVariables = "version")
    private String version;

    /**
     * Login.
     * 
     * @param loginRequested
     *            the login requested
     * @return the user info success response vo
     * @since 31/08/2014, 07:37:51 PM
     */
    public SuccessResponseVO login(SuccessRequestVO loginRequested) {
        SessionSuccessResponseVO response;
        try {
            loginRequested.processValues(this);
            requestingUser = String.valueOf(loginRequested.extractValue("requestingUser"));// (String)
            // loginRequested.getAttribute("Username");
            passwordProvided = BCrypt.hashpw(String.valueOf(loginRequested.extractValue("passwordProvided")),
                    BCrypt.gensalt(14));// (String)
            // loginRequested.getAttribute("Password");
            type = (UserTypes) loginRequested.extractValue("type");
            model = String.valueOf(loginRequested.extractValue("model"));
            operativeSystem = String.valueOf(loginRequested.extractValue("operativeSystem"));
            serial = String.valueOf(loginRequested.extractValue("serial"));
            version = String.valueOf(loginRequested.extractValue("version"));
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(requestingUser,
                    passwordProvided);
            Authentication auth;
            String generatedToken;
            switch (type) {
            case END_USER_TYPE:
                response = new UserInfoSuccessResponseVO();
                auth = authenticationManager.authenticate(token);
                // SecurityContextHolder.getContext().setAuthentication(auth);
                generatedToken = tokenGenerator.getToken(requestingUser, passwordProvided);
                response.setToken(generatedToken.replace("+", "%2B").replace("/", "%2F"));
                requestAddress = String.valueOf(loginRequested.extractValue("requestAddress"));
                EndUsersPK key = new EndUsersPK();
                key.setAppUsername(auth.getName());
                EndUsers user = accessor.getByLogicalId(key);
                user.setLastLoggedIp(requestAddress);
                user.setLastLogged(Calendar.getInstance().getTime());
                try {
                    user = accessor.edit(user);
                } catch (NonexistentEntityException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                response.setFullName(user.getUserNames() + " " + user.getLastName());
                response.setEmail(user.getEmail());
                ((UserInfoSuccessResponseVO) response).setLastSuccessLoggedOn(user.getLastLogged());
                ((UserInfoSuccessResponseVO) response).setLastSuccessLoggedIP(user.getLastLoggedIp());
                ((UserInfoSuccessResponseVO) response).setLastSuccessLoggedWay(AllowedChannels
                        .valueOf(StringUtils.defaultString(user.getLastLoggedWay(), AllowedChannels.NONE.name())));
                response.setLastPasswordReset(user.getLastPasswordReset());
                response.setCreatedSince(user.getCreatedSince());
                response.setUserType(user.getIdUserType().getEndUserType());
                response.setUserTypeDescription(user.getIdUserType().getEndUserDescription());
                ((UserInfoSuccessResponseVO) response).setMobile(user.getMobile());
                ((UserInfoSuccessResponseVO) response).setBirthAge(user.getBirthAge());
                return response;
            case SERVICE_PROVIDER_TYPE:
                response = new ProviderInfoSuccessResponseVO();
                auth = authenticationProvider.authenticate(token);
                generatedToken = tokenGenerator.getToken(requestingUser, passwordProvided);
                response.setToken(generatedToken.replace("+", "%2B").replace("/", "%2F"));
                requestAddress = String.valueOf(loginRequested.extractValue("requestAddress"));
                ServiceProvidersPK keyProv = new ServiceProvidersPK();
                keyProv.setAppUsername(auth.getName());
                ServiceProviders userProv = accessorProvider.getByLogicalId(keyProv);
                // accessorProv.update(user);
                response.setFullName(userProv.getName() + " " + userProv.getLastName());
                response.setEmail(userProv.getEmail());
                response.setCreatedSince(userProv.getAuthorizedOn());
                response.setUserType(userProv.getProviderRole().getProviderType());
                response.setUserTypeDescription(userProv.getProviderRole().getProviderType());
                return response;
            }
            response = null;
        } catch (BadCredentialsException unmatched) {
            System.out.println("unmatched");
            throw ControllerExceptionFactory.createException(unmatched.getClass().getCanonicalName(), 3,
                    loginRequested.getErrorProcessingValues());
        } catch (UsernameNotFoundException notfound) {
            System.out.println("notfound");
            throw ControllerExceptionFactory.createException(notfound.getClass().getCanonicalName(), 3,
                    loginRequested.getErrorProcessingValues());
        } catch (DisabledException unable) {
            System.out.println("unable");
            throw ControllerExceptionFactory.createException(unable.getClass().getCanonicalName(), 3,
                    loginRequested.getErrorProcessingValues());
        }
        return response;
    }

    /**
     * Gets the user info.
     * 
     * @param userRequested
     *            the user requested
     * @return the user info
     * @since 31/08/2014, 07:37:51 PM
     */
    public UserInfoSuccessResponseVO getUserInfo(SuccessRequestVO userRequested) {
        userRequested.processValues(this);
        generatedToken = String.valueOf(userRequested.extractValue("generatedToken"));
        try {
            if (tokenGenerator.validate(generatedToken.replace("%2B", "+").replace("%2F", "/"))) {
                UserInfoSuccessResponseVO response = new UserInfoSuccessResponseVO();
                EndUsersPK key = new EndUsersPK();
                key.setAppUsername(
                        ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal())
                                .getUsername());
                EndUsers user = accessor.getByLogicalId(key);
                response.setFullName(user.getUserNames() + " " + user.getLastName());
                response.setEmail(user.getEmail());
                response.setToken(generatedToken);
                return response;
            } else {
                return null;
            }
        } catch (BadPaddingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Validate origin.
     * 
     * @return true, if successful, otherwise false
     * @since 31/08/2014, 07:37:51 PM
     */
    private boolean validateOrigin() {
        return (model != null && operativeSystem != null && serial != null && version != null);
    }

    /**
     * Sign up user.
     * 
     * @param newUser
     *            the new user
     * @return the success response vo
     * @since 31/08/2014, 07:37:51 PM
     */
    @Override
    public SuccessResponseVO signUpUser(SuccessRequestVO newUser) {
        AppSignupSuccessResponseVO response = new AppSignupSuccessResponseVO();
        try {
            newUser.processValues(this);
            requestingUser = String.valueOf(newUser.extractValue("requestingUser"));
            passwordProvided = BCrypt.hashpw(String.valueOf(newUser.extractValue("passwordProvided")),
                    BCrypt.gensalt(14));
            birthAge = Date.class.cast(newUser.extractValue("birthAge"));
            email = String.valueOf(newUser.extractValue("email"));
            first_names = String.valueOf(newUser.extractValue("first_names"));
            last_names = String.valueOf(newUser.extractValue("last_names"));
            mobile = String.valueOf(newUser.extractValue("mobile"));
            gender = (AllowedGender) (newUser.extractValue("gender"));
            model = String.valueOf(newUser.extractValue("model"));
            operativeSystem = String.valueOf(newUser.extractValue("operativeSystem"));
            serial = String.valueOf(newUser.extractValue("serial"));
            version = String.valueOf(newUser.extractValue("version"));
            type = UserTypes.class.cast(newUser.extractValue("type"));

            switch (type) {
            case END_USER_TYPE:
                if (requestingUser == null) {
                    requestingUser = first_names.substring(0, 2)
                            + last_names.substring(last_names.length() - 5, last_names.length() - 1)
                            + String.valueOf(System.currentTimeMillis()).toLowerCase().toString().trim()
                                    .substring(0, 18);
                }

                requestAddress = String.valueOf(newUser.extractValue("requestAddress"));
                EndUsersPK key = new EndUsersPK();
                key.setAppUsername(requestingUser);
                EndUsers user = new EndUsers();
                user.setEndUsersPK(key);
                user.setUserNames(first_names);
                user.setLastName(last_names);
                user.setAppPassword(passwordProvided);
                user.setBirthAge(birthAge);
                user.setCreatedSince(Calendar.getInstance().getTime());
                user.setEmail(email);
                user.setMobile(mobile);
                user.setUserStatus(1);
                user.setIdUserType(new EndUserTypes(5));

                EndUsers createdUser = accessor.create(user);

                // if (validateOrigin()) {
                // Collection<UserAuthors> originData = new
                // ArrayList<UserAuthors>();
                // UserAuthors origin = new UserAuthors();
                // origin.setGadgetModel(model);
                // origin.setGadgetOs(operativeSystem);
                // origin.setGadgetSerial(serial);
                // origin.setGadgetVersion(version);
                // origin.setInternetAddress(requestAddress);
                // origin.setEndUsers(createdUser);
                // originData.add(origin);
                // createdUser.setUserAuthorsCollection(originData);
                // }
                response.setCreatedSince(Calendar.getInstance().getTime());
                response.setEmail(email);
                response.setFullName(requestingUser);
                response.setUserTypeDescription(createdUser.getIdUserType().getEndUserDescription());
                break;
            case SERVICE_PROVIDER_TYPE:
                break;
            default:
                break;
            }
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(requestingUser,
                    passwordProvided);
            authenticationManager.authenticate(token);
            String generatedToken = tokenGenerator.getToken(requestingUser, passwordProvided);
            response.setToken(generatedToken.replace("+", "%2B").replace("/", "%2F"));
            return response;
        } catch (BadCredentialsException unmatched) {
            System.out.println("unmatched");
            throw ControllerExceptionFactory.createException(unmatched.getClass().getCanonicalName(), 3,
                    newUser.getErrorProcessingValues());
        } catch (UsernameNotFoundException notfound) {
            System.out.println("notfound");
            throw ControllerExceptionFactory.createException(notfound.getClass().getCanonicalName(), 3,
                    newUser.getErrorProcessingValues());
        } catch (DisabledException unable) {
            System.out.println("unable");
            throw ControllerExceptionFactory.createException(unable.getClass().getCanonicalName(), 3,
                    newUser.getErrorProcessingValues());
        } catch (AlreadyOnSourceException duplicate) {
            throw duplicate;
        } catch (PreexistingEntityException e) {
            throw new AlreadyOnSourceException(e.getMessage());
        }
    }

    /**
     * Reset password.
     * 
     * @param changeUser
     *            the change user
     * @return the success response vo
     * @since 31/08/2014, 07:37:51 PM
     */
    @Override
    public SuccessResponseVO resetPassword(SuccessRequestVO changeUser) {
        return null;
    }
}