Family-Map-Project / FamilyMapServer / FamilyMapServerStudent-master / src / dao / AuthTokenDAO.java
AuthTokenDAO.java
Raw
package dao;

import model.AuthToken;
import model.Event;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * AuthToken data access object that performs operations associated with authTokens
 */
public class AuthTokenDAO
{
    private final Connection conn;

    public AuthTokenDAO(Connection conn) {this.conn = conn;}
    /**
     * Creates an AuthToken
     * @param authToken
     */
    public void createAuthToken(AuthToken authToken) throws DataAccessException
    {
        String sql = "INSERT INTO AuthTokens (username, token) VALUES(?,?)";

        try (PreparedStatement stmt = conn.prepareStatement(sql))
        {
            stmt.setString(1, authToken.getUsername());
            stmt.setString(2, authToken.getAuthToken());

            stmt.executeUpdate();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            throw new DataAccessException("Error encountered while inserting into the database");
        }
    }

    /**
     * Retrieves the username of the user associated with the authToken
     * @param token
     * @return
     */
    public String getUsername(String token) throws DataAccessException
    {
        AuthToken authToken;
        ResultSet rs = null;
        String sql = "SELECT * FROM AuthTokens WHERE token = ?;";

        try (PreparedStatement stmt = conn.prepareStatement(sql))
        {
            stmt.setString(1, token);
            rs = stmt.executeQuery();
            if (rs.next())
            {
                authToken = new AuthToken(rs.getString("username"), rs.getString("token"));

                return authToken.getUsername();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            throw new DataAccessException("Error encountered while finding event");
        }
        finally
        {
            if(rs != null)
            {
                try
                {
                    rs.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    /**
     * Removes all the tokens from the database
     */
    public void removeAllTokens() throws DataAccessException
    {
        String sql = "DELETE FROM AuthTokens";

        try(PreparedStatement stmt = conn.prepareStatement(sql))
        {
            stmt.executeUpdate();
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            throw new DataAccessException("Error encountered while deleting from the database");
        }
    }
}