Package com.simpletwitter.service

Source Code of com.simpletwitter.service.LoginService

package com.simpletwitter.service;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;

import com.simpletwitter.common.DatabaseManager;
import com.simpletwitter.common.PasswordHash;
import com.simpletwitter.models.TwitterUser;

public class LoginService {

  public static TwitterUser validateUser(TwitterUser tuser) {

    String username = tuser.getUsername();
    String password = tuser.getPassword();

    if (username == null && password == null) {
      return null;
    }

    if ("".equals(username) && "".equals(password)) {
      return null;
    }

    DatabaseManager da = DatabaseManager.getInstance();
    TwitterUser exm = new TwitterUser();
    exm.setUsername(tuser.getUsername());
    TwitterUser objectByExample = da.getObjectByExample(exm);
    if (objectByExample != null) {
      String expectedPassword = objectByExample.getPassword();
      if (validate(password, expectedPassword)) {
        return objectByExample;
      } else {
        return null;
      }
    } else {
      String passwordH = password;
      passwordH = getPasswordHash(password);
      tuser.setPassword(passwordH);
      return createNewUser(tuser);
    }

  }

  protected static boolean validate(String password, String expectedPassword) {
    boolean validatePassword = false;
    try {
      validatePassword = PasswordHash.validatePassword(password,
          expectedPassword);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }
    return validatePassword;
  }

  protected static String getPasswordHash(String password) {
    String createHash = password;
    try {
      createHash = PasswordHash.createHash(password);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }
    return createHash;
  }

  private static TwitterUser createNewUser(TwitterUser tuser) {
    DatabaseManager da = DatabaseManager.getInstance();
    tuser.setDateCreated(new Date());
    TwitterUser createObject = da.createObject(tuser);
    return createObject;
  }
}
TOP

Related Classes of com.simpletwitter.service.LoginService

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.