de.egore911.opengate.services.PilotService.java Source code

Java tutorial

Introduction

Here is the source code for de.egore911.opengate.services.PilotService.java

Source

/*
 * Copyright (c) 2013 Christoph Brill
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package de.egore911.opengate.services;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

import de.egore911.opengate.EntityManagerFilter;
import de.egore911.opengate.annotation.Documentation;
import de.egore911.opengate.model.Faction;
import de.egore911.opengate.model.Pilot;
import de.egore911.opengate.model.Vessel;

@Path("/pilot")
@Documentation("Authentication and registration for pilots")
public class PilotService {

    private static final Logger LOG = Logger.getLogger(PilotService.class.getName());

    private SecureRandom random = new SecureRandom();

    @POST
    @Path("/login/{login}")
    @Produces("application/json")
    @Documentation("Allows a pilot to log in. This method is called by the client through the server. "
            + "It returns the ID of the user and it's ship data on success. "
            + "Otherwise HTTP 404 (Not Found) will be return, or an HTTP 500 (Internal "
            + "Server Error) in case of an internal error.")
    public Response performLogin(@PathParam("login") String login, @FormParam("password") String password) {
        EntityManager em = EntityManagerFilter.getEntityManager();
        try {
            String passwordHash = hashPassword(password);
            try {
                Pilot pilot = (Pilot) em
                        .createQuery("select pilot from Pilot pilot " + "where pilot.login = :login "
                                + "and pilot.passwordHash = :passwordHash")
                        .setParameter("login", login).setParameter("passwordHash", passwordHash).getSingleResult();
                if (pilot.getVerificationCode() != null && !pilot.getVerificationCode().isEmpty()) {
                    return Response.status(Status.UNAUTHORIZED).build();
                }
                try {
                    JSONObject jsonObject = new JSONObject();
                    StatusHelper.ok(jsonObject);
                    jsonObject.put("id", pilot.getKey().getId());
                    // TODO properly wrap the vessel and its equipment/cargo
                    jsonObject.put("vessel_id", pilot.getVessel().getKey().getId());
                    return Response.ok(jsonObject.toString()).build();
                } catch (JSONException e) {
                    LOG.log(Level.SEVERE, e.getMessage(), e);
                    return Response.status(Status.INTERNAL_SERVER_ERROR).build();
                }
            } catch (NoResultException e) {
                LOG.log(Level.FINER, e.getMessage(), e);
                return Response.status(Status.NOT_FOUND).build();
            }
        } catch (NoSuchAlgorithmException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    private String hashPassword(String password) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(("Cheij3soo5ei" + password + "mohVaishei6e").getBytes());
        byte digest[] = messageDigest.digest();
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            hexString.append(Integer.toHexString(0xFF & digest[i]));
        }
        return hexString.toString();
    }

    @GET
    @Path("/login/{login}")
    @Produces("text/html")
    @Documentation("Generates a login form to be used to test the login service. The parameter login "
            + "is not used here and only neccessary to determine the POST-URL.")
    public String getLoginForm() {
        return "<html><head></head><body><form method=\"post\"><input type=\"password\" name=\"password\"><input type=\"submit\" value=\"login\" /></form></body></html>";
    }

    @POST
    @Path("/logout/{id}")
    @Produces("application/json")
    @Documentation("Allow a pilot to be logged out from the meta server. Right now it does not yet "
            + "have a purpose to log out, but will somewhere in the future.")
    public Response performLogout(@PathParam("id") Integer id) {
        try {
            JSONObject jsonObject = new JSONObject();
            StatusHelper.ok(jsonObject);
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    @GET
    @Path("/logout/{id}")
    @Produces("text/html")
    @Documentation("Generates a logout form to be used to test the login service. The parameter 'id' is "
            + "not actually used here and only neccessary to determine the POST-URL.")
    public String getLogoutForm() {
        return "<html><head></head><body><form method=\"post\"><input type=\"submit\" value=\"logout\" /></form></body></html>";
    }

    private String randomText() {
        return new BigInteger(130, random).toString(32);
    }

    @POST
    @Path("/register")
    @Produces("application/json")
    @Documentation("Register a new pilot. This will at first verify the login and email are "
            + "unique and the email is valid. After this it will register the pilot and send "
            + "and email to him to verify the address. The 'verify' will finalize the registration. "
            + "This method returns a JSON object containing a status field, i.e. {status: 'failed', "
            + "details: '...'} in case of an error and {status: 'ok', id: ...}. If an internal "
            + "error occured an HTTP 500 will be sent.")
    public Response performRegister(@FormParam("login") String login, @FormParam("email") String email,
            @FormParam("faction_id") @Documentation("ID of the faction this pilot will be working for") long factionId) {
        JSONObject jsonObject = new JSONObject();
        EntityManager em = EntityManagerFilter.getEntityManager();
        Number n = (Number) em
                .createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.login = (:login)")
                .setParameter("login", login).getSingleResult();
        if (n.intValue() > 0) {
            try {
                StatusHelper.failed(jsonObject, "Duplicate login");
                return Response.ok(jsonObject.toString()).build();
            } catch (JSONException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }

        n = (Number) em.createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.email = (:email)")
                .setParameter("email", email).getSingleResult();
        if (n.intValue() > 0) {
            try {
                StatusHelper.failed(jsonObject, "Duplicate email");
                return Response.ok(jsonObject.toString()).build();
            } catch (JSONException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }

        InternetAddress recipient;
        try {
            recipient = new InternetAddress(email, login);
        } catch (UnsupportedEncodingException e1) {
            try {
                StatusHelper.failed(jsonObject, "Invalid email");
                return Response.ok(jsonObject.toString()).build();
            } catch (JSONException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }

        Faction faction;
        try {
            faction = em.find(Faction.class, factionId);
        } catch (NoResultException e) {
            try {
                StatusHelper.failed(jsonObject, "Invalid faction");
                return Response.ok(jsonObject.toString()).build();
            } catch (JSONException e1) {
                LOG.log(Level.SEVERE, e.getMessage(), e1);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }

        Vessel vessel;
        try {
            vessel = (Vessel) em
                    .createQuery("select vessel from Vessel vessel " + "where vessel.faction = :faction "
                            + "order by vessel.techLevel asc")
                    .setParameter("faction", faction).setMaxResults(1).getSingleResult();
            // TODO assign initical equipment as well
        } catch (NoResultException e) {
            try {
                StatusHelper.failed(jsonObject, "Faction has no vessel");
                return Response.ok(jsonObject.toString()).build();
            } catch (JSONException e1) {
                LOG.log(Level.SEVERE, e.getMessage(), e1);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }

        String passwordHash;
        String password = randomText();
        try {
            passwordHash = hashPassword(password);
        } catch (NoSuchAlgorithmException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }

        em.getTransaction().begin();
        try {
            Pilot pilot = new Pilot();
            pilot.setLogin(login);
            pilot.setCreated(new Date());
            pilot.setPasswordHash(passwordHash);
            pilot.setEmail(email);
            pilot.setFaction(faction);
            pilot.setVessel(vessel);
            pilot.setVerificationCode(randomText());
            em.persist(pilot);
            em.getTransaction().commit();
            try {
                // send e-mail to registered user containing the new password

                Properties props = new Properties();
                Session session = Session.getDefaultInstance(props, null);

                String msgBody = "Welcome to opengate!\n\nSomeone, propably you, registered the user "
                        + pilot.getLogin()
                        + " with your e-mail adress. The following credentials can be used for your account:\n"
                        + "  login : " + pilot.getLogin() + "\n" + "  password : " + password + "\n\n"
                        + "To log into the game you need to verify your account using the following link: http://opengate-meta.appspot.com/services/pilot/verify/"
                        + pilot.getLogin() + "?verification=" + pilot.getVerificationCode();

                try {
                    Message msg = new MimeMessage(session);
                    msg.setFrom(new InternetAddress("egore911@gmail.com", "Opengate administration"));
                    msg.addRecipient(Message.RecipientType.TO, recipient);
                    msg.setSubject("Your Example.com account has been activated");
                    msg.setText(msgBody);
                    Transport.send(msg);

                } catch (AddressException e) {
                    LOG.log(Level.SEVERE, e.getMessage(), e);
                    return Response.status(Status.INTERNAL_SERVER_ERROR).build();
                } catch (MessagingException e) {
                    LOG.log(Level.SEVERE, e.getMessage(), e);
                    return Response.status(Status.INTERNAL_SERVER_ERROR).build();
                } catch (UnsupportedEncodingException e) {
                    LOG.log(Level.SEVERE, e.getMessage(), e);
                    return Response.status(Status.INTERNAL_SERVER_ERROR).build();
                }

                StatusHelper.ok(jsonObject);
                jsonObject.put("id", pilot.getKey().getId());
                jsonObject.put("vessel_id", pilot.getVessel().getKey().getId());
                // TODO properly wrap the vessel and its equipment/cargo
                return Response.ok(jsonObject.toString()).build();
            } catch (JSONException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        } catch (NoResultException e) {
            return Response.status(Status.FORBIDDEN).build();
        } finally {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
        }
    }

    @GET
    @Path("/register")
    @Produces("text/html")
    @Documentation("Generates a login form to be used to test the registration service.")
    public String getRegisterForm() {
        StringBuilder buffer = new StringBuilder();
        buffer.append(
                "<html><head></head><body><form method=\"post\"><table><tr><th>Login:</th><td><input type=\"login\" name=\"login\"></td></tr><tr><th>E-Mail:</th><td><input type=\"email\" name=\"email\"></td></tr><tr><th>Faction:</th><td><select name=\"faction_id\">");
        EntityManager em = EntityManagerFilter.getEntityManager();
        List<Faction> factions = em.createQuery("select faction from Faction faction order by name")
                .getResultList();
        for (Faction faction : factions) {
            buffer.append("<option value=\"");
            buffer.append(faction.getKey().getId());
            buffer.append("\">");
            buffer.append(faction.getName());
            buffer.append("</option>");
        }
        buffer.append(
                "</select></td></tr><tr><td></td><td><input type=\"submit\"></td></tr></table></form></body></html>");
        return buffer.toString();
    }

    @GET
    @Path("/verify/{login}")
    @Produces("text/html")
    @Documentation("Verify a pilots email address. This URL is sent to the pilot after registration and is the final step to complete the registration. If the email could not be verified (e.g. duplicate verification) it will return a HTTP 400 (Bad Request).")
    public Response getVerifyForm(@PathParam("login") String login,
            @QueryParam("verification") @Documentation("The random generated verification code sent by mail to the user") String verificationCode) {
        if (verificationCode == null || verificationCode.isEmpty()) {
            return Response.ok(
                    "<html><head></head><body><form method=\"post\"><input type=\"verification\"></form></body></html>")
                    .build();
        } else {
            EntityManager em = EntityManagerFilter.getEntityManager();
            try {
                Pilot pilot = (Pilot) em
                        .createQuery("select pilot from Pilot pilot " + "where pilot.login = :login "
                                + "and pilot.verificationCode = :verificationCode")
                        .setParameter("login", login).setParameter("verificationCode", verificationCode)
                        .getSingleResult();
                pilot.setVerificationCode(null);
                pilot.setModified(new Date());
                em.merge(pilot);
                return Response.ok("E-Mail adress has been verified. You can log into the game now.").build();
            } catch (NoResultException e) {
                return Response.status(Status.BAD_REQUEST).build();
            }
        }
    }

}