source: Dev/branches/play+dojo/app/controllers/Auth.java @ 322

Last change on this file since 322 was 322, checked in by hendrikvanantwerpen, 13 years ago

Added Play! framework and application with Jena dependency. Working on
the basic things now (login/register), after that start implementing
our data model.

File size: 2.3 KB
RevLine 
[322]1package controllers;
2
3import play.*;
4import play.mvc.*;
5
6import views.html.*;
7
8import database.*;
9
10import org.codehaus.jackson.*;
11
12public class Auth extends Controller {
13 
14    private static final String AUTH_COOKIE = "rft_uid";
15
16    private static void setSessionCookie(String uid) {
17        response().setCookie(AUTH_COOKIE, uid, 3600, "/api");
18    }
19
20    public static Result restore() {
21        Http.Cookie c = request().cookies().get(AUTH_COOKIE);
22        if ( c != null ) {
23            String uid = c.value();
24            // lookup c
25            setSessionCookie(uid);
26        }
27        return unauthorized();
28    }
29
30    public static Result register() {
31        JsonNode json = request().body().asJson();
32        String email = json.findPath("email").getTextValue();
33        String password = json.findPath("password").getTextValue();
34        if ( json == null ) {
35            return badRequest("Body expected.");
36        }
37        Model model = DB.getDefault().getModel();
38        boolean exists = userExists(model, email);
39        if ( exists ) {
40            return forbidden();
41        } else {
42            UUID uid = UUID.generate();
43            double salt = rand();
44            model.createResource(DB.NS+uid)
45                .addProperty(RDF.type,"rtr:User")
46                .addProperty(DB.PREDICATES_NS+"email", email)
47                .addProperty(DB.PREDICATES_NS+"passwordHash", sha1(password,salt))
48                .addProperty(DB.PREDICATES_NS+"passwordSalt", salt);
49
50            setSessionCookie(uid);
51            return created();
52        }
53    }
54 
55    private boolean userExists(Model model, String email) {
56        Query query = QueryFactory.create(DB.PREFIX+"ASK { ?user rtr:email \""+email+"\" . }") ;
57        QueryExecution qexec = QueryExecutionFactory.create(query, model) ;
58        boolean result = qexec.execAsk() ;
59        qexec.close() ;
60        return result;
61    }
62
63    public static Result login() {
64        JsonNode json = request().body().asJson();
65        if ( json == null ) {
66            return restore();
67        } else {
68            String email = json.findPath("email").getTextValue();
69            String password = json.findPath("password").getTextValue();
70            // authenticate
71            setSessionCookie("XYZ");
72            return ok();
73        }
74    }
75 
76
77
78}
Note: See TracBrowser for help on using the repository browser.