Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial commit

  • Loading branch information...
commit 2d13a24cfd55fb2f4cc87cda24b84a8e1d085e95 1 parent 3b2633b
@jaliss authored
Showing with 4,335 additions and 0 deletions.
  1. +175 −0 LICENSE.txt
  2. +23 −0 README
  3. +8 −0 Readme-Icons.txt
  4. +178 −0 app/controllers/securesocial/SecureSocial.java
  5. +134 −0 app/controllers/securesocial/UsernamePasswordController.java
  6. +50 −0 app/notifiers/securesocial/Mails.java
  7. +93 −0 app/securesocial/jobs/Bootstrap.java
  8. +35 −0 app/securesocial/jobs/PendingActivationsJobs.java
  9. +29 −0 app/securesocial/provider/AccessDeniedException.java
  10. +39 −0 app/securesocial/provider/AuthenticationException.java
  11. +28 −0 app/securesocial/provider/AuthenticationMethod.java
  12. +70 −0 app/securesocial/provider/DefaultUserService.java
  13. +129 −0 app/securesocial/provider/IdentityProvider.java
  14. +116 −0 app/securesocial/provider/OAuth1Provider.java
  15. +155 −0 app/securesocial/provider/OAuth2Provider.java
  16. +136 −0 app/securesocial/provider/OpenIDOAuthHybridProvider.java
  17. +119 −0 app/securesocial/provider/OpenIDProvider.java
  18. +69 −0 app/securesocial/provider/ProviderRegistry.java
  19. +32 −0 app/securesocial/provider/ProviderType.java
  20. +90 −0 app/securesocial/provider/SocialUser.java
  21. +33 −0 app/securesocial/provider/UserId.java
  22. +139 −0 app/securesocial/provider/UserService.java
  23. +61 −0 app/securesocial/provider/providers/FacebookProvider.java
  24. +91 −0 app/securesocial/provider/providers/FoursquareProvider.java
  25. +70 −0 app/securesocial/provider/providers/GoogleProvider.java
  26. +65 −0 app/securesocial/provider/providers/LinkedInProvider.java
  27. +58 −0 app/securesocial/provider/providers/MyOpenIDProvider.java
  28. +56 −0 app/securesocial/provider/providers/TwitterProvider.java
  29. +101 −0 app/securesocial/provider/providers/UsernamePasswordProvider.java
  30. +89 −0 app/securesocial/provider/providers/WordpressProvider.java
  31. +58 −0 app/securesocial/provider/providers/YahooProvider.java
  32. +6 −0 app/views/securesocial/Mails/sendActivationEmail.html
  33. +96 −0 app/views/securesocial/SecureSocial/login.html
  34. +30 −0 app/views/securesocial/SecureSocial/main.html
  35. +16 −0 app/views/securesocial/SecureSocial/noticePage.html
  36. +83 −0 app/views/securesocial/UsernamePasswordController/signup.html
  37. +49 −0 build.xml
  38. +35 −0 commands.py
  39. BIN  commands.pyc
  40. +4 −0 conf/dependencies.yml
  41. +47 −0 conf/messages
  42. +25 −0 conf/routes
  43. BIN  documentation/images/loginPage.png
  44. BIN  documentation/images/signUpPage.png
  45. +247 −0 documentation/manual/home.textile
  46. BIN  public/images/providers/facebook.png
  47. BIN  public/images/providers/foursquare.png
  48. BIN  public/images/providers/google.png
  49. BIN  public/images/providers/linkedin.png
  50. BIN  public/images/providers/myopenid.png
  51. BIN  public/images/providers/twitter.png
  52. BIN  public/images/providers/wordpress.png
  53. BIN  public/images/providers/yahoo.png
  54. +330 −0 public/stylesheets/bootstrap-1.3.0/bootstrap.min.css
  55. +12 −0 samples-and-tests/testapp/app/controllers/Application.java
  56. +35 −0 samples-and-tests/testapp/app/views/Application/index.html
  57. +19 −0 samples-and-tests/testapp/app/views/errors/404.html
  58. +21 −0 samples-and-tests/testapp/app/views/errors/500.html
  59. +31 −0 samples-and-tests/testapp/app/views/main.html
  60. +296 −0 samples-and-tests/testapp/conf/application.conf
  61. +12 −0 samples-and-tests/testapp/conf/dependencies.yml
  62. +3 −0  samples-and-tests/testapp/conf/messages
  63. +18 −0 samples-and-tests/testapp/conf/routes
  64. +1 −0  samples-and-tests/testapp/modules/securesocial
  65. BIN  samples-and-tests/testapp/public/images/favicon.png
  66. +16 −0 samples-and-tests/testapp/public/javascripts/jquery-1.5.2.min.js
  67. +330 −0 samples-and-tests/testapp/public/stylesheets/bootstrap-1.3.0/bootstrap.min.css
  68. 0  samples-and-tests/testapp/public/stylesheets/main.css
  69. +7 −0 samples-and-tests/testapp/test/Application.test.html
  70. +17 −0 samples-and-tests/testapp/test/ApplicationTest.java
  71. +13 −0 samples-and-tests/testapp/test/BasicTest.java
  72. +7 −0 samples-and-tests/testapp/test/data.yml
  73. 0  src/play.plugins
View
175 LICENSE.txt
@@ -0,0 +1,175 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
View
23 README
@@ -0,0 +1,23 @@
+h1. SecureSocial Module for Play! Framework Applications
+
+SecureSocial allows you to add an authentication UI to your app that works with services based on OAuth1, OAuth2, OpenID and OpenID+OAuth hybrid protocols.
+
+It also provides a Username and Password mechanism for users that do not wish to use existing accounts in other networks.
+
+The following services are supported:
+
+* Twitter (OAuth1)
+* Facebook (OAuth2)
+* Google (OpenID + OAuth Hybrid)
+* Yahoo (OpenID + OAuth Hybrid)
+* LinkedIn (OAuth1)
+* Foursquare (OAuth2)
+* MyOpenID (OpenID)
+* Wordpress (OpenID)
+* Username and Password
+
+Check the documentation folder for more information.
+
+h2. Licence
+
+SecureSocial is distributed under "Apache 2 licence":http://www.apache.org/licenses/LICENSE-2.0.html.
View
8 Readme-Icons.txt
@@ -0,0 +1,8 @@
+The icons used in this module (except the MyOpenID icon) are part of the WPZOOM Social Networking Icon Set by WPZOOM designed by David Ferreira.
+
+They are licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License (http://creativecommons.org/licenses/by-nc-sa/3.0/).
+
+Please read more at:
+http://www.iconfinder.com/browse/iconset/WPZOOM_Social_Networking_Icon_Set/#readme
+
+
View
178 app/controllers/securesocial/SecureSocial.java
@@ -0,0 +1,178 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package controllers.securesocial;
+
+import play.Logger;
+import play.i18n.Messages;
+import play.libs.OAuth;
+import play.mvc.Before;
+import play.mvc.Controller;
+import securesocial.provider.*;
+
+import java.util.Collection;
+
+/**
+ * This is the main controller for the SecureSocial module.
+ *
+ */
+public class SecureSocial extends Controller {
+
+ private static final String USER_COOKIE = "securesocial.user";
+ private static final String NETWORK_COOKIE = "securesocial.network";
+ private static final String ORIGINAL_URL = "originalUrl";
+ private static final String GET = "GET";
+ private static final String ROOT = "/";
+ private static final String USER = "user";
+ private static final String ERROR = "error";
+ private static final String SECURESOCIAL_AUTH_ERROR = "securesocial.authError";
+
+ /**
+ * Checks if there is a user logged in and redirects to the login page if not.
+ */
+ @Before(unless={"login", "authenticate", "logout"})
+ static void checkAccess() throws Throwable
+ {
+ final UserId userId = getUserId();
+
+ if ( userId == null ) {
+ final String originalUrl = request.method.equals(GET) ? request.url : ROOT;
+ flash.put(ORIGINAL_URL, originalUrl);
+ login();
+ } else {
+ SocialUser user = UserService.find(userId);
+ if ( user == null ) {
+ // the user had the cookies but the UserService can't find it ...
+ // it must have been erased, redirect to login again.
+ clearUserId();
+ login();
+ }
+
+ // if the user is using OAUTH1 or OPENID HYBRID OAUTH set the ServiceInfo
+ // so the app using this module can access it easily to invoke the APIs.
+ if ( user.authMethod == AuthenticationMethod.OAUTH1 || user.authMethod == AuthenticationMethod.OPENID_OAUTH_HYBRID ) {
+ final OAuth.ServiceInfo sinfo;
+ IdentityProvider provider = ProviderRegistry.get(user.id.provider);
+ if ( user.authMethod == AuthenticationMethod.OAUTH1 ) {
+ sinfo = ((OAuth1Provider)provider).getServiceInfo();
+ } else {
+ sinfo = ((OpenIDOAuthHybridProvider)provider).getServiceInfo();
+ }
+ user.serviceInfo = sinfo;
+ }
+ // make the user available in templates
+ renderArgs.put(USER, user);
+ }
+ }
+
+ /**
+ * Returns the current user.
+ *
+ * @return SocialUser the current user
+ */
+ public static SocialUser getCurrentUser() {
+ return (SocialUser) renderArgs.get(USER);
+ }
+
+ /*
+ * Removes the SecureSocial cookies from the session.
+ */
+ private static void clearUserId() {
+ session.remove(USER_COOKIE);
+ session.remove(NETWORK_COOKIE);
+ }
+
+ /*
+ * Sets the SecureSocial cookies in the session.
+ */
+ private static void setUserId(SocialUser user) {
+ session.put(USER_COOKIE, user.id.id);
+ session.put(NETWORK_COOKIE, user.id.provider.toString());
+ }
+
+ /*
+ * Creates a UserId object from the values stored in the session.
+ *
+ * @see UserId
+ * @returns UserId the user id
+ */
+ private static UserId getUserId() {
+ final String userId = session.get(USER_COOKIE);
+ final String networkId = session.get(NETWORK_COOKIE);
+
+ UserId id = null;
+
+ if ( userId != null && networkId != null ) {
+ id = new UserId();
+ id.id = userId;
+ id.provider = ProviderType.valueOf(networkId);
+ }
+ return id;
+ }
+
+ /**
+ * The action for the login page.
+ */
+ public static void login() {
+ final Collection providers = ProviderRegistry.all();
+ flash.keep(ORIGINAL_URL);
+ boolean userPassEnabled = ProviderRegistry.get(ProviderType.userpass) != null;
+ render(providers, userPassEnabled);
+
+ }
+
+ /**
+ * The logout action.
+ */
+ public static void logout() {
+ clearUserId();
+ login();
+ }
+
+ /**
+ * This is the entry point for all authentication requests from the login page.
+ * The type is used to invoke the right provider.
+ *
+ * @param type The provider type as selected by the user in the login page
+ * @see ProviderType
+ * @see IdentityProvider
+ */
+ public static void authenticate(ProviderType type) {
+ if ( type == null ) {
+ Logger.error("Provider type was missing in request");
+ // just throw a 404 error
+ notFound();
+ }
+ flash.keep(ORIGINAL_URL);
+
+ IdentityProvider provider = ProviderRegistry.get(type);
+ String originalUrl = null;
+
+ try {
+ SocialUser user = provider.authenticate();
+ setUserId(user);
+ originalUrl = flash.get(ORIGINAL_URL);
+ } catch ( Exception e ) {
+ e.printStackTrace();
+ Logger.error(e, "Error authenticating user");
+ if ( flash.get(ERROR) == null ) {
+ flash.error(Messages.get(SECURESOCIAL_AUTH_ERROR));
+ }
+ flash.keep(ORIGINAL_URL);
+ login();
+ }
+ redirect( originalUrl != null ? originalUrl : ROOT);
+ }
+}
View
134 app/controllers/securesocial/UsernamePasswordController.java
@@ -0,0 +1,134 @@
+/**
+ * Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package controllers.securesocial;
+
+import notifiers.securesocial.Mails;
+import play.Logger;
+import play.data.validation.Email;
+import play.data.validation.Equals;
+import play.data.validation.Required;
+import play.i18n.Messages;
+import play.libs.Crypto;
+import play.mvc.Controller;
+import play.mvc.Router;
+import securesocial.provider.*;
+
+/**
+ * The controller for the UI required by the Username Password Provider.
+ */
+public class UsernamePasswordController extends Controller
+{
+ private static final String USER_NAME = "userName";
+ private static final String SECURESOCIAL_USER_NAME_TAKEN = "securesocial.userNameTaken";
+ private static final String SECURESOCIAL_ERROR_CREATING_ACCOUNT = "securesocial.errorCreatingAccount";
+ private static final String SECURESOCIAL_ACCOUNT_CREATED = "securesocial.accountCreated";
+ private static final String SECURESOCIAL_ACTIVATION_TITLE = "securesocial.activationTitle";
+ private static final String SECURESOCIAL_SECURE_SOCIAL_NOTICE_PAGE_HTML = "securesocial/SecureSocial/noticePage.html";
+ private static final String DISPLAY_NAME = "displayName";
+ private static final String EMAIL = "email";
+ private static final String SECURESOCIAL_INVALID_LINK = "securesocial.invalidLink";
+ private static final String SECURESOCIAL_ACTIVATION_SUCCESS = "securesocial.activationSuccess";
+ private static final String SECURESOCIAL_SECURE_SOCIAL_LOGIN = "securesocial.SecureSocial.login";
+ private static final String SECURESOCIAL_ACTIVATE_TITLE = "securesocial.activateTitle";
+
+ /**
+ * Renders the sign up page.
+ */
+ public static void signup() {
+ render();
+ }
+
+ /**
+ * Creates an account
+ *
+ * @param userName The username
+ * @param displayName The user's full name
+ * @param email The email
+ * @param password The password
+ * @param password2 The password verification
+ */
+ public static void createAccount(@Required(message = "securesocial.required") String userName,
+ @Required String displayName,
+ @Required @Email(message = "securesocial.invalidEmail") String email,
+ @Required String password,
+ @Required @Equals(message = "securesocial.passwordsMustMatch", value = "password") String password2) {
+ if ( validation.hasErrors() ) {
+ tryAgain(userName, displayName, email);
+ }
+
+ UserId id = new UserId();
+ id.id = userName;
+ id.provider = ProviderType.userpass;
+
+ if ( UserService.find(id) != null ) {
+ validation.addError(USER_NAME, Messages.get(SECURESOCIAL_USER_NAME_TAKEN));
+ tryAgain(userName, displayName, email);
+ }
+ SocialUser user = new SocialUser();
+ user.id = id;
+ user.displayName = displayName;
+ user.email = email;
+ user.password = Crypto.passwordHash(password);
+ // the user will remain inactive until the email verification is done.
+ user.isEmailVerified = false;
+ user.authMethod = AuthenticationMethod.USER_PASSWORD;
+
+ try {
+ UserService.save(user);
+ } catch ( Throwable e ) {
+ Logger.error(e, "Error while invoking UserService.save()");
+ flash.error(Messages.get(SECURESOCIAL_ERROR_CREATING_ACCOUNT));
+ tryAgain(userName, displayName, email);
+ }
+
+ // create an activation id
+ final String uuid = UserService.createActivation(user);
+ Mails.sendActivationEmail(user, uuid);
+ flash.success(Messages.get(SECURESOCIAL_ACCOUNT_CREATED));
+ final String title = Messages.get(SECURESOCIAL_ACTIVATION_TITLE, user.displayName);
+ render(SECURESOCIAL_SECURE_SOCIAL_NOTICE_PAGE_HTML, title);
+ }
+
+ private static void tryAgain(String username, String displayName, String email) {
+ flash.put(USER_NAME, username);
+ flash.put(DISPLAY_NAME, displayName);
+ flash.put(EMAIL, email);
+ validation.keep();
+ signup();
+ }
+
+ /**
+ * The action invoked from the activation email the user receives after signing up.
+ *
+ * @param uuid The activation id
+ */
+ public static void activate(String uuid) {
+ try {
+ if ( UserService.activate(uuid) == false ) {
+ flash.error( Messages.get(SECURESOCIAL_INVALID_LINK) );
+ } else {
+ flash.success(Messages.get(SECURESOCIAL_ACTIVATION_SUCCESS, Router.reverse(SECURESOCIAL_SECURE_SOCIAL_LOGIN)));
+ }
+ } catch ( Throwable t) {
+ Logger.error(t, "Error while activating account");
+ flash.error(Messages.get(SECURESOCIAL_ERROR_CREATING_ACCOUNT));
+ }
+ final String title = Messages.get(SECURESOCIAL_ACTIVATE_TITLE);
+ render(SECURESOCIAL_SECURE_SOCIAL_NOTICE_PAGE_HTML, title);
+ }
+}
View
50 app/notifiers/securesocial/Mails.java
@@ -0,0 +1,50 @@
+/**
+ * Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package notifiers.securesocial;
+
+import play.Play;
+import play.mvc.Mailer;
+import play.mvc.Router;
+import securesocial.provider.SocialUser;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A helper class to send welcome emails to users that signed up using the
+ * Username Password controller
+ *
+ * @see securesocial.provider.providers.UsernamePasswordProvider
+ * @see controllers.securesocial.UsernamePasswordController
+ */
+public class Mails extends Mailer {
+ private static final String SECURESOCIAL_MAILER_SUBJECT = "securesocial.mailer.subject";
+ private static final String SECURESOCIAL_MAILER_FROM = "securesocial.mailer.from";
+ private static final String SECURESOCIAL_USERNAME_PASSWORD_CONTROLLER_ACTIVATE = "securesocial.UsernamePasswordController.activate";
+ private static final String UUID = "uuid";
+
+ public static void sendActivationEmail(SocialUser user, String uuid) {
+ setSubject( Play.configuration.getProperty(SECURESOCIAL_MAILER_SUBJECT));
+ setFrom(Play.configuration.getProperty(SECURESOCIAL_MAILER_FROM));
+ addRecipient(user.email);
+ Map<String, Object> args = new HashMap<String, Object>();
+ args.put(UUID, uuid);
+ String activationUrl = Router.getFullUrl(SECURESOCIAL_USERNAME_PASSWORD_CONTROLLER_ACTIVATE, args);
+ send(user, activationUrl);
+ }
+}
View
93 app/securesocial/jobs/Bootstrap.java
@@ -0,0 +1,93 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.jobs;
+
+import play.Logger;
+import play.Play;
+import play.jobs.Job;
+import play.jobs.OnApplicationStart;
+import securesocial.provider.*;
+
+import java.lang.reflect.Modifier;
+import java.util.*;
+
+/**
+ * A Job to load the providers and set the user service.
+ */
+@OnApplicationStart
+public class Bootstrap extends Job {
+ private static final String SECURESOCIAL_PROVIDERS = "securesocial.providers";
+ private static final String SEPARATOR = ",";
+ private static final String SECURESOCIAL = "securesocial";
+
+ @Override
+ public void doJob() throws Exception {
+ // register providers
+ final List<Class> providers = Play.classloader.getAssignableClasses(IdentityProvider.class);
+ if ( providers.size() > 0 ) {
+ Map<ProviderType, IdentityProvider> availableProviders = new LinkedHashMap<ProviderType, IdentityProvider>();
+ for( Class clazz : providers ) {
+ if ( !Modifier.isAbstract(clazz.getModifiers()) ) {
+ IdentityProvider provider = (IdentityProvider) clazz.newInstance();
+ availableProviders.put(provider.type, provider);
+ }
+ }
+ // register them in the preferred order
+ final String s = Play.configuration.getProperty(SECURESOCIAL_PROVIDERS);
+
+ if ( s != null && s.length() > 0) {
+ final String[] requestedProviders = s.split(SEPARATOR);
+ for ( String type: requestedProviders ) {
+ try {
+ ProviderRegistry.register(availableProviders.get(ProviderType.valueOf(type)));
+ } catch ( IllegalArgumentException e ) {
+ Logger.error("Unknown type specified in securesocial.providers: %s", type);
+ }
+ }
+ } else {
+ for( IdentityProvider p : availableProviders.values()) {
+ ProviderRegistry.register(p);
+ }
+ }
+ } else {
+ Logger.fatal("Unable to find identity providers.");
+ }
+
+ // set the user service
+ final List<Class> classes = Play.classloader.getAssignableClasses(UserService.Service.class);
+ UserService.Service service = null;
+
+ int classesFound = classes.size();
+ if ( classesFound == 1 ) {
+ // use the default implementation
+ Logger.info("Using default user service");
+ service = new DefaultUserService();
+ } else if ( classesFound == 2 ) {
+ // a custom implementation was found. use it instead of the default
+ Class clazz = classes.get(0);
+ if ( clazz.getName().startsWith(SECURESOCIAL) ) {
+ clazz = classes.get(1);
+ }
+ service = (UserService.Service) clazz.newInstance();
+ Logger.info("Using custom user service: %s", service.getClass());
+ } else {
+ // should not happen unless someone implements the interface more than once.
+ Logger.fatal("More than one custom UserService was found. Unable to initialize.");
+ }
+ UserService.setService(service);
+ }
+}
View
35 app/securesocial/jobs/PendingActivationsJobs.java
@@ -0,0 +1,35 @@
+/**
+ * Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package securesocial.jobs;
+
+import play.jobs.Every;
+import play.jobs.Job;
+import securesocial.provider.UserService;
+
+/**
+ * A Job that deletes pending activations every 24 hours
+ *
+ */
+@Every("24h")
+public class PendingActivationsJobs extends Job
+{
+ @Override
+ public void doJob() throws Exception {
+ UserService.deletePendingActivations();
+ }
+}
View
29 app/securesocial/provider/AccessDeniedException.java
@@ -0,0 +1,29 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+import play.utils.FastRuntimeException;
+
+/**
+ * An exception thrown when the user denies access to the application
+ * in the login page of the 3rd party service
+ */
+public class AccessDeniedException extends FastRuntimeException {
+ public AccessDeniedException() {
+ super();
+ }
+}
View
39 app/securesocial/provider/AuthenticationException.java
@@ -0,0 +1,39 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+import play.libs.OAuth;
+import play.utils.FastRuntimeException;
+
+/**
+ * An exception thrown when there is an error in the authentication flow
+ */
+public class AuthenticationException extends FastRuntimeException {
+ private OAuth.Error error;
+
+ public AuthenticationException() {
+ super();
+ }
+
+ public AuthenticationException(OAuth.Error error) {
+ super(error.details());
+ }
+
+ public OAuth.Error getError() {
+ return error;
+ }
+}
View
28 app/securesocial/provider/AuthenticationMethod.java
@@ -0,0 +1,28 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+/**
+ * Authentication methods used by the Identity Providers
+ */
+public enum AuthenticationMethod {
+ OAUTH1,
+ OAUTH2,
+ OPENID,
+ OPENID_OAUTH_HYBRID,
+ USER_PASSWORD
+}
View
70 app/securesocial/provider/DefaultUserService.java
@@ -0,0 +1,70 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+import play.libs.Codec;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The default user service provided with SecureSocial.
+ * If users need to find/save users in a custom backing store they only
+ * need to provide an implementation of the UserService.Service interface in their app. It will be picked up automatically.
+ *
+ * This class it not suitable for a production environment. It is only meant to be used in development. For production use
+ * you need to provide your own implementation.
+ *
+ * @see UserService.Service
+ * @see securesocial.jobs.Bootstrap
+ */
+public class DefaultUserService implements UserService.Service {
+
+ private Map<String, SocialUser> users = new HashMap<String, SocialUser>();
+ private Map<String, SocialUser> activations = new HashMap<String, SocialUser>();
+
+ public SocialUser find(UserId id) {
+ return users.get(id.id + id.provider.toString());
+ }
+
+ public void save(SocialUser user) {
+ users.put(user.id.id + user.id.provider.toString(), user);
+ }
+
+ public String createActivation(SocialUser user) {
+ final String uuid = Codec.UUID();
+ activations.put(uuid, user);
+ return uuid;
+ }
+
+ public boolean activate(String uuid) {
+ SocialUser user = activations.get(uuid);
+ boolean result = false;
+
+ if( user != null ) {
+ user.isEmailVerified = true;
+ save(user);
+ activations.remove(uuid);
+ result = true;
+ }
+ return result;
+ }
+
+ public void deletePendingActivations() {
+ activations.clear();
+ }
+}
View
129 app/securesocial/provider/IdentityProvider.java
@@ -0,0 +1,129 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Base class for all itendity providers
+ */
+public abstract class IdentityProvider {
+ /**
+ * The provider ID.
+ */
+ public ProviderType type;
+
+ /**
+ * The authentication method used by this provider
+ */
+ public AuthenticationMethod authMethod;
+
+ private static final String TYPE = "type";
+ private static final String SECURESOCIAL_SECURE_SOCIAL_AUTHENTICATE = "securesocial.SecureSocial.authenticate";
+ private static final String SECURESOCIAL = "securesocial.";
+ private static final String DOT = ".";
+
+ /**
+ * Creates a new IdentityProvider
+ *
+ * @param type The type for this provider
+ * @param authMethod The authentication method used by this provider
+ */
+ protected IdentityProvider(ProviderType type, AuthenticationMethod authMethod) {
+ this.type = type;
+ this.authMethod = authMethod;
+ }
+
+ @Override
+ public String toString() {
+ return type.toString();
+ }
+
+ /**
+ * The authentication flow starts here. This method is called from the
+ * SecureSocial controller
+ *
+ * @return A SocialUser if the user was authenticated properly
+ */
+ public SocialUser authenticate() {
+ // authenticate against the 3rd party service (facebook, twitter, etc)
+ Map<String, Object> authContext = new HashMap<String, Object>();
+ SocialUser user = doAuth(authContext);
+
+ // if user authenticated correctly, retrieve some profile information
+ fillProfile(user, authContext);
+
+ // save the user
+ user.lastAccess = new Date();
+ UserService.save(user);
+
+ // we're done.
+ return user;
+ }
+
+ /**
+ * A helper method to create a user with some authentication details.
+ *
+ * @return A SocialUser object
+ */
+ protected SocialUser createUser() {
+ SocialUser user = new SocialUser();
+ user.id = new UserId();
+ user.id.provider = type;
+ user.authMethod = authMethod;
+ return user;
+ }
+
+ /**
+ * Returns the full url for the authenticate action.
+ *
+ * @return A url
+ */
+ public String getFullUrl() {
+ Map<String, Object> args = new HashMap<String, Object>();
+ args.put(TYPE, type);
+ return play.mvc.Router.getFullUrl(SECURESOCIAL_SECURE_SOCIAL_AUTHENTICATE, args);
+ }
+
+ /**
+ * Subclasses must implement the authentication logic in this method
+ *
+ * @param authContext This map can be used to store information that fillProfile will need to complete the operation
+ * @return SocialUser the authenticated user
+ */
+ protected abstract SocialUser doAuth(Map<String, Object> authContext);
+
+ /**
+ * Once the user is authenticated this method is called to retrieve profile information from the provider.
+ *
+ * @param user A SocialUser
+ * @param authContext This map can contain information collected during the doAuth call.
+ */
+ protected abstract void fillProfile(SocialUser user, Map<String, Object> authContext);
+
+ /**
+ * A helper method to return the keys for the properties required by the provider.
+ *
+ * @param type The provider type
+ * @return A String
+ */
+ public static String getPropertiesKey(ProviderType type) {
+ return new StringBuilder(SECURESOCIAL).append(type).append(DOT).toString();
+ }
+}
View
116 app/securesocial/provider/OAuth1Provider.java
@@ -0,0 +1,116 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+import play.Play;
+import play.cache.Cache;
+import play.libs.OAuth;
+import play.mvc.Scope;
+import play.mvc.results.Redirect;
+
+import java.util.Map;
+
+/**
+ * A provider that handles the OAuth1 authentication flow
+ */
+public abstract class OAuth1Provider extends IdentityProvider {
+
+ private static final String DENIED = "denied";
+ private static final String SECURESOCIAL = "securesocial.";
+ private OAuth.ServiceInfo serviceInfo;
+ private static final String REQUEST_TOKEN_URL = "requestTokenURL";
+ private static final String ACCESS_TOKEN_URL = "accessTokenURL";
+ private static final String AUTHORIZATION_URL = "authorizationURL";
+ private static final String CONSUMER_KEY = "consumerKey";
+ private static final String CONSUMER_SECRET = "consumerSecret";
+
+
+ protected OAuth1Provider(ProviderType type)
+ {
+ super(type, AuthenticationMethod.OAUTH1);
+ serviceInfo = createServiceInfo(getPropertiesKey(type));
+ }
+
+ /**
+ * Gets the service info required to invoke the APIs for this provider.
+ *
+ * @return A play.libs.OAuth.ServiceInfo object
+ */
+ public OAuth.ServiceInfo getServiceInfo() {
+ return serviceInfo;
+ }
+
+ /**
+ * Creates a ServiceInfo using the properties in the application.conf
+ *
+ * @param key The key for this provider
+ * @return A OAuth.ServiceInfo object
+ */
+ public static OAuth.ServiceInfo createServiceInfo(String key) {
+ return new OAuth.ServiceInfo(
+ Play.configuration.getProperty(key + REQUEST_TOKEN_URL),
+ Play.configuration.getProperty(key + ACCESS_TOKEN_URL),
+ Play.configuration.getProperty(key + AUTHORIZATION_URL),
+ Play.configuration.getProperty(key + CONSUMER_KEY),
+ Play.configuration.getProperty(key + CONSUMER_SECRET)
+ );
+
+ }
+
+ @Override
+ public SocialUser doAuth(Map<String, Object> authContext) throws AccessDeniedException {
+ Scope.Params params = Scope.Params.current();
+
+ if ( params.get(DENIED) != null ) {
+ throw new AccessDeniedException();
+ }
+
+ final String key = new StringBuilder(SECURESOCIAL).append(Scope.Session.current().getId()).toString();
+ OAuth service = OAuth.service(serviceInfo);
+
+ if ( !OAuth.isVerifierResponse() ) {
+ // first step on the authentication process
+ OAuth.Response response = service.retrieveRequestToken();
+ if ( response.error != null ) {
+ // there was an error retrieving the access token
+ throw new AuthenticationException(response.error);
+ }
+ SocialUser user = createUser();
+ user.token = response.token;
+ user.secret = response.secret;
+ Cache.add(key, user);
+ throw new Redirect( service.redirectUrl(response.token), false);
+ }
+
+ // the OAuth provider is redirecting back to us
+ SocialUser user = (SocialUser) Cache.get(key);
+ if ( user == null ) {
+ throw new AuthenticationException();
+ }
+ Cache.delete(key);
+ OAuth.Response response = service.retrieveAccessToken(user.token, user.secret);
+ if ( response.error != null ) {
+ throw new AuthenticationException(response.error);
+ }
+
+ // all was ok, replace the tokens
+ user.token = response.token;
+ user.secret = response.secret;
+ user.serviceInfo = serviceInfo;
+ return user;
+ }
+}
View
155 app/securesocial/provider/OAuth2Provider.java
@@ -0,0 +1,155 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import play.Play;
+import play.libs.OAuth2;
+import play.mvc.Scope;
+import play.mvc.results.Redirect;
+
+import java.util.Map;
+
+/**
+ * A provider that handles the OAuth2 authentication flow
+ */
+public abstract class OAuth2Provider extends IdentityProvider
+{
+ private OAuth2 service;
+ private String[] scope;
+ private static final String SCOPE = "scope";
+ private static final String AUTHORIZATION_URL = "authorizationURL";
+ private static final String ACCESS_TOKEN_URL = "accessTokenURL";
+ private static final String CLIENTID = "clientid";
+ private static final String SECRET = "secret";
+ private static final String QUESTION_MARK = "?";
+ private static final String AMPERSAND = "&";
+ private static final String CLIENT_ID = "client_id=";
+ private static final String EQUALS_SIGN = "=";
+ private static final String REDIRECT_URI = "&redirect_uri=";
+ private static final String ACCESS_TOKEN = "access_token";
+ private static final String OAUTH_TOKEN = "oauth_token";
+ private static final String ERROR = "error";
+
+ protected OAuth2Provider(ProviderType type) {
+ super(type, AuthenticationMethod.OAUTH2);
+ final String key = getPropertiesKey(type);
+ service = createOAuth2(key);
+ scope = getScope(key, SCOPE);
+ }
+
+ /**
+ * Creates an OAuth2 object using the properties specified for the provider.
+ *
+ * @param key The provider key
+ * @return An OAuth2 object
+ */
+ private OAuth2 createOAuth2(String key) {
+ return new OAuth2(
+ Play.configuration.getProperty(key + AUTHORIZATION_URL),
+ Play.configuration.getProperty(key + ACCESS_TOKEN_URL),
+ Play.configuration.getProperty(key + CLIENTID),
+ Play.configuration.getProperty(key + SECRET)
+ );
+ }
+
+ /**
+ * Returns the scope specified for this provider in the properties file (eg: facebook.scope)
+ *
+ * @param providerKey The properties key
+ * @param scopeKey The property name
+ * @return The scope
+ */
+ public static String[] getScope(String providerKey, String scopeKey) {
+ final String s = Play.configuration.getProperty(providerKey + SCOPE);
+ String []scope = null;
+ if ( s != null && s.trim().length() > 0) {
+ scope = new String[] {scopeKey, s};
+ }
+ return scope;
+ }
+
+ /**
+ * @see IdentityProvider#doAuth(java.util.Map)
+ * @return
+ */
+ @Override
+ protected SocialUser doAuth(Map<String, Object> authContext) {
+ Scope.Params params = Scope.Params.current();
+
+ if ( params.get(ERROR) != null ) {
+ // todo: improve this. Get details of the error and include them in the exception.
+ throw new AuthenticationException();
+ }
+
+ if ( !OAuth2.isCodeResponse() ) {
+ StringBuilder authUrl = new StringBuilder(service.authorizationURL);
+ String delimiter = service.authorizationURL.indexOf(QUESTION_MARK) == -1 ? QUESTION_MARK : AMPERSAND;
+ authUrl.append(delimiter).append(CLIENT_ID).append(service.clientid);
+ if ( scope != null ) {
+ authUrl.append(AMPERSAND).append(scope[0]).append(EQUALS_SIGN).append(scope[1]);
+ }
+ authUrl.append(REDIRECT_URI).append(getFullUrl());
+ throw new Redirect(authUrl.toString());
+ }
+
+ final String authUrl = getFullUrl();
+ OAuth2.Response response = service.retrieveAccessToken(authUrl);
+ if ( response == null ) {
+ throw new AuthenticationException();
+ }
+
+ String accessTokenFromJson = null;
+ if ( response.error != null ) {
+ if ( response.error.type == OAuth2.Error.Type.UNKNOWN ) {
+ // the OAuth2 class is expecting the access token in the query string.
+ // this is not what the OAuth2 spec says. Facebook works, but Foursquare fails for example.
+ // So I'm going to check if the token is there before throwing the exception.
+ // todo: fix the OAuth2 class.
+ JsonElement asJson = response.httpResponse.getJson();
+
+ if ( asJson != null ) {
+ JsonObject body = asJson.getAsJsonObject();
+ if ( body != null ) {
+ // this is what many libraries expect (probably because Facebook returns it)
+ JsonElement token = body.get(ACCESS_TOKEN);
+ if ( token != null ) {
+ accessTokenFromJson = token.getAsString();
+ } else {
+ // this is what should be returned as defined in the OAuth2 spec
+ token = body.get(OAUTH_TOKEN);
+ if ( token != null ) {
+ accessTokenFromJson = token.getAsString();
+ }
+ }
+ }
+ }
+ }
+
+ // if the workaround did not find the token then we really have an error,
+ // so I need to throw the exception
+ if ( accessTokenFromJson == null ) {
+ // todo: add error to the exception
+ throw new AuthenticationException();
+ }
+ }
+ SocialUser user = createUser();
+ user.accessToken = accessTokenFromJson == null ? response.accessToken : accessTokenFromJson;
+ return user;
+ }
+}
View
136 app/securesocial/provider/OpenIDOAuthHybridProvider.java
@@ -0,0 +1,136 @@
+/**
+ * Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package securesocial.provider;
+
+import play.Logger;
+import play.Play;
+import play.libs.OAuth;
+import play.libs.OpenID;
+import play.libs.WS;
+import play.mvc.Scope;
+import play.mvc.results.Redirect;
+
+import java.util.Map;
+
+/**
+ * Base class for all providers that need to support the OpenID + OAuth Hybrid protocol
+ */
+public abstract class OpenIDOAuthHybridProvider extends OpenIDProvider
+{
+ private OAuth.ServiceInfo sinfo;
+ private String[][] oauthParameters;
+ private static final String OPENID_EXT2_SCOPE = "openid.ext2.scope";
+ private static final String OPENID_NS_EXT2 = "openid.ns.ext2";
+ private static final String HTTP_SPECS_OPENID_NET_EXTENSIONS_OAUTH_1_0 = "http://specs.openid.net/extensions/oauth/1.0";
+ private static final String OPENID_EXT2_CONSUMER = "openid.ext2.consumer";
+ private static final String OPENID_OAUTH_REQUEST_TOKEN = "openid.oauth.request_token";
+ private static final String OPENID_EXT2_REQUEST_TOKEN = "openid.ext2.request_token";
+ private static final String AMPERSAND = "&";
+ private static final String EQUALS = "=";
+ private static final String EMPTY_SECRET = "";
+
+ protected OpenIDOAuthHybridProvider(ProviderType type, String userFormat) {
+ super(type, userFormat);
+ final String key = getPropertiesKey(type);
+ sinfo = OAuth1Provider.createServiceInfo(key);
+
+ final String scope[] = OAuth2Provider.getScope(key, OPENID_EXT2_SCOPE);
+ if ( scope != null ) {
+ oauthParameters = new String[3][2];
+ oauthParameters[2][0] = scope[0];
+ oauthParameters[2][1] = scope[1];
+
+ } else {
+ oauthParameters = new String[2][2];
+ }
+ oauthParameters[0] = new String[] {OPENID_NS_EXT2, HTTP_SPECS_OPENID_NET_EXTENSIONS_OAUTH_1_0};
+ oauthParameters[1] = new String[] {OPENID_EXT2_CONSUMER, sinfo.consumerKey};
+
+ }
+
+ /**
+ * Returns the ServiceInfo needed to invoke APIs in the service this provider represents
+ *
+ *
+ * @return A OAuth.ServiceInfo object
+ */
+ public OAuth.ServiceInfo getServiceInfo() {
+ return sinfo;
+ }
+
+ /**
+ * Executes the OpenID + OAuth1 hybrid flow.
+ *
+ * @see OpenIDProvider#doAuth(java.util.Map)
+ * @see IdentityProvider#doAuth(java.util.Map)
+ */
+ protected SocialUser doAuth(Map<String, Object> authContext) {
+ SocialUser user;
+
+ try {
+ user = super.doAuth(authContext);
+ } catch ( Redirect redirect ) {
+ // todo: add this behaviour into Play's OpenID class.
+ redirect.url = addParameters(new StringBuilder(redirect.url), oauthParameters).toString();
+ throw redirect;
+ }
+
+ // OpenID flow is done, complete the OAuth part
+ Scope.Params params = Scope.Params.current();
+ String token = params.get(OPENID_OAUTH_REQUEST_TOKEN);
+
+ if ( token == null ) {
+ token = params.get(OPENID_EXT2_REQUEST_TOKEN);
+ }
+ if ( token == null ) {
+ Logger.error("Request token is missing in OpenID+OAuth callback. Provider: " + type);
+ throw new AuthenticationException();
+ }
+ if ( Logger.isDebugEnabled() ) {
+ Logger.debug("openid.ext2.scope = " + params.get(OPENID_EXT2_SCOPE));
+ Logger.debug("openid.ext2.request_token = " + token);
+ }
+ OAuth oauth = OAuth.service(sinfo);
+ OAuth.Response response = oauth.retrieveAccessToken(token, EMPTY_SECRET);
+ if ( response.error != null ) {
+ Logger.error("Error retrieving access token from %s, : %s", type, response.error.toString());
+ throw new AuthenticationException(response.error);
+ }
+
+ user.token = response.token;
+ user.secret = response.secret;
+ user.serviceInfo = sinfo;
+
+ if ( Logger.isDebugEnabled() ) {
+ Logger.debug("After OAuth exchange: request token = " + token + " -> token = " + user.token + " - secret = " + user.secret);
+ }
+ user.authMethod = AuthenticationMethod.OPENID_OAUTH_HYBRID;
+ return user;
+ }
+
+ // a helper method to add parameters to some urls ...
+ // todo: fix play so this is not needed.
+ private StringBuilder addParameters(StringBuilder url, String [][]additionalParams) {
+ // this is a hack, retrieveVerificationCode should allow passing parameters
+ if ( additionalParams != null ) {
+ for ( int i = 0 ; i < additionalParams.length ; i++ ) {
+ url.append(AMPERSAND).append(additionalParams[i][0]).append(EQUALS).append( WS.encode(additionalParams[i][1]));
+ }
+ }
+ return url;
+ }
+}
View
119 app/securesocial/provider/OpenIDProvider.java
@@ -0,0 +1,119 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+import play.i18n.Messages;
+import play.libs.OpenID;
+import play.mvc.Http;
+import play.mvc.Scope;
+
+import java.util.Map;
+
+/**
+ * An OpenID provider
+ */
+public abstract class OpenIDProvider extends IdentityProvider
+{
+ private boolean needsUsername;
+ private String userFormat;
+ private static final String USERNAME_TAG = "{username}";
+ private static final String OPENID_USER = "openid.user";
+ private static final String USERNAME_REGEX = "\\{username\\}";
+ protected static final String USER_INFO = "userInfo";
+ private static final String SECURESOCIAL_OPEN_ID_USER_NOT_SPECIFIED = "securesocial.openIdUserNotSpecified";
+
+ /**
+ * Creates an OpenID provider.
+ *
+ * @param type the Provider Type (eg: myopenid)
+ * @param userFormat The user url format (eg: http://{username}.wordpress.com)
+ */
+ protected OpenIDProvider(ProviderType type, String userFormat) {
+ super(type, AuthenticationMethod.OPENID);
+ this.userFormat = userFormat;
+ needsUsername = userFormat.indexOf(USERNAME_TAG) != -1;
+ }
+
+ /**
+ * Returns the user url (eg: http://user.wordpress.com) for an OpenID service.
+ * The method checks if the userFormat has a {username} tag and if it does then
+ * looks for the username value in the request parameters.
+ *
+ * If there is no {username} tag the userFormat is used a passed by the subclass.
+ * This is because some providers (eg: google or yahoo) do not need the username in the
+ * url.
+ *
+ * @return The url representing the user.
+ */
+ protected String getUser() {
+ final String user;
+ if ( needsUsername ) {
+ final String username = Scope.Params.current().get(OPENID_USER);
+ if ( username == null || username.trim().length() == 0) {
+ Scope.Flash.current().error(Messages.get(SECURESOCIAL_OPEN_ID_USER_NOT_SPECIFIED));
+ throw new AuthenticationException();
+ }
+ user = userFormat.replaceFirst(USERNAME_REGEX, username);
+ } else {
+ user = userFormat;
+ }
+ return user;
+ }
+
+
+ /**
+ * Returns true if the userFormat does not have a {username} tag.
+ * @return A boolean
+ */
+ protected boolean needsUsername() {
+ return needsUsername;
+ }
+
+ /**
+ * @see IdentityProvider#doAuth(java.util.Map)
+ */
+ @Override
+ protected SocialUser doAuth(Map<String, Object> authContext) {
+ if ( !OpenID.isAuthenticationResponse() ) {
+ OpenID openId = OpenID.id(getUser());
+ final String url = getFullUrl();
+ openId.returnTo( url );
+ openId.forRealm( Http.Request.current().getBase() );
+ configure(openId);
+ if ( !openId.verify() ) {
+ throw new AuthenticationException();
+ }
+ }
+ //
+ OpenID.UserInfo verifiedUser = OpenID.getVerifiedID();
+ if ( verifiedUser == null ) {
+ throw new AuthenticationException();
+ }
+ authContext.put(USER_INFO, verifiedUser);
+ SocialUser user = createUser();
+ user.id.id = verifiedUser.id;
+ return user;
+ }
+
+ /**
+ * This method allows subclasses to set up additional settings (such as specifying attribute exchange or sreg)
+ * before redirecting the user to the OpenId provider.
+ *
+ * @param openId
+ */
+ protected abstract void configure(OpenID openId);
+}
View
69 app/securesocial/provider/ProviderRegistry.java
@@ -0,0 +1,69 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+import play.Logger;
+
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * A Provider Registry. All the providers discovered by the bootstrap job are registered here.
+ * The SecureSocial controller looks for the providers here as well.
+ *
+ * @see securesocial.jobs.Bootstrap
+ * @see controllers.securesocial.SecureSocial
+ */
+public class ProviderRegistry {
+ private static Map<ProviderType, IdentityProvider> providers = new LinkedHashMap<ProviderType, IdentityProvider>();
+
+ /**
+ * Registgers a provider.
+ *
+ * @param p The identity provider.
+ * @throws RuntimeException if there is another provider registered with the same type.
+ * @see ProviderType
+ */
+ public static void register(IdentityProvider p) {
+ if ( providers.get(p.type) != null ) {
+ // make sure the same type is not used more than once
+ Logger.error("Tried to register provider for type: " + p.type + " but it is registered already. Providers: " + providers);
+ throw new RuntimeException("There is already a provider registered for type: " + p.type);
+ }
+ providers.put(p.type, p);
+ Logger.info("Registered Identity Provider: " + p.type);
+ }
+
+ /**
+ * Returns a provider that matches the specified type.
+ *
+ * @param type A ProviderType
+ * @return An IdentityProvider
+ */
+ public static IdentityProvider get(ProviderType type) {
+ return providers.get(type);
+ }
+
+ /**
+ * Returns all the registered providers.
+ * @return A Collection with the providers
+ */
+ public static Collection<IdentityProvider> all() {
+ return providers.values();
+ }
+}
View
32 app/securesocial/provider/ProviderType.java
@@ -0,0 +1,32 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+/**
+ * An enum with the authentication providers supported by SecureSocial
+ */
+public enum ProviderType {
+ twitter,
+ facebook,
+ google,
+ yahoo,
+ linkedin,
+ foursquare,
+ userpass,
+ wordpress,
+ myopenid
+}
View
90 app/securesocial/provider/SocialUser.java
@@ -0,0 +1,90 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+import play.libs.OAuth;
+
+import java.util.Date;
+
+/**
+ * A class representing a conected user and its authentication details.
+ */
+public class SocialUser implements java.io.Serializable {
+ /**
+ * The user id
+ */
+ public UserId id;
+
+ /**
+ * The user full name.
+ */
+ public String displayName;
+
+ /**
+ * The user's email
+ */
+ public String email;
+
+ /**
+ * A URL pointing to an avatar
+ */
+ public String avatarUrl;
+
+ /**
+ * The time of the last login. This is set by the SecureSocial controller.
+ */
+ public Date lastAccess;
+
+ /**
+ * The method that was used to authenticate the user.
+ */
+ public AuthenticationMethod authMethod;
+
+ /**
+ * The service info required to make calls to the API for OAUTH1 users
+ * (available when authMethod is OAUTH1 or OPENID_OAUTH_HYBRID)
+ *
+ * Note: this value does not need to be persisted by UserService since it is set automatically
+ * in the SecureSocial Controller for each request that needs it.
+ */
+ public OAuth.ServiceInfo serviceInfo;
+
+ /**
+ * The OAuth1 token (available when authMethod is OAUTH1 or OPENID_OAUTH_HYBRID)
+ */
+ public String token;
+
+ /**
+ * The OAuth1 secret (available when authMethod is OAUTH1 or OPENID_OAUTH_HYBRID)
+ */
+ public String secret;
+
+ /**
+ * The OAuth2 access token (available when authMethod is OAUTH2)
+ */
+ public String accessToken;
+
+ /**
+ * The user password (available when authMethod is USER_PASSWORD)
+ */
+ public String password;
+
+ /**
+ * A boolean indicating if the user has validated his email adddress (available when authMethod is USER_PASSWORD)
+ */
+ public boolean isEmailVerified;
+}
View
33 app/securesocial/provider/UserId.java
@@ -0,0 +1,33 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+/**
+ * A class to uniquely identify users. This combines the id the user has on
+ * an external service (eg: twitter, facebook) with the provider type.
+ */
+public class UserId implements java.io.Serializable {
+ /**
+ * The id the user has in a external service.
+ */
+ public String id;
+
+ /**
+ * The provider this user belongs to.
+ */
+ public ProviderType provider;
+}
View
139 app/securesocial/provider/UserService.java
@@ -0,0 +1,139 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider;
+
+/**
+ * A class that provides the means to find save and create users
+ * for the SecureSocial Module.
+ *
+ * @see DefaultUserService
+ */
+public class UserService {
+ /**
+ * This is the interface that defines the behaviour for UserService.
+ * There is a default implementation in the DefaultUserService class that
+ * stores things in a map. This is just to provide an example, as a real
+ * implementation should persist things in a database
+ *
+ * @see DefaultUserService
+ */
+ public interface Service {
+ /**
+ * Finds a SocialUser that matches the id
+ *
+ * @param id A UserId object
+ * @return A SocialUser instance or null if no user matches the specified id.
+ */
+ SocialUser find(UserId id);
+
+ /**
+ * Saves the user in the backing store.
+ *
+ * @param user A SocialUser object
+ */
+ void save(SocialUser user);
+
+ /**
+ * Creates an activation request. This is needed for users that
+ * are creating an account in the system instead of using one in a 3rd party system.
+ *
+ * @param user The user that needs to be activated
+ * @return A string with a uuid that will be embedded in the welcome email.
+ */
+ String createActivation(SocialUser user);
+
+ /**
+ * Activates a user by setting the isEmailVerified field to true. This is only used
+ * for UsernamePassword accounts.
+ *
+ * @param uuid The uuid created using the createActivation method.
+ * @return Returns true if the user was activated - false otherwise.
+ */
+ boolean activate(String uuid);
+
+ /**
+ * This method deletes activations that were not completed by the user (The user did not follow the link
+ * in the welcome email).
+ *
+ * The method should delete the information store for the user too.
+ * store for the user.
+ */
+ void deletePendingActivations();
+ }
+
+ private static Service service;
+
+ /**
+ * Sets the Service implementation that will be used.
+ *
+ * @param delegate A Service instance.
+ * @See securesocial.jobs.Bootstrap
+ */
+ public static void setService(Service delegate) {
+ service = delegate;
+ }
+
+ /**
+ * @see securesocial.provider.UserService.Service#find(UserId)
+ *
+ */
+ public static SocialUser find(UserId id) {
+ checkIsInitialized();
+ return service.find(id);
+ }
+
+ private static void checkIsInitialized() {
+ if( service == null ) {
+ throw new RuntimeException("UserService was not properly initialized.");
+ }
+ }
+
+ /**
+ * @see securesocial.provider.UserService.Service#save(SocialUser)
+ *
+ */
+ public static void save(SocialUser user) {
+ checkIsInitialized();
+ service.save(user);
+ }
+
+ /**
+ * @see securesocial.provider.UserService.Service#createActivation(SocialUser)
+ *
+ */
+ public static String createActivation(SocialUser user) {
+ return service.createActivation(user);
+ }
+
+ /**
+ * @see securesocial.provider.UserService.Service#activate(String)
+ *
+ */
+ public static boolean activate(String uuid) {
+ checkIsInitialized();
+ return service.activate(uuid);
+ }
+
+ /**
+ * @see securesocial.provider.UserService.Service#deletePendingActivations()
+ *
+ */
+ public static void deletePendingActivations() {
+ checkIsInitialized();
+ service.deletePendingActivations();
+ }
+}
View
61 app/securesocial/provider/providers/FacebookProvider.java
@@ -0,0 +1,61 @@
+/**
+* Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+package securesocial.provider.providers;
+
+import com.google.gson.JsonObject;
+import play.Logger;
+import play.libs.WS;
+import securesocial.provider.*;
+
+import java.util.Map;
+
+/**
+ * A Facebook Provider
+ */
+public class FacebookProvider extends OAuth2Provider
+{
+ private static final String ME_API = "https://graph.facebook.com/me?fields=name,picture,email&access_token=%s";
+ private static final String ERROR = "error";
+ private static final String MESSAGE = "message";
+ private static final String TYPE = "type";
+ private static final String ID = "id";
+ private static final String NAME = "name";
+ private static final String PICTURE = "picture";
+ private static final String EMAIL = "email";
+
+ public FacebookProvider() {
+ super(ProviderType.facebook);
+ }
+
+ @Override
+ protected void fillProfile(SocialUser user, Map<String, Object> authContext) {
+ JsonObject me = WS.url(ME_API, user.accessToken).get().getJson().getAsJsonObject();
+ JsonObject error = me.getAsJsonObject(ERROR);
+
+ if ( error != null ) {
+ final String message = error.get(MESSAGE).getAsString();
+ final String type = error.get(TYPE).getAsString();
+ Logger.error("Error retrieving profile information from Facebook. Error type: %s, message: %s.", type, message);
+ throw new AuthenticationException();
+ }
+
+ user.id.id = me.get(ID).getAsString();
+ user.displayName = me.get(NAME).getAsString();
+ user.avatarUrl = me.get(PICTURE).getAsString();
+ user.email = me.get(EMAIL).getAsString();
+ }
+}
View
91 app/securesocial/provider/providers/FoursquareProvider.java
@@ -0,0 +1,91 @@
+/**
+ * Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package securesocial.provider.providers;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import play.Logger;
+import play.libs.WS;
+import securesocial.provider.*;
+
+import java.util.Map;
+
+/**
+ * A provider for Foursquare
+ */
+public class FoursquareProvider extends OAuth2Provider {
+ private static final String SELF_API = "https://api.foursquare.com/v2/users/self?oauth_token=%s";
+ private static final String META = "meta";
+ private static final String CODE = "code";
+ private static final String ERROR_TYPE = "errorType";
+ private static final String ERROR_DETAIL = "errorDetail";
+ private static final String RESPONSE = "response";
+ private static final String USER = "user";
+ private static final String ID = "id";
+ private static final String FIRST_NAME = "firstName";
+ private static final String LAST_NAME = "lastName";
+ private static final String SPACE = " ";
+ private static final String PHOTO = "photo";
+ private static final String CONTACT = "contact";
+ private static final String EMAIL = "email";
+
+ public FoursquareProvider() {
+ super(ProviderType.foursquare);
+ }
+
+ @Override
+ protected void fillProfile(SocialUser user, Map<String, Object> authContext) {
+ JsonObject me = WS.url(SELF_API, user.accessToken).get().getJson().getAsJsonObject();
+ JsonObject meta = me.getAsJsonObject(META);
+
+ if ( meta.get(CODE).getAsInt() != 200 ) {
+ final String errorType = meta.get(ERROR_TYPE).getAsString();
+ final String errorDetail = meta.get(ERROR_DETAIL).getAsString();
+ Logger.error("Error retrieving profile information from Foursquare. Error type: %s, detail: %s.", errorType, errorDetail);
+ throw new AuthenticationException();
+ }
+
+ JsonObject response = me.getAsJsonObject(RESPONSE);
+ if ( response == null ) {
+ throw new AuthenticationException();
+ }
+
+ JsonObject userInfo = response.getAsJsonObject(USER);
+ if( userInfo == null ) {
+ throw new AuthenticationException();
+ }
+
+ user.id.id = userInfo.get(ID).getAsString();
+ user.displayName = userInfo.get(FIRST_NAME).getAsString();
+ final JsonElement lastName = userInfo.get(LAST_NAME);
+ if ( lastName != null ) {
+ user.displayName = fullName(user.displayName, lastName.getAsString());
+ }
+ user.avatarUrl = userInfo.get(PHOTO).getAsString();
+ final JsonObject contact = userInfo.getAsJsonObject(CONTACT);
+ if ( contact != null ) {
+ final JsonElement userEmail = contact.get(EMAIL);
+ if ( userEmail != null ) {
+ user.email = userEmail.getAsString();
+ }
+ }
+ }
+
+ static String fullName(String first, String last) {
+ return new StringBuilder(first).append(SPACE).append(last).toString();
+ }
+}
View
70 app/securesocial/provider/providers/GoogleProvider.java
@@ -0,0 +1,70 @@
+/**
+ * Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package securesocial.provider.providers;
+
+import com.google.gson.JsonElement;
+import play.libs.OpenID;
+import play.libs.WS;
+import securesocial.provider.*;
+
+import java.util.Map;
+
+/**
+ * A Google provider that implements OpenID 2 + OAuth extensions.
+ * In a single flow the user gets authenticated and a token that can be used to invoke
+ * Google's APIs is retrieved.
+ */
+public class GoogleProvider extends OpenIDOAuthHybridProvider {
+ private static final String USER_FORMAT = "https://www.google.com/accounts/o8/id";
+ private static final String EMAIL = "email";
+ private static final String FIRST_NAME = "firstName";
+ private static final String LAST_NAME = "lastName";
+ private static final String HTTP_AXSCHEMA_ORG_CONTACT_EMAIL = "http://axschema.org/contact/email";
+ private static final String HTTP_AXSCHEMA_ORG_NAME_PERSON_FIRST = "http://axschema.org/namePerson/first";
+ private static final String HTTP_AXSCHEMA_ORG_NAME_PERSON_LAST = "http://axschema.org/namePerson/last";
+ private static final String SELF_API = "https://www-opensocial.googleusercontent.com/api/people/@me/@self";
+ private static final String ENTRY = "entry";
+ private static final String THUMBNAIL_URL = "thumbnailUrl";
+
+ public GoogleProvider() {
+ super(ProviderType.google, USER_FORMAT);
+ authMethod = AuthenticationMethod.OPENID_OAUTH_HYBRID;
+ }
+
+ @Override
+ protected void configure(OpenID openId) {
+ openId.required(EMAIL, HTTP_AXSCHEMA_ORG_CONTACT_EMAIL);
+ openId.required(FIRST_NAME, HTTP_AXSCHEMA_ORG_NAME_PERSON_FIRST);
+ openId.required(LAST_NAME, HTTP_AXSCHEMA_ORG_NAME_PERSON_LAST);
+ }
+
+ @Override
+ protected void fillProfile(SocialUser user, Map<String, Object> authContext) {
+ OpenID.UserInfo info = (OpenID.UserInfo) authContext.get(OpenIDProvider.USER_INFO);
+ user.displayName = FoursquareProvider.fullName(info.extensions.get(FIRST_NAME),info.extensions.get(LAST_NAME));
+ user.email = info.extensions.get(EMAIL);
+
+ WS.HttpResponse response = WS.url(SELF_API).oauth(user.serviceInfo, user.token, user.secret).get();
+ if ( response.getStatus() != 200 ) {
+ // Amazingly, if there's an error Google replies with an html page ... if it were json I could
+ // log some info.
+ throw new AuthenticationException();
+ }
+ JsonElement contactInfo = response.getJson();
+ user.avatarUrl = contactInfo.getAsJsonObject().getAsJsonObject(ENTRY).get(THUMBNAIL_URL).getAsString();
+ }
+}
View
65 app/securesocial/provider/providers/LinkedInProvider.java
@@ -0,0 +1,65 @@
+/**
+ * Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package securesocial.provider.providers;
+
+import com.google.gson.JsonObject;
+import play.Logger;
+import play.libs.WS;
+import securesocial.provider.*;
+
+import java.util.Map;
+
+/**
+ * A provider for LinkedIn
+ */
+public class LinkedInProvider extends OAuth1Provider
+{
+ private static final String ME_API = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url)?format=json";
+ private static final String ERROR_CODE = "errorCode";
+ private static final String MESSAGE = "message";
+ private static final String REQUEST_ID = "requestId";
+ private static final String TIMESTAMP = "timestamp";
+ private static final String ID = "id";
+ private static final String FIRST_NAME = "firstName";
+ private static final String LAST_NAME = "lastName";
+ private static final String PICTURE_URL = "pictureUrl";
+
+ public LinkedInProvider() {
+ super(ProviderType.linkedin);
+ }
+
+ @Override
+ protected void fillProfile(SocialUser user, Map<String, Object> authContext) {
+ JsonObject me = WS.url(ME_API).oauth(user.serviceInfo,user.token, user.secret).get().getJson().getAsJsonObject();
+
+ if ( me.get(ERROR_CODE) != null ) {
+ int errorCode = me.get(ERROR_CODE).getAsInt();
+ final String message = me.get(MESSAGE).getAsString();
+ final String requestId = me.get(REQUEST_ID).getAsString();
+ final String timestamp = me.get(TIMESTAMP).getAsString();
+ Logger.error("Error retrieving profile information from LinkedIn. Error code: %s, message: %s, requestId: %s, timestamp: %s.",
+ errorCode, message, requestId, timestamp);
+ throw new AuthenticationException();
+ }
+ user.id.id = me.get(ID).getAsString();
+ user.displayName = FoursquareProvider.fullName(me.get(FIRST_NAME).getAsString(),me.get(LAST_NAME).getAsString());
+ user.avatarUrl = me.get(PICTURE_URL).getAsString();
+
+ // can't get the email because the LinkedIn API does not provide it.
+ //user.email = ;
+ }
+}
View
58 app/securesocial/provider/providers/MyOpenIDProvider.java
@@ -0,0 +1,58 @@
+/**
+ * Copyright 2011 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package securesocial.provider.providers;
+
+import play.libs.OpenID;
+import securesocial.provider.OpenIDProvider;
+import securesocial.provider.ProviderType;
+import securesocial.provider.SocialUser;
+
+import java.util.Map;
+
+/**
+ * A provider for MyOpenID
+ */
+public class MyOpenIDProvider extends OpenIDProvider{
+ private static final String USER_FORMAT = "http://{username}.myopenid.com/";
+ private static final String FULL_NAME = "fullName";
+ private static f