]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/dojo/openils/User.js
LP2045292 Color contrast for AngularJS patron bills
[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             if (args.username) {
129                 var initReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.init', args.username);
130             } else {
131                 var initReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.init', args.barcode);
132             }
133     
134             initReq.oncomplete = function(r) {
135                 var seed = r.recv().content(); 
136                 var loginInfo = {
137                     type : args.type,
138                     username : args.username,
139                     barcode : args.barcode,
140                     password : hex_md5(seed + hex_md5(args.passwd)), 
141                     agent : args.agent,
142                 };
143     
144                 var authReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.verify', loginInfo);
145                 authReq.oncomplete = function(rr) {
146                     var data = rr.recv().content();
147                     var evt = openils.Event.parse(data);
148                     if (evt && evt.code == 0) onComplete(true);
149                     else onComplete(false);
150                 }
151                 authReq.send();
152             }
153     
154             initReq.send();
155         },
156     
157     
158         /**
159          * Logs in, sets the authtoken/authtime vars, and fetches the logged in user
160          */
161         login_async : function(args, onComplete) {
162             var _u = this;
163
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.agent) args.agent = _u.login_agent;
169             if (!args.location) args.location = _u.location;
170
171             var initReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.init', args.username);
172     
173             initReq.oncomplete = function(r) {
174                 var seed = r.recv().content(); 
175                 var loginInfo = {
176                     username : args.username,
177                     password : hex_md5(seed + hex_md5(args.passwd)), 
178                     type : args.type,
179                     agent : args.agent,
180                     org : args.location,
181                     workstation : args.workstation
182                 };
183     
184                 var authReq = OpenSRF.CachedClientSession('open-ils.auth').request('open-ils.auth.authenticate.complete', loginInfo);
185                 authReq.oncomplete = function(rr) {
186                     var data = rr.recv().content();
187
188                     if(!data || !data.payload)
189                         throw new Error("Login Failed: " + js2JSON(data));
190
191                     _u.authtoken = data.payload.authtoken;
192                                         if (!openils.User.authtoken) openils.User.authtoken = _u.authtoken;
193                     _u.authtime = data.payload.authtime;
194                                         if (!openils.User.authtime) openils.User.authtime = _u.authtime;
195                     _u.getBySession(onComplete);
196                     if(_u.authcookie) {
197                         dojo.cookie(_u.authcookie, _u.authtoken, {path:'/'});
198                     }
199                 }
200                 authReq.send();
201             }
202     
203             initReq.send();
204         },
205
206         login : function(args) {
207             var _u = this;
208             if (!args) args = {};
209             if (!args.username) args.username = _u.username;
210             if (!args.passwd) args.passwd = _u.passwd;
211             if (!args.type) args.type = _u.login_type;
212             if (!args.agent) args.agent = _u.login_agent;
213             if (!args.location) args.location = _u.location;
214
215             var seed = fieldmapper.standardRequest(
216                 ['open-ils.auth', 'open-ils.auth.authenticate.init'],
217                 [args.username]
218             );
219
220             var loginInfo = {
221                 username : args.username,
222                 password : hex_md5(seed + hex_md5(args.passwd)), 
223                 type : args.type,
224                 agent : args.agent,
225                 org : args.location,
226                 workstation : args.workstation,
227             };
228
229             var data = fieldmapper.standardRequest(
230                 ['open-ils.auth', 'open-ils.auth.authenticate.complete'],
231                 [loginInfo]
232             );
233
234             if(!data || !data.payload) return false;
235
236             _u.authtoken = data.payload.authtoken;
237             if (!openils.User.authtoken) openils.User.authtoken = _u.authtoken;
238             _u.authtime = data.payload.authtime;
239             if (!openils.User.authtime) openils.User.authtime = _u.authtime;
240
241             if(_u.authcookie) {
242                 dojo.cookie(_u.authcookie, _u.authtoken, {path:'/'});
243             }
244
245             return true;
246         },
247
248     
249         /**
250          * Returns a list of the "highest" org units where the user has the given permission(s).
251          * @param permList A single permission or list of permissions
252          * @param includeDescendents If true, return a list of 'highest' orgs plus descendents
253          * @idlist If true, return a list of IDs instead of org unit objects
254          */
255         getPermOrgList : function(permList, onload, includeDescendents, idlist) {
256             if(typeof permList == 'string') permList = [permList];
257
258             var self = this;
259             var oncomplete = function(r) {
260                 var permMap = {};
261                 if(r) permMap = openils.Util.readResponse(r);
262                 var orgList = [];
263
264                 for(var i = 0; i < permList.length; i++) {
265                     var perm = permList[i];
266                     var permOrgList = permMap[perm] || self.permOrgCache[self.user.id()][perm];
267                     self.permOrgCache[self.user.id()][perm] = permOrgList;
268
269                     for(var j in permOrgList) {
270                         if(includeDescendents) {
271                             orgList = orgList.concat(
272                                 fieldmapper.aou.descendantNodeList(permOrgList[j]));
273                         } else {
274                             orgList = orgList.concat(fieldmapper.aou.findOrgUnit(permOrgList[j]));
275                         }
276                     }
277                 }
278
279                 // remove duplicates
280                 var trimmed = [];
281                 for(var idx in orgList) {
282                     var val = (idlist) ? orgList[idx].id() : orgList[idx];
283                     if(trimmed.indexOf(val) < 0)
284                         trimmed.push(val);
285                 }
286                 onload(trimmed);
287             };
288
289             var fetchList = [];
290             for(var i = 0; i < permList.length; i++) {
291                 if(!self.permOrgCache[self.user.id()][permList[i]])
292                     fetchList.push(permList[i]);
293             }
294
295             if(fetchList.length == 0) 
296                 return oncomplete();
297
298             fieldmapper.standardRequest(
299                 ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
300                 {   async: true,
301                     params: [this.authtoken, fetchList],
302                     oncomplete: oncomplete
303                 }
304             );
305         },
306
307     
308         /**
309          * Sets the store for an existing openils.widget.OrgUnitFilteringSelect 
310          * using the orgs where the user has the requested permission.
311          * @param perm The permission to check
312          * @param selector The pre-created dijit.form.FilteringSelect object.  
313          * @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.
314          */
315         buildPermOrgSelector : function(perm, selector, selectedOrg, onload) {
316             var _u = this;
317     
318             dojo.require('dojo.data.ItemFileReadStore');
319
320             function hookupStore(store, useOrg) {
321                 selector.store = store;
322                 selector.startup();
323                 if(useOrg != null)
324                     selector.setValue(useOrg);
325                 else
326                     selector.setValue(_u.user.ws_ou());
327                 if(onload) onload();
328             }
329
330             function buildTreePicker(orgList) {
331                 var store = new dojo.data.ItemFileReadStore({data:aou.toStoreData(orgList)});
332                 if (selectedOrg == -1 && orgList[0])
333                     selectedOrg = orgList[0].id();
334
335                 hookupStore(store, selectedOrg);
336                 _u.permOrgStoreCache[perm] = store;
337             }
338     
339                 if (_u.permOrgStoreCache[perm])
340                         hookupStore(_u.permOrgStoreCache[perm]);
341                 else
342                 _u.getPermOrgList(perm, buildTreePicker, true);
343         },
344
345     });
346
347         openils.User.user = null;
348         openils.User.authtoken = null;
349         openils.User.authtime = null;
350     openils.User.authcookie = null;
351     openils.User.default_login_agent = null; // global agent override
352     openils.User.localeStrings =
353         dojo.i18n.getLocalization("openils.User", "User");
354
355     openils.User.formalName = function(u) {
356         if (!u) u = openils.User.user;
357         return dojo.string.substitute(
358             openils.User.localeStrings.FULL_NAME, [
359                 u.family_name(), u.first_given_name(),
360                 u.second_given_name() ?  u.second_given_name() : "",
361                 u.prefix() ? u.prefix() : "",
362                 u.suffix() ? u.suffix() : ""
363             ]
364         ).replace(/\s{2,}/g, " ").replace(/\s$/, "");
365     };
366 }
367
368