panagiota.koltsida 7 years ago
parent 61598eb0fe
commit ca5e8bea23

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Google</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry kind="src" path="target/m2e-wtp/web-resources"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>

@ -0,0 +1,4 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding/<project>=UTF-8

@ -0,0 +1,8 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7

@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="google-hook-login-portlet">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<dependent-module archiveName="checkAdditionalEmails-1.0.0-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/checkAdditionalEmails/checkAdditionalEmails">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="java-output-path" value="/Google/target/classes"/>
<property name="context-root" value="Google-login-hook"/>
</wb-module>
</project-modules>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="jst.web" version="2.4"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="liferay.hook" version="6.0"/>
<installed facet="java" version="1.7"/>
</faceted-project>

@ -0,0 +1 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

@ -0,0 +1,11 @@
DELEGATES_PREFERENCE=delegateValidatorList
USER_BUILD_PREFERENCE=enabledBuildValidatorList
USER_MANUAL_PREFERENCE=enabledManualValidatorList
USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.700.v201508251749
disabled=06target
eclipse.preferences.version=1
override=true
suspend=false
vals/org.eclipse.jst.jsp.core.JSPBatchValidator/groups=0107include01113projectNature131org.eclipse.jdt.core.javanature0107include110111contentType134org.eclipse.jst.jsp.core.jspsourceT111contentType142org.eclipse.jst.jsp.core.jspfragmentsourceT111contentType134org.eclipse.jst.jsp.core.tagsourceT07fileext03jspF07fileext04jspfF07fileext03jsfF07fileext03tagF07fileext04tagfF07fileext03jsvF07fileext04jtplF0107exclude0104file127src/main/webapp/custom_jspsT02
vals/org.eclipse.jst.jsp.core.JSPContentValidator/groups=0107include09111contentType134org.eclipse.jst.jsp.core.jspsourceT111contentType142org.eclipse.jst.jsp.core.jspfragmentsourceT07fileext03jspF07fileext04jspfF07fileext03jsfF07fileext03tagF07fileext04tagfF07fileext03jsvF07fileext04jtplF0107exclude0104file127src/main/webapp/custom_jspsF02
vf.version=3

@ -0,0 +1 @@
${gcube.license}

@ -0,0 +1,66 @@
The gCube System - ${name}
--------------------------------------------------
${description}
${gcube.description}
${gcube.funding}
Version
--------------------------------------------------
${version} (${buildDate})
Please see the file named "changelog.xml" in this directory for the release notes.
Authors
--------------------------------------------------
* Michalis Nikolopoulos (mnikolopoulos@cite.gr), CITE S.A.
Maintainers
-----------
* Michalis Nikolopoulos (mnikolopoulos@cite.gr), CITE S.A.
Download information
--------------------------------------------------
Source code is available from SVN:
${scm.url}
Binaries can be downloaded from the gCube website:
${gcube.website}
Installation
--------------------------------------------------
Use the respective war
Documentation
--------------------------------------------------
Documentation is available on-line in the gCube Wiki:
${gcube.wikiRoot}
Support
--------------------------------------------------
Bugs and support requests can be reported in the gCube issue tracking tool:
${gcube.issueTracking}
Licensing
--------------------------------------------------
This software is licensed under the terms you may find in the file named "LICENSE" in this directory.

@ -0,0 +1,11 @@
<ReleaseNotes>
<Changeset component="gr.cite.google.1-0-0" date="2016-03-15">
<Change>First release of the google authentication hook</Change>
</Changeset>
<Changeset component="gr.cite.google.1-1-0" date="2016-09-25">
<Change>Updated to work with the multiple email addresses authentication mechanism</Change>
</Changeset>
<Changeset component="gr.cite.google.1-1-1" date="2016-12-13">
<Change>Fixed a bug concerning users with no google+ available where the authenticated response did not include given and family names</Change>
</Changeset>
</ReleaseNotes>

@ -0,0 +1,31 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<directory>${distroDirectory}</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README</include>
<include>LICENSE</include>
<include>changelog.xml</include>
<include>profile.xml</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
</fileSets>
<files>
<file>
<source>target/${build.finalName}.war</source>
<outputDirectory>/${artifactId}</outputDirectory>
</file>
</files>
</assembly>

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID />
<Type>Service</Type>
<Profile>
<Description>${description}</Description>
<Class>Portal</Class>
<Name>${artifactId}</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<MavenCoordinates>
<groupId>${groupId}</groupId>
<artifactId>${artifactId}</artifactId>
<version>${version}</version>
</MavenCoordinates>
<Files>
<File>${build.finalName}.war</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

@ -0,0 +1,149 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.0.0</version>
<relativePath />
</parent>
<groupId>gr.cite.google</groupId>
<artifactId>Google-login-hook</artifactId>
<packaging>war</packaging>
<name>Google Login Hook</name>
<description>
The Google hook allows users to login with their Google credentials to a liferay portal
</description>
<version>1.2.0-SNAPSHOT</version>
<scm>
<connection>scm:svn:http://svn.cite.gr/code-bluebridge/google-hook</connection>
<developerConnection>scm:http://svn.cite.gr/code-bluebridge/google-hook</developerConnection>
<url>http://svn.cite.gr/code-bluebridge/google-hook</url>
</scm>
<properties>
<liferay.version>6.2.2</liferay.version>
<liferay.auto.deploy.dir>${system.CATALINA_HOME}/../deploy</liferay.auto.deploy.dir>
<distroDirectory>${project.basedir}/distro</distroDirectory>
</properties>
<build>
<plugins>
<!-- <plugin> <groupId>com.liferay.maven.plugins</groupId> <artifactId>liferay-maven-plugin</artifactId>
<version>${liferay.maven.plugin.version}</version> <configuration> <autoDeployDir>${liferay.auto.deploy.dir}</autoDeployDir>
<appServerDeployDir>${liferay.app.server.deploy.dir}</appServerDeployDir>
<appServerLibGlobalDir>${liferay.app.server.lib.global.dir}</appServerLibGlobalDir>
<appServerPortalDir>${liferay.app.server.portal.dir}</appServerPortalDir>
<liferayVersion>${liferay.version}</liferayVersion> <pluginType>hook</pluginType>
</configuration> </plugin> -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>servicearchive</id>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>maven-portal-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>portal-service</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>util-java</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.portlet</groupId>
<artifactId>portlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- scribe -->
<dependency>
<groupId>com.github.scribejava</groupId>
<artifactId>scribejava-apis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>landing-page-library</artifactId>
<version>[1.0.0-SNAPSHOT,)</version>
</dependency>
<dependency>
<groupId>gr.cite.additionalemailaddresses</groupId>
<artifactId>checkAdditionalEmails</artifactId>
<version>[1.0.0-SNAPSHOT,2.0.0-SNAPSHOT)</version>
</dependency>
</dependencies>
</project>

@ -0,0 +1,73 @@
package gr.cite.google;
import gr.cite.google.util.GoogleConstantVariables;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.PrefsPropsUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.BaseAutoLogin;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class GoogleAutoLogin extends BaseAutoLogin {
private static final Log log = LogFactoryUtil.getLog(GoogleOAuth.class);
@Override
protected String[] doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
long companyId = PortalUtil.getCompanyId(request);
boolean googleAuthEnabled = PrefsPropsUtil.getBoolean(companyId, GoogleConstantVariables.GOOGLE_LOGIN_ENABLED, true);
log.debug("Is google enabled: " + googleAuthEnabled);
if (!googleAuthEnabled) {
return null;
}
User user = getUser(request, companyId);
if (user == null) {
return null;
}
String[] credentials = new String[3];
credentials[0] = String.valueOf(user.getUserId());
credentials[1] = user.getPassword();
credentials[2] = Boolean.TRUE.toString();
return credentials;
}
protected User getUser(HttpServletRequest request, long companyId) throws PortalException, SystemException {
HttpSession session = request.getSession();
String emailAddress = GetterUtil.getString(session.getAttribute(GoogleConstantVariables.USER_EMAIL_ADDRESS_FOR_SESSION_GOOGLE));
session.removeAttribute(GoogleConstantVariables.USER_EMAIL_ADDRESS_FOR_SESSION_GOOGLE);
log.debug("User's mail form session: " + emailAddress);
if (Validator.isNull(emailAddress)) {
return null;
}
User user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);
return user;
}
public static Log getLog() {
return log;
}
}

@ -0,0 +1,175 @@
package gr.cite.google;
import gr.cite.additionalemailaddresses.CheckAdditionalEmailAddresses;
import gr.cite.google.model.GoogleJson;
import gr.cite.google.util.GoogleConstantVariables;
import gr.cite.google.util.LoginHookEssentialMethods;
import java.io.IOException;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.gcube.portal.landingpage.LandingPageManager;
import com.github.scribejava.apis.GoogleApi20;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.google.gson.Gson;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.struts.BaseStrutsAction;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PrefsPropsUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
public class GoogleOAuth extends BaseStrutsAction {
private static final Log log = LogFactoryUtil.getLog(GoogleOAuth.class);
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
String returnFromGoogleUrl = PortalUtil.getPortalURL(request) + PropsUtil.get(GoogleConstantVariables.RETURN_FROM_GOOGLE_URL);
String googleClientId = PrefsPropsUtil.getString(themeDisplay.getCompanyId(), GoogleConstantVariables.GOOGLE_CLIENT_ID, PropsUtil.get(GoogleConstantVariables.GOOGLE_CLIENT_ID));
String googleClientSecret = PrefsPropsUtil.getString(themeDisplay.getCompanyId(), GoogleConstantVariables.GOOGLE_CLIENT_SECRET, PropsUtil.get(GoogleConstantVariables.GOOGLE_CLIENT_SECRET));
Boolean canCreateAccount = PrefsPropsUtil.getBoolean(themeDisplay.getCompanyId(), PropsKeys.COMPANY_SECURITY_STRANGERS);
User user = null;
String landingPage = "";
//Initial call to the hook and redirection to google
if (ParamUtil.getString(request, Constants.CMD).equals("login")){
log.debug("Initial call for login...");
establishConnectionWithGoogle(session, response, returnFromGoogleUrl, googleClientId, googleClientSecret);
//Answer from google with the data we need
} else if (ParamUtil.getString(request, Constants.CMD).equals("token")){
String oauthCode = ParamUtil.getString(request, GoogleConstantVariables.OAUTH_CODE);
log.debug("User gave permision to read data...");
log.debug("google oauthCode -> " + oauthCode);
if (Validator.isNull(oauthCode)) {
//System.out.println("validator is null for oauthCode");
return null;
}
GoogleJson googleUserInfo = retrieveUsersGoogleInfo(oauthCode, returnFromGoogleUrl, googleClientId, googleClientSecret);
if (googleUserInfo == null){
throw new LoginException();
}
log.debug("Google's object: " + googleUserInfo.toString());
try {
user = CheckAdditionalEmailAddresses.checkInIfAdditionalEmailAndIfVerified(googleUserInfo.getEmail());
} catch (Exception e) {
log.error("Error occured while searching in additional emails", e);
e.printStackTrace();
throw e;
}
if(user != null){
log.info("Email " + googleUserInfo.getEmail() + " has been found in additional Email Addresses");
session.setAttribute(GoogleConstantVariables.USER_EMAIL_ADDRESS_FOR_SESSION_GOOGLE, user.getEmailAddress());
}else if (canCreateAccount){
LoginHookEssentialMethods.addUser(session, themeDisplay.getCompanyId(), googleUserInfo);
user = UserLocalServiceUtil.getUserById(UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), googleUserInfo.getEmail()).getUserId());
}else{
try{
user = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), googleUserInfo.getEmail());
log.debug("Login user " + user.getFullName() + " email address " + user.getEmailAddress());
session.setAttribute(GoogleConstantVariables.USER_EMAIL_ADDRESS_FOR_SESSION_GOOGLE, user.getEmailAddress());
}catch (PortalException e){
SessionErrors.add(session, NoSuchUserException.class);
}
}
//ensure the user is redirected to the requested page before logging in
if (session.getAttribute("redirectUrlAfterLogin") != null && session.getAttribute("redirectUrlAfterLogin").toString().compareTo("") != 0) {
landingPage = session.getAttribute("redirectUrlAfterLogin").toString();
session.setAttribute("redirectUrlAfterLogin", null);
}
else {
landingPage = LandingPageManager.getLandingPagePath(request, user);
}
//landingPage = LandingPageManager.getLandingPagePath(request, user);
response.sendRedirect(landingPage);
}
return null;
}
/**
*
* Initial call to google, in order to retrieve authorization code.
*
* @param response
* @param returnFromLinkedInUrl
* @throws IOException
*/
private void establishConnectionWithGoogle(HttpSession session, HttpServletResponse response, String returnFromGoogleUrl, String googleClientId, String googleClientSecret) throws IOException {
OAuth20Service service = new ServiceBuilder().apiKey(googleClientId).apiSecret(googleClientSecret).callback(returnFromGoogleUrl).scope(GoogleConstantVariables.API_CALL_SCOPE).build(GoogleApi20.instance());
String googleAuthUrl = service.getAuthorizationUrl();
log.debug("Google Auth URL -> " + googleAuthUrl);
response.sendRedirect(googleAuthUrl);
}
/**
*
* Using authorization code, we get access token and make the API call we need to retrieve data
* from google.
*
* @param oauthCode
* @param returnFromGoogleUrl
* @return GoogleJson
* @throws IOException
*/
private GoogleJson retrieveUsersGoogleInfo(String oauthCode, String returnFromGoogleUrl, String googleClientId, String googleClientSecret) throws IOException {
OAuth20Service service = new ServiceBuilder().apiKey(googleClientId).apiSecret(googleClientSecret).callback(returnFromGoogleUrl).scope(GoogleConstantVariables.API_CALL_SCOPE).build(GoogleApi20.instance());
//Verifier verifier = new Verifier(oauthCode);
OAuth2AccessToken accessToken = service.getAccessToken(oauthCode);
//OAuth2AccessToken accessToken, AbstractRequest request
OAuthRequest authRequest = new OAuthRequest(Verb.GET, GoogleConstantVariables.API_CALL, service);
service.signRequest(accessToken, authRequest);
String bodyResponse = authRequest.send().getBody();
log.trace("Google oauth body response -> " + bodyResponse);
GoogleJson googleJson = new Gson().fromJson(bodyResponse, GoogleJson.class);
return googleJson;
}
}

@ -0,0 +1,42 @@
package gr.cite.google.model;
import com.google.gson.annotations.SerializedName;
/**
* @author mnikolopoulos
*
* This is the data we deserialize, in case we need more/different data from the google,
* we can check their API and make the appropriate changes here and maybe to the the actual call
* and to the scope as well if needed.
*
*/
public class GoogleJson {
private String email;
@SerializedName("given_name")
private String givenName;
@SerializedName("family_name")
private String familyName;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
}

@ -0,0 +1,32 @@
package gr.cite.google.util;
public class GoogleConstantVariables {
public final static String REDIRECT_URL_AFTER_LOGIN = "redirectUrlAfterLogin";
public final static String USER_EMAIL_ADDRESS_FOR_SESSION_GOOGLE = "userEmailAdressGoogle";
public final static String GOOGLE_CLIENT_ID = "google.client.id";
public final static String GOOGLE_CLIENT_SECRET = "google.client.secret";
public final static String OAUTH_CODE = "code";
public final static String OAUTH_TOKEN = "oauth_token";
public final static String REQUEST_TOKEN_SECRET_GOOGLE = "requestTokenSecretGoogle";
public final static String API_CALL = "https://www.googleapis.com/oauth2/v2/userinfo";
public final static String RETURN_FROM_GOOGLE_URL = "google.hook.callback.url";
public final static String GOOGLE_LOGIN_ENABLED = "google.auth.enabled";
//public final static String API_CALL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
public final static String API_CALL_SCOPE = "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email";
public final static String OAUTH_SERVICE_OBJECT = "oAuthService";
}

@ -0,0 +1,139 @@
package gr.cite.google.util;
import gr.cite.google.model.GoogleJson;
import gr.cite.google.util.GoogleConstantVariables;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
import javax.portlet.WindowStateException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.liferay.portal.DuplicateUserEmailAddressException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.LiferayWindowState;
import com.liferay.portal.kernel.util.LocaleUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortletKeys;
import com.liferay.portlet.PortletURLFactoryUtil;
public class LoginHookEssentialMethods {
private static final Log log = LogFactoryUtil.getLog(LoginHookEssentialMethods.class);
/**
*
* Try to add new user to portal, then set user's email address in session.
*
*
* @param session
* @param companyId
* @param googleJson
* @return User
* @throws SystemException, PortalException, EmailAddressException
*/
public static User addUser(HttpSession session, long companyId, GoogleJson googleJson) throws PortalException, SystemException {
User user = null;
long creatorUserId = 0;
boolean autoPassword = true;
String password1 = StringPool.BLANK;
String password2 = StringPool.BLANK;
boolean autoScreenName = true;
String screenName = StringPool.BLANK;
String emailAddress = googleJson.getEmail();
String openId = StringPool.BLANK;
Locale locale = LocaleUtil.getDefault();
String givenName = googleJson.getGivenName();
String firstName = " ";
if (givenName != null)
firstName = givenName;
String middleName = StringPool.BLANK;
String familyName = googleJson.getFamilyName();
String lastName = " ";
if (familyName != null)
lastName = familyName;
int prefixId = 0;
int suffixId = 0;
boolean male = false;
int birthdayMonth = Calendar.JANUARY;
int birthdayDay = 1;
int birthdayYear = 1970;
String jobTitle = StringPool.BLANK;
long[] groupIds = null;
long[] organizationIds = null;
long[] roleIds = null;
long[] userGroupIds = null;
boolean sendEmail = true;
ServiceContext serviceContext = new ServiceContext();
try{
user = UserLocalServiceUtil.addUser(creatorUserId, companyId,
autoPassword, password1, password2, autoScreenName, screenName,
emailAddress, 0, openId, locale, firstName, middleName,
lastName, prefixId, suffixId, male, birthdayMonth, birthdayDay,
birthdayYear, jobTitle, groupIds, organizationIds, roleIds,
userGroupIds, sendEmail, serviceContext);
user = UserLocalServiceUtil.updateLastLogin(user.getUserId(),user.getLoginIP());
user = UserLocalServiceUtil.updatePasswordReset(user.getUserId(), false);
user = UserLocalServiceUtil.updateEmailAddressVerified(user.getUserId(), true);
log.info("New user was created. Login new user with current credentials");
}catch (DuplicateUserEmailAddressException e){
log.info("User with the same email address already exists. Login user with said mail.");
}
session.setAttribute(GoogleConstantVariables.USER_EMAIL_ADDRESS_FOR_SESSION_GOOGLE, emailAddress);
return user;
}
/**
*
* Redirects User to appropriate portal page.
*
* @param response
* @param redirectUrlCustom is the portal page user would visit if user was already logged in
* @param redirectUrlDefault is the default landing page of the portal, which is a fall-back in case of empty redirectUrlCustom
* @throws IOException
* @throws SystemException
* @throws PortalException
* @throws WindowStateException
* @throws PortletModeException
*/
public static void reditectUserToHisPage(HttpServletResponse response, HttpServletRequest request, String redirectUrlCustom, String redirectUrlDefault) throws PortletModeException, WindowStateException, IOException {
ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
PortletURL portletURL = PortletURLFactoryUtil.create(request, PortletKeys.LOGIN, themeDisplay.getPlid(), PortletRequest.RENDER_PHASE);
portletURL.setPortletMode(PortletMode.VIEW);
portletURL.setWindowState(LiferayWindowState.POP_UP);
portletURL.setParameter("redirect", redirectUrlCustom);
portletURL.setParameter("struts_action", "/login/login_redirect");
response.sendRedirect(portletURL.toString());
}
}

@ -0,0 +1,7 @@
google=Google
google-client-id=Client Id
google-client-secret=Client Secret
google-client-id-helpMessage=Fill this field with the client id google has provided you with
google-client-secret-helpMessage=Fill this field with client secret google has provided you with
google-enable=Check, if you want to use google login, otherwise uncheck
sign-in-with-google=Sign up with Google

@ -0,0 +1,26 @@
# Add Google as a tab for configuration
company.settings.form.authentication=google
# Make this struts path public accessible
auth.public.paths=/portal/google_login
# Set Google's authentication Class
auto.login.hooks=gr.cite.google.GoogleAutoLogin
# Add Google to navigation bar at login
# if using the custom login hook then you can safely remove
# this option but you need to concatenate the value 'google' to the login.form.navigation.socials
# option in the login-hook.
# if not using the custom login hook, this option should be enabled in order to have google as a login method.
# login.form.navigation.post=google
#google initial call to create the login connection
google.hook.call.url=/c/portal/google_login?cmd=login
# Callback url after logging in to google
google.hook.callback.url=/c/portal/google_login?cmd=token
# Google Authentication configuration
google.auth.enabled=true
google.client.id=
google.client.secret=

@ -0,0 +1,21 @@
<?xml version="1.0"?>
<!DOCTYPE hook PUBLIC "-//Liferay//DTD Hook 6.2.0//EN" "http://www.liferay.com/dtd/liferay-hook_6_2_0.dtd">
<hook>
<!-- The specified contains new configuration and/or overrides already existing configuration for the portal -->
<portal-properties>portal.properties</portal-properties>
<!-- The specified file contains the language -->
<language-properties>content/Language.properties</language-properties>
<!-- Specify the jsp directory that contains overridden jsps and new jsps -->
<custom-jsp-dir>/custom_jsps</custom-jsp-dir>
<!-- Create a new struts action -->
<struts-action>
<struts-action-path>/portal/google_login</struts-action-path>
<struts-action-impl>gr.cite.google.GoogleOAuth</struts-action-impl>
</struts-action>
</hook>

@ -0,0 +1,9 @@
name=Google
module-group-id=liferay
module-incremental-version=1
tags=
short-description=
change-log=
page-url=http://www.liferay.com
author=Liferay, Inc.
licenses=LGPL

@ -0,0 +1,4 @@
<?xml version="1.0"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
</web-app>

@ -0,0 +1,42 @@
.social-hook div[class*="-hook-icon"] {
display: inline-block;
padding: 0px 6px;
color: white;
margin-right: -5px;
box-shadow: 2px 0px 8px -2px rgba(0,0,0,0.7), -2px 1px 1px 1px rgba(0,0,0,0.3);
z-index: 10;
position: relative;
width: 10%
}
.social-hook div[class$="-hook-text"] {
display: inline-block;
padding: 0px 10px;
border-radius: 0px 5px 5px 0px;
color: white;
box-shadow: 1px 1px 3px 1.5px rgba(0,0,0,0.3);
width: 50%;
}
.social-hook a[class$="-hook-link"] {
text-align: center;
}
.social-hook div[class$="-hook-label-wrapper"]{
white-space: nowrap;
}
.social-hook div[class$="-hook-label-wrapper"]:hover{
opacity : 0.85;
}
.social-hook .google-hook-text, .social-hook .google-hook-icon{
background-color: rgb(209, 72, 54);
}
@media (max-width: 480px) {
.social-hook div[class$="-hook-text"] {
min-width: 50%;
width: inherit;
}
}

@ -0,0 +1,56 @@
<%@ include file="/html/portlet/login/init.jsp" %>
<%@ page import="com.liferay.portal.util.PortalUtil" %>
<link rel="stylesheet" href="/html/portlet/login/css/google.css">
<!-- initialize variables for google login request -->
<%
boolean isGoogleAuthEnabled = PrefsPropsUtil.getBoolean(company.getCompanyId(), "google.auth.enabled", true);
String googleLoginUrl = PortalUtil.getPathContext().toString() + PropsUtil.get("google.hook.call.url");
String redirect = ParamUtil.getString(request, "redirect");
session.setAttribute("redirectUrlAfterLogin", redirect);
String[] navSocialsArray = PropsUtil.getArray("login.form.navigation.socials");
String[] navPostsArray = PropsUtil.getArray("login.form.navigation.post");
Set<String> navSocialsSet = new HashSet<String>(Arrays.asList(navSocialsArray));
Set<String> navPostsSet = new HashSet<String>(Arrays.asList(navPostsArray));
Boolean inSocials = navSocialsSet.contains("google");
Boolean inPosts = navPostsSet.contains("google");
%>
<c:if test="<%= isGoogleAuthEnabled %>">
<div class="social-hook">
<c:choose>
<c:when test="<%= inSocials %>">
<a href="<%= googleLoginUrl.toString() %>" class="google-hook-link">
<div class="google-hook-label-wrapper">
<div class="google-hook-icon">
<h5>
<i class="icon-google-plus"></i>
</h5>
</div>
<div class="google-hook-text">
<h5>
<%= LanguageUtil.get(pageContext, "sign-in-with-google")%>
</h5>
</div>
</div>
</a>
</c:when>
<c:when test="<%= inPosts %>">
<liferay-ui:icon
message="google"
src="/html/portlet/login/navigation/google.png"
url="<%= googleLoginUrl.toString() %>"
/>
</c:when>
</c:choose>
</div>
</c:if>

Binary file not shown.

After

Width:  |  Height:  |  Size: 661 B

@ -0,0 +1,25 @@
<!--
A configuration page for client id and client secret, in case they need to be changedl.
Additionally there is a checkbox to disable google hook.
-->
<%@ include file="/html/portlet/portal_settings/init.jsp" %>
<%
boolean isGoogleAuthEnabled = PrefsPropsUtil.getBoolean(company.getCompanyId(), "google.auth.enabled", true);
String googleClientId = PrefsPropsUtil.getString(company.getCompanyId(), "google.client.id");
String googleClientSecret = PrefsPropsUtil.getString(company.getCompanyId(), "google.client.secret");
%>
<aui:fieldset>
<aui:input helpMessage="google-enable" label="enabled" name='<%= "settings--google.auth.enabled--" %>' type="checkbox" value='<%= isGoogleAuthEnabled %>' />
<aui:input cssClass="input-xxlarge" helpMessage="google-client-id-helpMessage" label="google-client-id" name='<%= "settings--google.client.id--" %>' type="text" value="<%= googleClientId %>" />
<aui:input cssClass="input-xxlarge" helpMessage="google-client-secret-helpMessage" label="google-client-secret" name='<%= "settings--google.client.secret--" %>' type="text" value="<%= googleClientSecret %>" />
</aui:fieldset>