package se.chalmers.dat255.grupp12;
import com.google.gson.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
/**
* Date: 2013-10-01
* Time: 12:57
*/
public class Authorization {
private static final String AUTH_URL = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=";
public static synchronized User authorize(String mail, String token) throws IOException, SQLException {
JsonObject userInfo = getUserInfo(token);
String name = userInfo.get("name").getAsString();
String googleMail = userInfo.get("email").getAsString();
System.out.println(googleMail + " == " + mail);
if (googleMail.equals(mail)) {
try {
return Database.getInstance().getUser(mail);
} catch (DataNotFoundException e) {
return Database.getInstance().insertUser(new User(name, mail));
}
} else {
return null;
}
}
private static JsonObject getUserInfo(String token) throws IOException {
URL url = new URL(AUTH_URL + token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != 200) {
throw new RuntimeException("Google returns response code: " + con.getResponseCode());
}
InputStream in = new BufferedInputStream(con.getInputStream());
java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
return new JsonParser().parse(result).getAsJsonObject();
}
}