forked from bioversity/Crop-Ontology
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
115 lines (91 loc) · 2.97 KB
/
auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
importPackage(javax.servlet.http);
/**
* authentication system!!!
*/
var auth = (function(){
/**
* check if we're logged in
* by looking inside the request for a "user" cookie token
* and checking if it exists in the datastore.
* if it exists, return the entire user-entity of that result,
* otherwise return false
*/
function getUser(request) {
var cookies = request.getCookies();
if(!cookies)
return false;
// find the user cookie
var userCookie = false;
for(var i=0; i<cookies.length; i++) {
if(cookies[i].getName().equals("user")) {
userCookie = cookies[i];
}
}
if(!userCookie) // no user cookie found
return false;
// get the token (value of cookie)
var token = userCookie.getValue();
// make sure the token is not an empty string :)
if(token.equals("") || !token)
return false;
// check if it exists in datastore
var users = googlestore.query("user")
.filter("token", "=", token)
.fetch();
if(!users.length) // doesn't exist
return false;
//if(q.length > 1) // what?!? more than 1 token, XXX logout
// great we found it, return it!
return users[0];
}
/**
* username&password, generate token, store it in DB for this user
* and add the "user" cookie
*/
function login(response, username, hashedPassword) {
var res = googlestore.query("user")
.filter("username", "=", username)
.filter("password", "=", hashedPassword)
.fetch(1);
if(!res.length) { // user not found
return false;
} else {
var userEntity = res[0],
token = tokenGenerator();
userEntity.setProperty("token", token);
googlestore.put(userEntity);
// add a cookie
var cookie = new Cookie("user", token);
// 30 years :)
cookie.setMaxAge(30 * 365 * 24 * 60 * 60);
response.addCookie(cookie);
return true;
}
}
function tokenGenerator() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 8; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function isAdmin(userEntity) {
var admin = userEntity.getProperty("admin");
if(admin && admin == true)
return true;
else
return false;
}
function getLanguage(userEntity) {
if(!userEntity) return false;
var language = userEntity.getProperty("language");
return language;
}
return {
getUser: getUser,
login: login,
isAdmin: isAdmin,
getLanguage: getLanguage
};
})();
exports = auth;