zallery/src/zall/manager/AuthenticationManager.java

91 lines
2.9 KiB
Java
Raw Normal View History

package zall.manager;
import zall.Zallery;
import zall.ZalleryConstant;
import zall.bean.Folder;
import zall.bean.Media;
import zall.bean.User;
import zutil.Hasher;
import zutil.db.DBConnection;
import zutil.log.LogUtil;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.logging.Logger;
/**
*
*/
public class AuthenticationManager {
private static final Logger logger = LogUtil.getLogger();
/**
* Authenticate a username and password and return the associated Uaer object
*/
public static User authenticate(DBConnection db, String email, String password) throws SQLException {
User authenticatedUser = null;
User user = User.load(db, email);
// Valid email?
if( user != null ){
if (user.getPassword().equals(Hasher.MD5(password))) {
authenticatedUser = user;
authenticatedUser.setAuthBy(User.AuthType.USER_INPUT);
authenticatedUser.save(db);
logger.info("User(" + authenticatedUser.getName() + ") authenticated by "+authenticatedUser.getAuthBy());
}
}
return authenticatedUser;
}
/**
* @return true if the user has a valid authentication session
*/
public static boolean valid(User user, HttpServletRequest request) {
if(user == null)
return false;
if(!user.isEnabled())
return false;
if(user.getSessionHash() == null || user.getSessionHash().isEmpty() )
return false;
switch( user.getAuthBy() ){
case USER_INPUT:
if (!user.isEmailVerified()) return false;
case COOKIE:
String cookieHash = Zallery.getCookieValue(request.getCookies(), ZalleryConstant.SESSION_KEY_AUTH_HASH);
return user.getSessionHash().equals(cookieHash) &&
user.getIpHost().equals( request.getRemoteAddr() );
}
return false;
}
/**
* @return true if the specified user can edit the media
*/
public static boolean canEdit(User user, Media target) {
return target != null && (user.isSuperUser() || target.getUser().equals(user));
}
/**
* @return true if the specified user can edit the media
*/
public static boolean canEdit(User user, Folder target) {
return target != null && (user.isSuperUser() || user.equals( target.getUser() ));
}
/**
* @return true if the specified user can edit the profile of the other user
*/
public static boolean canEdit(User user, User target){
return user.equals( target ) || user.isSuperUser();
}
/**
* Reset the user authentication. In plain word: logout user.
*/
public static void reset(DBConnection db, User user) throws SQLException {
user.setSessionHash(null);
user.save(db);
}
}