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

Commit 3b5de42

Browse files
committed
Add users on startup feature
1 parent 86ea03e commit 3b5de42

4 files changed

Lines changed: 173 additions & 179 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Play Authenticate sample Java application
2+
3+
This modified version of play-authenticate-usage
4+
has a YAML file in conf/intial-data.yml that
5+
injects a couple of users into the app when
6+
it first starts up. The injection routine is at the
7+
bottom of the app/Global.java file. Users and
8+
accompanying roles are injected into the appropriate
9+
tables in the Play database at startup.

samples/java/play-authenticate-usage/app/Global.java

100644100755
Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,32 @@
11
import java.util.Arrays;
2+
import java.util.List;
3+
import java.util.HashMap;
4+
import java.util.Iterator;
5+
import java.util.Map;
26

37
import models.SecurityRole;
8+
import models.User;
49

510
import com.feth.play.module.pa.PlayAuthenticate;
611
import com.feth.play.module.pa.PlayAuthenticate.Resolver;
712
import com.feth.play.module.pa.exceptions.AccessDeniedException;
813
import com.feth.play.module.pa.exceptions.AuthException;
914

1015
import controllers.routes;
16+
import javax.persistence.*;
1117

18+
import com.avaje.ebean.Ebean;
19+
20+
import play.libs.F;
21+
import play.libs.Yaml;
22+
import play.mvc.Http;
23+
import play.mvc.Result;
1224
import play.Application;
1325
import play.GlobalSettings;
1426
import play.mvc.Call;
27+
import play.db.ebean.*;
28+
import play.data.format.*;
29+
import play.data.validation.*;
1530

1631
public class Global extends GlobalSettings {
1732

@@ -68,16 +83,48 @@ public Call onException(final AuthException e) {
6883
});
6984

7085
initialData();
86+
insertData();
7187
}
7288

7389
private void initialData() {
7490
if (SecurityRole.find.findRowCount() == 0) {
7591
for (final String roleName : Arrays
76-
.asList(controllers.Application.USER_ROLE)) {
92+
.asList(controllers.Application.USER_ROLE, controllers.Application.ADMIN_ROLE )) {
7793
final SecurityRole role = new SecurityRole();
7894
role.roleName = roleName;
7995
role.save();
8096
}
8197
}
8298
}
83-
}
99+
100+
public static void insertData() {
101+
final boolean noRoles = Ebean.find(SecurityRole.class).findRowCount() == 0;
102+
final boolean noUsers = Ebean.find(User.class).findRowCount() == 0;
103+
104+
// This only gets run if there are either no roles or no users
105+
// already instantiated in the db
106+
if (noRoles || noUsers) {
107+
@SuppressWarnings("unchecked")
108+
final Map<String, List<Object>> all = (Map<String, List<Object>>) Yaml.load("initial-data.yml");
109+
110+
try {
111+
if (noRoles) {
112+
Ebean.save(all.get("roles"));
113+
}
114+
115+
if (noUsers) {
116+
// Insert users first
117+
Ebean.save(all.get("users"));
118+
for (final Object user : all.get("users")) {
119+
// Insert the User/SecurityRole relation
120+
Ebean.saveManyToManyAssociations(user, "roles");
121+
}
122+
}
123+
} catch (Exception ex) {
124+
// Logger.error(ex.getInvalid().toString());
125+
throw ex;
126+
}
127+
}
128+
}
129+
}
130+

samples/java/play-authenticate-usage/app/controllers/Application.java

100644100755
Lines changed: 73 additions & 177 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,6 @@
22

33
import java.text.SimpleDateFormat;
44
import java.util.Date;
5-
import java.util.Map;
6-
import java.io.BufferedReader;
7-
import java.io.IOException;
8-
import java.io.InputStreamReader;
9-
import java.net.HttpURLConnection;
10-
import java.net.MalformedURLException;
11-
import java.io.UnsupportedEncodingException;
12-
import java.net.URL;
13-
import java.net.URLEncoder;
14-
15-
import play.libs.ws.*;
16-
import play.libs.F.Function;
17-
import play.libs.F.Promise;
18-
import play.libs.Json;
195

206
import models.User;
217
import play.Routes;
@@ -28,178 +14,88 @@
2814
import providers.MyUsernamePasswordAuthProvider.MyLogin;
2915
import providers.MyUsernamePasswordAuthProvider.MySignup;
3016

31-
import com.typesafe.config.Config;
32-
import com.typesafe.config.ConfigFactory;
33-
import com.typesafe.config.ConfigValue;
34-
3517
import views.html.*;
3618
import be.objectify.deadbolt.java.actions.Group;
3719
import be.objectify.deadbolt.java.actions.Restrict;
3820

39-
import com.fasterxml.jackson.core.JsonProcessingException;
40-
import com.fasterxml.jackson.databind.JsonNode;
41-
import com.fasterxml.jackson.databind.ObjectMapper;
42-
4321
import com.feth.play.module.pa.PlayAuthenticate;
4422
import com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider;
4523
import com.feth.play.module.pa.user.AuthUser;
4624

4725
public class Application extends Controller {
4826

49-
public static final String FLASH_MESSAGE_KEY = "message";
50-
public static final String FLASH_ERROR_KEY = "error";
51-
public static final String USER_ROLE = "user";
52-
53-
public static Result index() {
54-
return ok(index.render());
55-
}
56-
57-
public static User getLocalUser(final Session session) {
58-
final AuthUser currentAuthUser = PlayAuthenticate.getUser(session);
59-
final User localUser = User.findByAuthUserIdentity(currentAuthUser);
60-
return localUser;
61-
}
62-
63-
@Restrict(@Group(Application.USER_ROLE))
64-
public static Result restricted() {
65-
final User localUser = getLocalUser(session());
66-
return ok(restricted.render(localUser));
67-
}
68-
69-
@Restrict(@Group(Application.USER_ROLE))
70-
public static Result profile() {
71-
final User localUser = getLocalUser(session());
72-
return ok(profile.render(localUser));
73-
}
74-
75-
public static Result login() {
76-
return ok(login.render(MyUsernamePasswordAuthProvider.LOGIN_FORM));
77-
}
78-
79-
public static Result doLogin() {
80-
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
81-
final Form<MyLogin> filledForm = MyUsernamePasswordAuthProvider.LOGIN_FORM
82-
.bindFromRequest();
83-
if (filledForm.hasErrors()) {
84-
// User did not fill everything properly
85-
return badRequest(login.render(filledForm));
86-
} else {
87-
// Everything was filled
88-
return UsernamePasswordAuthProvider.handleLogin(ctx());
89-
}
90-
}
91-
92-
public static Result signup() {
93-
return ok(signup.render(MyUsernamePasswordAuthProvider.SIGNUP_FORM));
94-
}
95-
96-
public static Result jsRoutes() {
97-
return ok(
98-
Routes.javascriptRouter("jsRoutes",
99-
controllers.routes.javascript.Signup.forgotPassword()))
100-
.as("text/javascript");
101-
}
102-
103-
public static String captchaResp(String gcaptchaCode) {
104-
String googUrl = "https://www.google.com/recaptcha/api/siteverify";
105-
String encSecret = "";
106-
String encCapcode = "";
107-
String error = "-1";
108-
URL url = null;
109-
// Get the secret key
110-
Config conf = ConfigFactory.load();
111-
String gsecretKey = conf.getString("play-authenticate.gcaptcha.gsecretKey");
112-
// Debug -- show values on console
113-
// System.out.println("gsecretKey = " + gsecretKey);
114-
// System.out.println("captchacode = " + gcaptchaCode);
115-
try {
116-
encSecret = URLEncoder.encode(gsecretKey, "UTF-8");
117-
encCapcode = URLEncoder.encode(gcaptchaCode, "UTF-8");
118-
} catch (UnsupportedEncodingException e) {
119-
e.printStackTrace();
120-
return error;
121-
}
122-
String query = "secret=" + encSecret + "&response=" + encCapcode;
123-
try {
124-
url = new URL(googUrl + "?" + query);
125-
} catch (MalformedURLException e) {
126-
e.printStackTrace();
127-
return error;
128-
}
129-
StringBuilder stringBuilder = new StringBuilder();
130-
try {
131-
// Check if Google validates the captcha response
132-
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
133-
connection.setRequestMethod("GET");
134-
connection.setRequestProperty("Accept", "application/json");
135-
// 10 seconds max to respond
136-
connection.setReadTimeout(10 * 1000);
137-
connection.connect();
138-
if (connection.getResponseCode() != 200) {
139-
throw new RuntimeException("Failed : HTTP error code : "
140-
+ connection.getResponseCode());
141-
}
142-
// read the output
143-
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
144-
String line = null;
145-
while ((line = reader.readLine()) != null) {
146-
stringBuilder.append(line);
147-
}
148-
return stringBuilder.toString();
149-
} catch (Exception e) {
150-
e.printStackTrace();
151-
}
152-
return error;
153-
}
154-
155-
public static Result doSignup() {
156-
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
157-
final Form<MySignup> filledForm = MyUsernamePasswordAuthProvider.SIGNUP_FORM
158-
.bindFromRequest();
159-
160-
final Map<String, String[]> values = request().body().asFormUrlEncoded();
161-
final String gcaptchaCode = values.get("g-recaptcha-response")[0];
162-
String error = "-1";
163-
164-
if (filledForm.hasErrors()) {
165-
// User did not fill everything properly
166-
return badRequest(signup.render(filledForm));
167-
} else {
168-
// Everything was filled
169-
// do something with your part of the form before handling the user
170-
// signup
171-
//
172-
// Check if captcha was filled in
173-
if (gcaptchaCode == null || gcaptchaCode.isEmpty()) {
174-
flash("error", "You need to successfully solve the reCAPTCHA at the bottom of the form in order to signup.");
175-
return badRequest(signup.render(filledForm));
176-
}
177-
178-
// Find out if Google likes the Captcha
179-
String json = captchaResp(gcaptchaCode);
180-
181-
// Check if an error occured while contacting Google and processing
182-
if (json.equals(error)) {
183-
flash("error", "An error occured while attempting to resolve the Google Captcha. Try again?");
184-
return badRequest(signup.render(filledForm));
185-
}
186-
187-
// Turn the json string into a Json object
188-
JsonNode jobj = Json.parse(json);
189-
Boolean captchaPassed = jobj.findPath("success").booleanValue();
190-
191-
if (captchaPassed) {
192-
return UsernamePasswordAuthProvider.handleSignup(ctx());
193-
} else {
194-
// Error codes are in jobj.findPath("error-codes").textValue();
195-
flash("error", "You need to successfully solve the reCAPTCHA at the bottom of the form in order to signup.");
196-
return badRequest(signup.render(filledForm));
197-
}
198-
}
199-
}
200-
201-
public static String formatTimestamp(final long t) {
202-
return new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").format(new Date(t));
203-
}
27+
public static final String FLASH_MESSAGE_KEY = "message";
28+
public static final String FLASH_ERROR_KEY = "error";
29+
public static final String USER_ROLE = "user";
30+
public static final String ADMIN_ROLE = "admin";
31+
32+
public static Result index() {
33+
return ok(index.render());
34+
}
35+
36+
public static User getLocalUser(final Session session) {
37+
final AuthUser currentAuthUser = PlayAuthenticate.getUser(session);
38+
final User localUser = User.findByAuthUserIdentity(currentAuthUser);
39+
return localUser;
40+
}
41+
42+
@Restrict(@Group(Application.USER_ROLE))
43+
public static Result restricted() {
44+
final User localUser = getLocalUser(session());
45+
return ok(restricted.render(localUser));
46+
}
47+
48+
@Restrict(@Group(Application.USER_ROLE))
49+
public static Result profile() {
50+
final User localUser = getLocalUser(session());
51+
return ok(profile.render(localUser));
52+
}
53+
54+
public static Result login() {
55+
return ok(login.render(MyUsernamePasswordAuthProvider.LOGIN_FORM));
56+
}
57+
58+
public static Result doLogin() {
59+
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
60+
final Form<MyLogin> filledForm = MyUsernamePasswordAuthProvider.LOGIN_FORM
61+
.bindFromRequest();
62+
if (filledForm.hasErrors()) {
63+
// User did not fill everything properly
64+
return badRequest(login.render(filledForm));
65+
} else {
66+
// Everything was filled
67+
return UsernamePasswordAuthProvider.handleLogin(ctx());
68+
}
69+
}
70+
71+
public static Result signup() {
72+
return ok(signup.render(MyUsernamePasswordAuthProvider.SIGNUP_FORM));
73+
}
74+
75+
public static Result jsRoutes() {
76+
return ok(
77+
Routes.javascriptRouter("jsRoutes",
78+
controllers.routes.javascript.Signup.forgotPassword()))
79+
.as("text/javascript");
80+
}
81+
82+
public static Result doSignup() {
83+
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
84+
final Form<MySignup> filledForm = MyUsernamePasswordAuthProvider.SIGNUP_FORM
85+
.bindFromRequest();
86+
if (filledForm.hasErrors()) {
87+
// User did not fill everything properly
88+
return badRequest(signup.render(filledForm));
89+
} else {
90+
// Everything was filled
91+
// do something with your part of the form before handling the user
92+
// signup
93+
return UsernamePasswordAuthProvider.handleSignup(ctx());
94+
}
95+
}
96+
97+
public static String formatTimestamp(final long t) {
98+
return new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").format(new Date(t));
99+
}
204100

205101
}

0 commit comments

Comments
 (0)