]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/dojo/openils/User.js
bd91ba878db7dbf4eb148a327e0d57109d706a46
[Evergreen.git] / Open-ILS / web / js / dojo / openils / User.js
1 /* ---------------------------------------------------------------------------
2  * Copyright (C) 2008  Georgia Public Library Service
3  * Bill Erickson <erickson@esilibrary.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * ---------------------------------------------------------------------------
15  */
16
17
18 if(!dojo._hasResource["openils.User"]) {
19
20     dojo._hasResource["openils.User"] = true;
21     dojo.provide("openils.User");
22     dojo.require("DojoSRF");
23     dojo.require('openils.Event');
24     dojo.require('fieldmapper.Fieldmapper');
25     dojo.require('fieldmapper.OrgUtils');
26     dojo.require('openils.Util');
27     dojo.require('dojo.cookie');
28     dojo.requireLocalization("openils.User", "User");
29
30     dojo.declare('openils.User', null, {
31
32         user : null,
33         username : null,
34         passwd : null,
35         login_type : 'opac',
36         location : null,
37         authtoken : null,
38         authtime : null,
39         workstation : null,
40         permOrgCache : {},
41         sessionCache : {},
42     
43         constructor : function ( kwargs ) {
44             kwargs = kwargs || {};
45             this.id = kwargs.id;
46             this.user = kwargs.user;
47             this.passwd = kwargs.passwd;
48             this.authtoken = kwargs.authtoken || openils.User.authtoken;
49             this.authtime = kwargs.authtime || openils.User.authtime;
50             this.login_type = kwargs.login_type;
51             this.location = kwargs.location;
52             this.authcookie = kwargs.authcookie || openils.User.authcookie;
53             this.permOrgStoreCache = {}; /* permName => permOrgUnitStore map */
54
55             if (this.authcookie) this.authtoken = dojo.cookie(this.authcookie);
56             if (this.id && this.authtoken) this.user = this.getById( this.id );
57             else if (this.authtoken) this.getBySession();
58             else if (kwargs.login) this.login();
59
60             var id = this.id || (this.user && this.user.id) ? this.user.id() : null;
61             if(id && !this.permOrgCache[id])
62                 this.permOrgCache[id] = {};
63         },
64
65         getBySession : function(onComplete) {
66             var _u = this;
67             var req = ['open-ils.auth', 'open-ils.auth.session.retrieve'];
68             var params = [_u.authtoken];
69
70             if(this.sessionCache[this.authtoken]) {
71                 this.user = this.sessionCache[this.authtoken];
72                                 if (!openils.User.user) 
73                     openils.User.user = this.user;
74                 return this.user;
75             }
76
77             if(onComplete) {
78                 fieldmapper.standardRequest(
79                     req, {   
80                         async: true,
81                         params: params,
82                         oncomplete : function(r) {
83                             var user = r.recv().content();
84                             _u.user = user;
85                             _u.sessionCache[_u.authtoken] = user;
86                                                 if (!openils.User.user) openils.User.user = _u.user;
87                             if(onComplete)
88                                 onComplete(user);
89                         }
90                     }
91                 );
92             } else {
93                 _u.user = fieldmapper.standardRequest(req, params);
94                                 if (!openils.User.user) openils.User.user = _u.user;
95                 _u.sessionCache[_u.authtoken] = _u.user;
96                 return _u.user;
97             }
98         },
99     
100         getById : function(id, onComplete) {
101             var req = OpenSRF.CachedClientSession('open-ils.actor').request('open-ils.actor.user.retrieve', this.authtoken, id);
102             if(onComplete) {
103                 req.oncomplete = function(r) {
104                     var user = r.recv().content();
105                     onComplete(user);
106                 }
107                 req.send();
108             } else {
109                 req.timeout = 10;
110                 req.send();
111                 return req.recv().content();
112             }
113         },
114     
115     
116         /**
117          * Logs in, sets the authtoken/authtime vars, and fetches the logged in user
118          */
119         login_async : function(args, onComplete) {
120             var _u = this;
121
122             if (!args) args = {};
123             if (!args.username) args.username = _u.username;
124             if (!args.passwd) args.passwd = _u.passwd;
125             if (!args.type) args.type = _u.login_type;
126             if (!args.location) args.location = _u.location;
127
128             var initReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.init', args.username);
129     
130             initReq.oncomplete = function(r) {
131                 var seed = r.recv().content(); 
132                 var loginInfo = {
133                     username : args.username,
134                     password : hex_md5(seed + hex_md5(args.passwd)), 
135                     type : args.type,
136                     org : args.location,
137                     workstation : args.workstation
138                 };
139     
140                 var authReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.complete', loginInfo);
141                 authReq.oncomplete = function(rr) {
142                     var data = rr.recv().content();
143
144                     if(!data || !data.payload)
145                         throw new Error("Login Failed: " + js2JSON(data));
146
147                     _u.authtoken = data.payload.authtoken;
148                                         if (!openils.User.authtoken) openils.User.authtoken = _u.authtoken;
149                     _u.authtime = data.payload.authtime;
150                                         if (!openils.User.authtime) openils.User.authtime = _u.authtime;
151                     _u.getBySession(onComplete);
152                     if(_u.authcookie) {
153                         dojo.cookie(_u.authcookie, _u.authtoken, {path:'/'});
154                     }
155                 }
156                 authReq.send();
157             }
158     
159             initReq.send();
160         },
161
162         login : function(args) {
163             var _u = this;
164             if (!args) args = {};
165             if (!args.username) args.username = _u.username;
166             if (!args.passwd) args.passwd = _u.passwd;
167             if (!args.type) args.type = _u.login_type;
168             if (!args.location) args.location = _u.location;
169
170             var seed = fieldmapper.standardRequest(
171                 ['open-ils.auth', 'open-ils.auth.authenticate.init'],
172                 [args.username]
173             );
174
175             var loginInfo = {
176                 username : args.username,
177                 password : hex_md5(seed + hex_md5(args.passwd)), 
178                 type : args.type,
179                 org : args.location,
180                 workstation : args.workstation,
181             };
182
183             var data = fieldmapper.standardRequest(
184                 ['open-ils.auth', 'open-ils.auth.authenticate.complete'],
185                 [loginInfo]
186             );
187
188             if(!data || !data.payload) return false;
189
190             _u.authtoken = data.payload.authtoken;
191             if (!openils.User.authtoken) openils.User.authtoken = _u.authtoken;
192             _u.authtime = data.payload.authtime;
193             if (!openils.User.authtime) openils.User.authtime = _u.authtime;
194
195             if(_u.authcookie) {
196                 dojo.cookie(_u.authcookie, _u.authtoken, {path:'/'});
197             }
198
199             return true;
200         },
201
202     
203         /**
204          * Returns a list of the "highest" org units where the user has the given permission(s).
205          * @param permList A single permission or list of permissions
206          * @param includeDescendents If true, return a list of 'highest' orgs plus descendents
207          * @idlist If true, return a list of IDs instead of org unit objects
208          */
209         getPermOrgList : function(permList, onload, includeDescendents, idlist) {
210             if(typeof permList == 'string') permList = [permList];
211
212             var self = this;
213             var oncomplete = function(r) {
214                 var permMap = {};
215                 if(r) permMap = openils.Util.readResponse(r);
216                 var orgList = [];
217
218                 for(var i = 0; i < permList.length; i++) {
219                     var perm = permList[i];
220                     var permOrgList = permMap[perm] || self.permOrgCache[self.user.id()][perm];
221                     self.permOrgCache[self.user.id()][perm] = permOrgList;
222
223                     for(var j in permOrgList) {
224                         if(includeDescendents) {
225                             orgList = orgList.concat(
226                                 fieldmapper.aou.descendantNodeList(permOrgList[j]));
227                         } else {
228                             orgList = orgList.concat(fieldmapper.aou.findOrgUnit(permOrgList[j]));
229                         }
230                     }
231                 }
232
233                 // remove duplicates
234                 var trimmed = [];
235                 for(var idx in orgList) {
236                     var val = (idlist) ? orgList[idx].id() : orgList[idx];
237                     if(trimmed.indexOf(val) < 0)
238                         trimmed.push(val);
239                 }
240                 onload(trimmed);
241             };
242
243             var fetchList = [];
244             for(var i = 0; i < permList.length; i++) {
245                 if(!self.permOrgCache[self.user.id()][permList[i]])
246                     fetchList.push(permList[i]);
247             }
248
249             if(fetchList.length == 0) 
250                 return oncomplete();
251
252             fieldmapper.standardRequest(
253                 ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
254                 {   async: true,
255                     params: [this.authtoken, fetchList],
256                     oncomplete: oncomplete
257                 }
258             );
259         },
260
261     
262         /**
263          * Sets the store for an existing openils.widget.OrgUnitFilteringSelect 
264          * using the orgs where the user has the requested permission.
265          * @param perm The permission to check
266          * @param selector The pre-created dijit.form.FilteringSelect object.  
267          */
268         buildPermOrgSelector : function(perm, selector, selectedOrg, onload) {
269             var _u = this;
270     
271             dojo.require('dojo.data.ItemFileReadStore');
272
273             function hookupStore(store) {
274                 selector.store = store;
275                 selector.startup();
276                 if(selectedOrg != null)
277                     selector.setValue(selectedOrg);
278                 else
279                     selector.setValue(_u.user.ws_ou());
280                 if(onload) onload();
281             }
282
283             function buildTreePicker(orgList) {
284                 var store = new dojo.data.ItemFileReadStore({data:aou.toStoreData(orgList)});
285                 hookupStore(store);
286                 _u.permOrgStoreCache[perm] = store;
287             }
288     
289                 if (_u.permOrgStoreCache[perm])
290                         hookupStore(_u.permOrgStoreCache[perm]);
291                 else
292                 _u.getPermOrgList(perm, buildTreePicker, true);
293         },
294
295     });
296
297         openils.User.user = null;
298         openils.User.authtoken = null;
299         openils.User.authtime = null;
300     openils.User.authcookie = null;
301     openils.User.localeStrings =
302         dojo.i18n.getLocalization("openils.User", "User");
303
304     openils.User.formalName = function(u) {
305         if (!u) u = openils.User.user;
306         return dojo.string.substitute(
307             openils.User.localeStrings.FULL_NAME, [
308                 u.family_name(), u.first_given_name(),
309                 u.second_given_name() ?  u.second_given_name() : "",
310                 u.prefix() ? u.prefix() : "",
311                 u.suffix() ? u.suffix() : ""
312             ]
313         ).replace(/\s{2,}/g, " ").replace(/\s$/, "");
314     };
315 }
316
317