package org.openslx.imagemaster.db.mappers; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.openslx.bwlp.thrift.iface.Role; import org.openslx.bwlp.thrift.iface.TNotFoundException; import org.openslx.bwlp.thrift.iface.UserInfo; import org.openslx.imagemaster.db.Database; import org.openslx.imagemaster.db.MysqlConnection; import org.openslx.imagemaster.db.MysqlStatement; import org.openslx.imagemaster.db.models.LocalUser; import org.openslx.imagemaster.util.Sha512Crypt; /** * Represents a user that can login against the masterserver. */ public class DbUser { private static final Logger LOGGER = Logger.getLogger( DbUser.class ); private static final String localUserSql = "SELECT" + " user.userid, user.password, user.organizationid, user.firstname, user.lastname, user.email" + " FROM user"; private static LocalUser localFromRs( ResultSet rs ) throws SQLException { return new LocalUser( rs.getString( "userid" ), rs.getString( "password" ), rs.getString( "organizationid" ), rs.getString( "firstname" ), rs.getString( "lastname" ), rs.getString( "email" ), Role.TUTOR ); } /** * Query database for user with given user id * * @param login (global user-id, login@org for test-accounts) * @return instance of DbUser for matching entry from DB, or null if not * found * @throws SQLException if the query fails */ public static LocalUser forUserId( final String login ) throws SQLException { try ( MysqlConnection connection = Database.getConnection() ) { MysqlStatement stmt = connection.prepareStatement( localUserSql + " WHERE user.userid = :userid" ); stmt.setString( "userid", login ); ResultSet rs = stmt.executeQuery(); if ( !rs.next() ) return null; return localFromRs( rs ); } catch ( SQLException e ) { LOGGER.error( "Query failed in DbUser.forLogin()", e ); throw e; } } public static LocalUser forUserId( String login, String password ) throws SQLException { LocalUser user = forUserId( login ); if ( user == null || !Sha512Crypt.verifyPassword( password, user.password ) ) return null; return user; } public static UserInfo getUserInfo( final String login ) throws SQLException, TNotFoundException { LocalUser user = forUserId( login ); if ( user == null ) throw new TNotFoundException(); return user.toUserInfo(); } public static List findUser( String organizationId, String searchTerm ) { // TODO Implement return new ArrayList<>( 0 ); } public static boolean exists( UserInfo user ) { return exists( user, false ); } public static boolean exists( UserInfo user, boolean withIdentity ) { if ( user == null ) return false; return exists( user.userId, withIdentity ); } private static boolean exists( String userId, boolean withIdentitiy ) { if ( userId == null ) return false; try { return forUserId( userId ) != null; } catch ( SQLException e ) { return false; } } }