Org unit prox adjustment tweaks
[working/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         login_agent : null,
37         location : null,
38         authtoken : null,
39         authtime : null,
40         workstation : null,
41         permOrgCache : {},
42         sessionCache : {},
43     
44         constructor : function ( kwargs ) {
45             kwargs = kwargs || {};
46             this.id = kwargs.id;
47             this.user = kwargs.user;
48             this.passwd = kwargs.passwd;
49             this.authtoken = kwargs.authtoken || openils.User.authtoken;
50             this.authtime = kwargs.authtime || openils.User.authtime;
51             this.login_type = kwargs.login_type;
52             this.login_agent = kwargs.login_agent || openils.User.default_login_agent || 'staffclient';
53             this.location = kwargs.location;
54             this.authcookie = kwargs.authcookie || openils.User.authcookie;
55             this.permOrgStoreCache = {}; /* permName => permOrgUnitStore map */
56
57             if (this.authcookie) this.authtoken = dojo.cookie(this.authcookie);
58             if (this.id && this.authtoken) this.user = this.getById( this.id );
59             else if (this.authtoken) this.getBySession();
60             else if (kwargs.login) this.login();
61
62             var id = this.id || (this.user && this.user.id) ? this.user.id() : null;
63             if(id && !this.permOrgCache[id])
64                 this.permOrgCache[id] = {};
65         },
66
67         getBySession : function(onComplete) {
68             var _u = this;
69             var req = ['open-ils.auth', 'open-ils.auth.session.retrieve'];
70             var params = [_u.authtoken];
71
72             if(this.sessionCache[this.authtoken]) {
73                 this.user = this.sessionCache[this.authtoken];
74                                 if (!openils.User.user) 
75                     openils.User.user = this.user;
76                 return this.user;
77             }
78
79             if(onComplete) {
80                 fieldmapper.standardRequest(
81                     req, {   
82                         async: true,
83                         params: params,
84                         oncomplete : function(r) {
85                             var user = r.recv().content();
86                             _u.user = user;
87                             _u.sessionCache[_u.authtoken] = user;
88                                                 if (!openils.User.user) openils.User.user = _u.user;
89                             if(onComplete)
90                                 onComplete(user);
91                         }
92                     }
93                 );
94             } else {
95                 _u.user = fieldmapper.standardRequest(req, params);
96                                 if (!openils.User.user) openils.User.user = _u.user;
97                 _u.sessionCache[_u.authtoken] = _u.user;
98                 return _u.user;
99             }
100         },
101     
102         getById : function(id, onComplete) {
103             var req = OpenSRF.CachedClientSession('open-ils.actor').request('open-ils.actor.user.retrieve', this.authtoken, id);
104             if(onComplete) {
105                 req.oncomplete = function(r) {
106                     var user = r.recv().content();
107                     onComplete(user);
108                 }
109                 req.send();
110             } else {
111                 req.timeout = 10;
112                 req.send();
113                 return req.recv().content();
114             }
115         },
116
117         /**
118          * Tests the given username and password.  This version is async only.
119          */
120         auth_verify : function(args, onComplete) {
121             var _u = this;
122             if (!args) args = {};
123             if (!args.username) args.username = _u.username;
124             if (!args.passwd) args.passwd = _u.passwd;
125             if (!args.agent) args.agent = _u.login_agent;
126             if (!args.type) args.type = _u.type;
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                     type : args.type,
134                     username : args.username,
135                     barcode : args.barcode,
136                     password : hex_md5(seed + hex_md5(args.passwd)), 
137                     agent : args.agent,
138                 };
139     
140                 var authReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.verify', loginInfo);
141                 authReq.oncomplete = function(rr) {
142                     var data = rr.recv().content();
143                     var evt = openils.Event.parse(data);
144                     if (evt && evt.code == 0) onComplete(true);
145                     else onComplete(false);
146                 }
147                 authReq.send();
148             }
149     
150             initReq.send();
151         },
152     
153     
154         /**
155          * Logs in, sets the authtoken/authtime vars, and fetches the logged in user
156          */
157         login_async : function(args, onComplete) {
158             var _u = this;
159
160             if (!args) args = {};
161             if (!args.username) args.username = _u.username;
162             if (!args.passwd) args.passwd = _u.passwd;
163             if (!args.type) args.type = _u.login_type;
164             if (!args.agent) args.agent = _u.login_agent;
165             if (!args.location) args.location = _u.location;
166
167             var initReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.init', args.username);
168     
169             initReq.oncomplete = function(r) {
170                 var seed = r.recv().content(); 
171                 var loginInfo = {
172                     username : args.username,
173                     password : hex_md5(seed + hex_md5(args.passwd)), 
174                     type : args.type,
175                     agent : args.agent,
176                     org : args.location,
177                     workstation : args.workstation
178                 };
179     
180                 var authReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.complete', loginInfo);
181                 authReq.oncomplete = function(rr) {
182                     var data = rr.recv().content();
183
184                     if(!data || !data.payload)
185                         throw new Error("Login Failed: " + js2JSON(data));
186
187                     _u.authtoken = data.payload.authtoken;
188                                         if (!openils.User.authtoken) openils.User.authtoken = _u.authtoken;
189                     _u.authtime = data.payload.authtime;
190                                         if (!openils.User.authtime) openils.User.authtime = _u.authtime;
191                     _u.getBySession(onComplete);
192                     if(_u.authcookie) {
193                         dojo.cookie(_u.authcookie, _u.authtoken, {path:'/'});
194                     }
195                 }
196                 authReq.send();
197             }
198     
199             initReq.send();
200         },
201
202         login : function(args) {
203             var _u = this;
204             if (!args) args = {};
205             if (!args.username) args.username = _u.username;
206             if (!args.passwd) args.passwd = _u.passwd;
207             if (!args.type) args.type = _u.login_type;
208             if (!args.agent) args.agent = _u.login_agent;
209             if (!args.location) args.location = _u.location;
210
211             var seed = fieldmapper.standardRequest(
212                 ['open-ils.auth', 'open-ils.auth.authenticate.init'],
213                 [args.username]
214             );
215
216             var loginInfo = {
217                 username : args.username,
218                 password : hex_md5(seed + hex_md5(args.passwd)), 
219                 type : args.type,
220                 agent : args.agent,
221                 org : args.location,
222                 workstation : args.workstation,
223             };
224
225             var data = fieldmapper.standardRequest(
226                 ['open-ils.auth', 'open-ils.auth.authenticate.complete'],
227                 [loginInfo]
228             );
229
230             if(!data || !data.payload) return false;
231
232             _u.authtoken = data.payload.authtoken;
233             if (!openils.User.authtoken) openils.User.authtoken = _u.authtoken;
234             _u.authtime = data.payload.authtime;
235             if (!openils.User.authtime) openils.User.authtime = _u.authtime;
236
237             if(_u.authcookie) {
238                 dojo.cookie(_u.authcookie, _u.authtoken, {path:'/'});
239             }
240
241             return true;
242         },
243
244     
245         /**
246          * Returns a list of the "highest" org units where the user has the given permission(s).
247          * @param permList A single permission or list of permissions
248          * @param includeDescendents If true, return a list of 'highest' orgs plus descendents
249          * @idlist If true, return a list of IDs instead of org unit objects
250          */
251         getPermOrgList : function(permList, onload, includeDescendents, idlist) {
252             if(typeof permList == 'string') permList = [permList];
253
254             var self = this;
255             var oncomplete = function(r) {
256                 var permMap = {};
257                 if(r) permMap = openils.Util.readResponse(r);
258                 var orgList = [];
259
260                 for(var i = 0; i < permList.length; i++) {
261                     var perm = permList[i];
262                     var permOrgList = permMap[perm] || self.permOrgCache[self.user.id()][perm];
263                     self.permOrgCache[self.user.id()][perm] = permOrgList;
264
265                     for(var j in permOrgList) {
266                         if(includeDescendents) {
267                             orgList = orgList.concat(
268                                 fieldmapper.aou.descendantNodeList(permOrgList[j]));
269                         } else {
270                             orgList = orgList.concat(fieldmapper.aou.findOrgUnit(permOrgList[j]));
271                         }
272                     }
273                 }
274
275                 // remove duplicates
276                 var trimmed = [];
277                 for(var idx in orgList) {
278                     var val = (idlist) ? orgList[idx].id() : orgList[idx];
279                     if(trimmed.indexOf(val) < 0)
280                         trimmed.push(val);
281                 }
282                 onload(trimmed);
283             };
284
285             var fetchList = [];
286             for(var i = 0; i < permList.length; i++) {
287                 if(!self.permOrgCache[self.user.id()][permList[i]])
288                     fetchList.push(permList[i]);
289             }
290
291             if(fetchList.length == 0) 
292                 return oncomplete();
293
294             fieldmapper.standardRequest(
295                 ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
296                 {   async: true,
297                     params: [this.authtoken, fetchList],
298                     oncomplete: oncomplete
299                 }
300             );
301         },
302
303     
304         /**
305          * Sets the store for an existing openils.widget.OrgUnitFilteringSelect 
306          * using the orgs where the user has the requested permission.
307          * @param perm The permission to check
308          * @param selector The pre-created dijit.form.FilteringSelect object.  
309          * @param selectedOrg org to select in FilteringSelect object. null defaults to user ws_ou, -1 will select the first OU where the perm is held, typically the top of a [sub]tree.
310          */
311         buildPermOrgSelector : function(perm, selector, selectedOrg, onload) {
312             var _u = this;
313     
314             dojo.require('dojo.data.ItemFileReadStore');
315
316             function hookupStore(store, useOrg) {
317                 selector.store = store;
318                 selector.startup();
319                 if(useOrg != null)
320                     selector.setValue(useOrg);
321                 else
322                     selector.setValue(_u.user.ws_ou());
323                 if(onload) onload();
324             }
325
326             function buildTreePicker(orgList) {
327                 var store = new dojo.data.ItemFileReadStore({data:aou.toStoreData(orgList)});
328                 if (selectedOrg == -1 && orgList[0])
329                     selectedOrg = orgList[0].id();
330
331                 hookupStore(store, selectedOrg);
332                 _u.permOrgStoreCache[perm] = store;
333             }
334     
335                 if (_u.permOrgStoreCache[perm])
336                         hookupStore(_u.permOrgStoreCache[perm]);
337                 else
338                 _u.getPermOrgList(perm, buildTreePicker, true);
339         },
340
341     });
342
343         openils.User.user = null;
344         openils.User.authtoken = null;
345         openils.User.authtime = null;
346     openils.User.authcookie = null;
347     openils.User.default_login_agent = null; // global agent override
348     openils.User.localeStrings =
349         dojo.i18n.getLocalization("openils.User", "User");
350
351     openils.User.formalName = function(u) {
352         if (!u) u = openils.User.user;
353         return dojo.string.substitute(
354             openils.User.localeStrings.FULL_NAME, [
355                 u.family_name(), u.first_given_name(),
356                 u.second_given_name() ?  u.second_given_name() : "",
357                 u.prefix() ? u.prefix() : "",
358                 u.suffix() ? u.suffix() : ""
359             ]
360         ).replace(/\s{2,}/g, " ").replace(/\s$/, "");
361     };
362 }
363
364