Skip to content
This repository has been archived by the owner on Feb 10, 2021. It is now read-only.

Commit

Permalink
Add users on startup feature
Browse files Browse the repository at this point in the history
  • Loading branch information
slimandslam committed Apr 5, 2015
1 parent 86ea03e commit 3b5de42
Show file tree
Hide file tree
Showing 4 changed files with 173 additions and 179 deletions.
9 changes: 9 additions & 0 deletions samples/java/play-authenticate-usage/README user-injection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Play Authenticate sample Java application

This modified version of play-authenticate-usage
has a YAML file in conf/intial-data.yml that
injects a couple of users into the app when
it first starts up. The injection routine is at the
bottom of the app/Global.java file. Users and
accompanying roles are injected into the appropriate
tables in the Play database at startup.
51 changes: 49 additions & 2 deletions samples/java/play-authenticate-usage/app/Global.java
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,17 +1,32 @@
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import models.SecurityRole;
import models.User;

import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.PlayAuthenticate.Resolver;
import com.feth.play.module.pa.exceptions.AccessDeniedException;
import com.feth.play.module.pa.exceptions.AuthException;

import controllers.routes;
import javax.persistence.*;

import com.avaje.ebean.Ebean;

import play.libs.F;
import play.libs.Yaml;
import play.mvc.Http;
import play.mvc.Result;
import play.Application;
import play.GlobalSettings;
import play.mvc.Call;
import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;

public class Global extends GlobalSettings {

Expand Down Expand Up @@ -68,16 +83,48 @@ public Call onException(final AuthException e) {
});

initialData();
insertData();
}

private void initialData() {
if (SecurityRole.find.findRowCount() == 0) {
for (final String roleName : Arrays
.asList(controllers.Application.USER_ROLE)) {
.asList(controllers.Application.USER_ROLE, controllers.Application.ADMIN_ROLE )) {
final SecurityRole role = new SecurityRole();
role.roleName = roleName;
role.save();
}
}
}
}

public static void insertData() {
final boolean noRoles = Ebean.find(SecurityRole.class).findRowCount() == 0;
final boolean noUsers = Ebean.find(User.class).findRowCount() == 0;

// This only gets run if there are either no roles or no users
// already instantiated in the db
if (noRoles || noUsers) {
@SuppressWarnings("unchecked")
final Map<String, List<Object>> all = (Map<String, List<Object>>) Yaml.load("initial-data.yml");

try {
if (noRoles) {
Ebean.save(all.get("roles"));
}

if (noUsers) {
// Insert users first
Ebean.save(all.get("users"));
for (final Object user : all.get("users")) {
// Insert the User/SecurityRole relation
Ebean.saveManyToManyAssociations(user, "roles");
}
}
} catch (Exception ex) {
// Logger.error(ex.getInvalid().toString());
throw ex;
}
}
}
}

250 changes: 73 additions & 177 deletions samples/java/play-authenticate-usage/app/controllers/Application.java
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,6 @@

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

import play.libs.ws.*;
import play.libs.F.Function;
import play.libs.F.Promise;
import play.libs.Json;

import models.User;
import play.Routes;
Expand All @@ -28,178 +14,88 @@
import providers.MyUsernamePasswordAuthProvider.MyLogin;
import providers.MyUsernamePasswordAuthProvider.MySignup;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValue;

import views.html.*;
import be.objectify.deadbolt.java.actions.Group;
import be.objectify.deadbolt.java.actions.Restrict;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider;
import com.feth.play.module.pa.user.AuthUser;

public class Application extends Controller {

public static final String FLASH_MESSAGE_KEY = "message";
public static final String FLASH_ERROR_KEY = "error";
public static final String USER_ROLE = "user";

public static Result index() {
return ok(index.render());
}

public static User getLocalUser(final Session session) {
final AuthUser currentAuthUser = PlayAuthenticate.getUser(session);
final User localUser = User.findByAuthUserIdentity(currentAuthUser);
return localUser;
}

@Restrict(@Group(Application.USER_ROLE))
public static Result restricted() {
final User localUser = getLocalUser(session());
return ok(restricted.render(localUser));
}

@Restrict(@Group(Application.USER_ROLE))
public static Result profile() {
final User localUser = getLocalUser(session());
return ok(profile.render(localUser));
}

public static Result login() {
return ok(login.render(MyUsernamePasswordAuthProvider.LOGIN_FORM));
}

public static Result doLogin() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MyLogin> filledForm = MyUsernamePasswordAuthProvider.LOGIN_FORM
.bindFromRequest();
if (filledForm.hasErrors()) {
// User did not fill everything properly
return badRequest(login.render(filledForm));
} else {
// Everything was filled
return UsernamePasswordAuthProvider.handleLogin(ctx());
}
}

public static Result signup() {
return ok(signup.render(MyUsernamePasswordAuthProvider.SIGNUP_FORM));
}

public static Result jsRoutes() {
return ok(
Routes.javascriptRouter("jsRoutes",
controllers.routes.javascript.Signup.forgotPassword()))
.as("text/javascript");
}

public static String captchaResp(String gcaptchaCode) {
String googUrl = "https://www.google.com/recaptcha/api/siteverify";
String encSecret = "";
String encCapcode = "";
String error = "-1";
URL url = null;
// Get the secret key
Config conf = ConfigFactory.load();
String gsecretKey = conf.getString("play-authenticate.gcaptcha.gsecretKey");
// Debug -- show values on console
// System.out.println("gsecretKey = " + gsecretKey);
// System.out.println("captchacode = " + gcaptchaCode);
try {
encSecret = URLEncoder.encode(gsecretKey, "UTF-8");
encCapcode = URLEncoder.encode(gcaptchaCode, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return error;
}
String query = "secret=" + encSecret + "&response=" + encCapcode;
try {
url = new URL(googUrl + "?" + query);
} catch (MalformedURLException e) {
e.printStackTrace();
return error;
}
StringBuilder stringBuilder = new StringBuilder();
try {
// Check if Google validates the captcha response
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
// 10 seconds max to respond
connection.setReadTimeout(10 * 1000);
connection.connect();
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ connection.getResponseCode());
}
// read the output
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return error;
}

public static Result doSignup() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MySignup> filledForm = MyUsernamePasswordAuthProvider.SIGNUP_FORM
.bindFromRequest();

final Map<String, String[]> values = request().body().asFormUrlEncoded();
final String gcaptchaCode = values.get("g-recaptcha-response")[0];
String error = "-1";

if (filledForm.hasErrors()) {
// User did not fill everything properly
return badRequest(signup.render(filledForm));
} else {
// Everything was filled
// do something with your part of the form before handling the user
// signup
//
// Check if captcha was filled in
if (gcaptchaCode == null || gcaptchaCode.isEmpty()) {
flash("error", "You need to successfully solve the reCAPTCHA at the bottom of the form in order to signup.");
return badRequest(signup.render(filledForm));
}

// Find out if Google likes the Captcha
String json = captchaResp(gcaptchaCode);

// Check if an error occured while contacting Google and processing
if (json.equals(error)) {
flash("error", "An error occured while attempting to resolve the Google Captcha. Try again?");
return badRequest(signup.render(filledForm));
}

// Turn the json string into a Json object
JsonNode jobj = Json.parse(json);
Boolean captchaPassed = jobj.findPath("success").booleanValue();

if (captchaPassed) {
return UsernamePasswordAuthProvider.handleSignup(ctx());
} else {
// Error codes are in jobj.findPath("error-codes").textValue();
flash("error", "You need to successfully solve the reCAPTCHA at the bottom of the form in order to signup.");
return badRequest(signup.render(filledForm));
}
}
}

public static String formatTimestamp(final long t) {
return new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").format(new Date(t));
}
public static final String FLASH_MESSAGE_KEY = "message";
public static final String FLASH_ERROR_KEY = "error";
public static final String USER_ROLE = "user";
public static final String ADMIN_ROLE = "admin";

public static Result index() {
return ok(index.render());
}

public static User getLocalUser(final Session session) {
final AuthUser currentAuthUser = PlayAuthenticate.getUser(session);
final User localUser = User.findByAuthUserIdentity(currentAuthUser);
return localUser;
}

@Restrict(@Group(Application.USER_ROLE))
public static Result restricted() {
final User localUser = getLocalUser(session());
return ok(restricted.render(localUser));
}

@Restrict(@Group(Application.USER_ROLE))
public static Result profile() {
final User localUser = getLocalUser(session());
return ok(profile.render(localUser));
}

public static Result login() {
return ok(login.render(MyUsernamePasswordAuthProvider.LOGIN_FORM));
}

public static Result doLogin() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MyLogin> filledForm = MyUsernamePasswordAuthProvider.LOGIN_FORM
.bindFromRequest();
if (filledForm.hasErrors()) {
// User did not fill everything properly
return badRequest(login.render(filledForm));
} else {
// Everything was filled
return UsernamePasswordAuthProvider.handleLogin(ctx());
}
}

public static Result signup() {
return ok(signup.render(MyUsernamePasswordAuthProvider.SIGNUP_FORM));
}

public static Result jsRoutes() {
return ok(
Routes.javascriptRouter("jsRoutes",
controllers.routes.javascript.Signup.forgotPassword()))
.as("text/javascript");
}

public static Result doSignup() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MySignup> filledForm = MyUsernamePasswordAuthProvider.SIGNUP_FORM
.bindFromRequest();
if (filledForm.hasErrors()) {
// User did not fill everything properly
return badRequest(signup.render(filledForm));
} else {
// Everything was filled
// do something with your part of the form before handling the user
// signup
return UsernamePasswordAuthProvider.handleSignup(ctx());
}
}

public static String formatTimestamp(final long t) {
return new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").format(new Date(t));
}

}
Loading

0 comments on commit 3b5de42

Please sign in to comment.