Pman.Login.js
[Pman.Core] / Pman.Login.js
1 //<script type="text/javascript">
2
3 /**
4  * login code -
5  * fires Pman 'authrefreshed'  event on every poll to server..
6  *
7  */
8
9 /***
10 re-arrange language code...
11 * flipping language should be like this:
12
13 * Ext.apply(_T, _T[lang]);
14
15 **/
16  
17   
18
19 Pman.Login =  new Roo.util.Observable({
20     
21     events : {
22         
23         'render' : true
24        
25     },
26     disabled : false,
27     
28     dialog : false,
29     form: false,
30     haslogo : false,
31     
32     authUserId: 0,
33     authUser: { id : false },
34        
35     checkFails : 0,
36     versionWarn: false,
37     sending : false,
38     
39     onLoad : function() // called on page load...
40     {
41         // load 
42        
43          
44         if (Roo.get('loading')) {
45             Roo.get('loading').remove();
46         }
47         this.switchLang('en');
48        
49         // check if we are logged in..
50         Roo.Ajax.request({  
51             url: baseURL + '/Login.js',  
52             params: {
53                 getAuthUser: true
54             },  
55             method: 'GET',  
56             success:  function(response, opts)  {  // check successfull...
57             
58                 var res = Pman.processResponse(response);
59                 this.checkFails =0;
60                 if (!res.success) { // error!
61                     this.checkFails = 5;
62                     //console.log('call failure');
63                     return Pman.Login.failure(response,opts);
64                 }
65                 
66                 
67                 if (!res.data.id) { // id=0 == login failure.
68                     return this.show(true);
69                 }
70                 
71                               
72                         //console.log(success);
73                 this.fillAuth(res.data);   
74                 this.checkFails =0;
75                 Pman.onload();
76                 return false;
77             },
78             failure : Pman.Login.show,
79             scope : Pman.Login
80               
81         });  
82     }, 
83     
84     
85     check: function(again) // called every so often to refresh cookie etc..
86     {
87         if (again) { // could be undefined..
88             Pman.Login.checkFails++;
89         } else {
90             Pman.Login.checkFails = 0;
91         }
92         var _this = this;
93         if (this.sending) {
94             
95             if ( Pman.Login.checkFails > 4) {
96                 Pman.Preview.disable();
97                 Roo.MessageBox.alert("Error",  
98                     "Error getting authentication status. - try reloading, or wait a while", function() {
99                         _this.sending = false;
100                     }); 
101                 return;
102             }
103             
104             _this.check.defer(10000, _this, [ true ]); // check in 10 secs.
105             return;
106         }
107         this.sending = true;
108         
109         Roo.Ajax.request({  
110             url: baseURL + '/Login.js',  
111             params: {
112                 getAuthUser: true
113             },  
114             method: 'GET',  
115             success:  Pman.Login.success,
116             failure : Pman.Login.failure,
117             scope : Pman.Login
118               
119         });  
120     }, 
121     
122     
123     
124     failure : function (response, opts) // called if login 'check' fails.. (causes re-check)
125     {
126         this.authUser = -1;
127         this.sending = false;
128         var res = Pman.processResponse(response);
129         //console.log(res);
130         if ( Pman.Login.checkFails > 2) {
131             Pman.Preview.disable();
132             Roo.MessageBox.alert("Error", res.errorMsg ? res.errorMsg : 
133                 "Error getting authentication status. - try reloading"); 
134             return;
135         }
136             
137         Pman.Login.check.defer(1000, Pman.Login, [ true ]);
138         return;  
139     },
140     
141     
142     success : function(response, opts)  // check successfull...
143     {  
144         this.sending = false;
145         var res = Pman.processResponse(response);
146         if (!res.success) {
147             return this.failure(response, opts);
148         }
149         if (!res.data || !res.data.id) {
150             return this.failure(response,opts);
151         }
152         //console.log(res);
153         this.fillAuth(res.data);
154         
155         this.checkFails =0;
156         Pman.onload();
157         return false;
158     },
159     
160     fillAuth: function(au) {
161         this.startAuthCheck();
162         this.authUserId = au.id;
163         this.authUser = au;
164         this.lastChecked = new Date();
165         // if login is used on other applicaitons..
166         if (Pman.fireEvent) { Pman.fireEvent('authrefreshed', au); }
167         
168         
169         //Pman.Tab.FaxQueue.newMaxId(au.faxMax);
170         //Pman.Tab.FaxTab.setTitle(au.faxNumPending);
171         
172         //this.switchLang(Roo.state.Manager.get('Pman.Login.lang', 'en'));
173         Roo.state.Manager.set('Pman.Login.lang.'+appNameShort, au.lang);
174         this.switchLang(au.lang);
175         
176      
177         // open system... - -on setyp..
178         if (this.authUserId  < 0) {
179             Roo.MessageBox.alert("Warning", 
180                 "This is an open system - please set up a admin user with a password.");  
181         }
182          
183         //Pman.onload(); // which should do nothing if it's a re-auth result...
184         
185              
186     },
187     
188     
189     intervalID : false,   /// the login refresher...
190     
191     lastChecked : false,
192     
193     startAuthCheck : function() // starter for timeout checking..
194     {
195         if (Pman.Login.intervalID) { // timer already in place...
196             return false;
197         }
198         
199         Pman.Login.intervalID =  window.setInterval(function() {
200                   Pman.Login.check(false);
201                 }, 120000); // every 120 secs = 2mins..
202         return true;
203         
204     },
205     
206     
207     create : function()
208     {
209         if (this.dialog) {
210             return;
211         }
212         var _this = this;
213         
214         this.dialog = new Roo.LayoutDialog(Roo.get(document.body).createChild({tag:'div'}),
215         { // the real end set is here...
216             autoCreated: true,
217             title: "Login",
218             modal: true,
219             width:  350,
220             height: 230,
221             shadow:true,
222             minWidth:200,
223             minHeight:180,
224             //proxyDrag: true,
225             closable: false,
226             draggable: false,
227             collapsible: false,
228             resizable: false,
229             center: {
230                 autoScroll:false,
231                 titlebar: false,
232                // tabPosition: 'top',
233                 hideTabs: true,
234                 closeOnTab: true,
235                 alwaysShowTabs: false
236             }  
237             
238         });
239         
240         
241         
242         this.dialog.addButton("Forgot Password", function()
243         {
244             
245             var n = _this.form.findField('username').getValue();
246             if (!n.length) {
247                 Roo.MessageBox.alert("Error", "Fill in your email address");
248                 return;
249             }
250             Roo.Ajax.request({
251                 url: baseURL + '/Login.js',  
252                 params: {
253                     passwordRequest: n
254                 },
255                 method: 'POST',  
256                 success:  function(response, opts)  {  // check successfull...
257                 
258                     var res = Pman.processResponse(response);
259                     if (!res.success) { // error!
260                        Roo.MessageBox.alert("Error" , res.errorMsg ? res.errorMsg  : "Problem Requesting Password Reset");
261                        return;
262                     }
263                     Roo.MessageBox.alert("Notice" , "Please check you email for the Password Reset message");
264                 },
265                 failure : function() {
266                     Roo.MessageBox.alert("Error" , "Problem Requesting Password Reset");
267                 }
268                 
269             });
270         });
271         
272         this.dialog.addButton("Login", function()
273         {
274             Pman.Login.dialog.el.mask("Logging in");
275             Pman.Login.form.doAction('submit', {
276                     url: baseURL + '/Login',
277                     method: 'POST'
278             });
279         });
280         this.layout = this.dialog.getLayout();
281         this.layout.beginUpdate();
282         
283         //layout.add('center', new Roo.ContentPanel('center', {title: 'The First Tab'}));
284         // generate some other tabs
285         this.form = new Roo.form.Form({
286             labelWidth: 100 ,
287             
288             listeners : {
289                 actionfailed : function(f, act) {
290                     // form can return { errors: .... }
291                         
292                     //act.result.errors // invalid form element list...
293                     //act.result.errorMsg// invalid form element list...
294                     
295                     Pman.Login.dialog.el.unmask();
296                     Roo.MessageBox.alert("Error", act.result.errorMsg ? act.result.errorMsg : 
297                                 "Login failed - communication error - try again.");
298                               
299                 },
300                 actioncomplete: function(re, act) {
301                      
302                     Roo.state.Manager.set('Pman.Login.username.'+appNameShort,  Pman.Login.form.findField('username').getValue() );
303                     Roo.state.Manager.set('Pman.Login.lang.'+appNameShort,  Pman.Login.form.findField('lang').getValue() );
304                     Pman.Login.fillAuth(act.result.data);
305                       
306                     Pman.Login.dialog.hide();
307                     if (Roo.get('loading-mask')) {
308                         //Roo.get('loading').show();
309                         Roo.get('loading-mask').show();
310                     }
311                    
312                     Pman.onload();
313                     
314                      
315                     
316                 }
317             }
318         
319             
320             
321              
322         });
323           
324         
325         
326         this.form.add( 
327        
328             new Roo.form.TextField({
329                 fieldLabel: "Email Address",
330                 name: 'username',
331                 width:200,
332                 autoCreate : {tag: "input", type: "text", size: "20"}
333             }),
334
335             new Roo.form.TextField({
336                 fieldLabel: "Password",
337                 inputType: 'password',
338                 name: 'password',
339                 width:200,
340                 autoCreate : {tag: "input", type: "text", size: "20"},
341                 listeners : {
342                     specialkey : function(e,ev) {
343                         if (ev.keyCode == 13) {
344                             Pman.Login.dialog.el.mask("Logging in");
345                             Pman.Login.form.doAction('submit', {
346                                     url: baseURL + '/Login',
347                                     method: 'POST'
348                             });
349                         }
350                     }
351                 }  
352             }) ,
353             new Roo.form.ComboBox({
354                 fieldLabel: "Language",
355                 name : 'langdisp',
356                 store: {
357                     xtype : 'SimpleStore',
358                     fields: ['lang', 'ldisp'],
359                     data : [
360                         [ 'en', 'English' ],
361                         [ 'zh_HK' , '\u7E41\u4E2D' ],
362                         [ 'zh_CN', '\u7C21\u4E2D' ]
363                     ]
364                 },
365                 
366                 valueField : 'lang',
367                 hiddenName:  'lang',
368                 width: 200,
369                 displayField:'ldisp',
370                 typeAhead: false,
371                 editable: false,
372                 mode: 'local',
373                 triggerAction: 'all',
374                 emptyText:'Select a Language...',
375                 selectOnFocus:true,
376                 listeners : {
377                     select :  function(cb, rec, ix) {
378                         
379                         
380                         Pman.Login.switchLang(rec.data.lang);
381                         
382                     }
383                 }
384             
385             })
386
387         );
388          
389         
390         var ef = this.dialog.getLayout().getEl().createChild({tag: 'div'});
391         ef.dom.style.margin = 10;
392           
393         this.form.render(ef.dom);
394          // logoprefix comes from base config.
395         Pman.Login.form.el.createChild({
396                 tag: 'img', 
397                 src: rootURL + '/Pman/'+appNameShort + '/templates/images/logo.gif',
398                 style: 'margin-bottom: 10px;'
399             },
400             Pman.Login.form.el.dom.firstChild 
401         );
402        
403         var vp = this.dialog.getLayout().add('center', new Roo.ContentPanel(ef, {
404             autoCreate : true,
405             //title: 'Org Details',
406             //toolbar: this.tb,
407             width: 250,
408             maxWidth: 250,
409             fitToFrame:true
410         }));
411         
412         this.layout.endUpdate();
413         
414         this.fireEvent('render', this);
415         
416         
417         
418         
419         
420     },
421     resizeToLogo : function()
422     {
423         var sz = Roo.get(Pman.Login.form.el.query('img')[0]).getSize();
424         if (!sz) {
425             this.resizeToLogo.defer(1000,this);
426             return;
427         }
428         var w = Roo.lib.Dom.getViewWidth() - 100;
429         var h = Roo.lib.Dom.getViewHeight() - 100;
430         Pman.Login.dialog.resizeTo(Math.max(350, Math.min(sz.width + 30, w)),Math.min(sz.height+200, h));
431         Pman.Login.dialog.center();
432     },
433     
434      
435     
436     show: function (modal, cb) 
437     {
438         if (this.disabled) {
439             return;
440         }
441         this.callback = cb; // used for non-pman usage..
442         modal = modal || false;
443         if (Pman.Login.authUserId < 0) { // logout!?
444             return;
445         }
446         
447         if (Pman.Login.intervalID) {
448             // remove the timer
449             window.clearInterval(Pman.Login.intervalID);
450             Pman.Login.intervalID = false;
451         }
452         
453         this.create();
454         
455         
456         
457         if (Roo.get('loading')) {
458             Roo.get('loading').remove();
459         }
460         if (Roo.get('loading-mask')) {
461             Roo.get('loading-mask').hide();
462         }
463         
464         //incomming._node = tnode;
465         // why we want this non-modal????
466         this.form.reset();
467         this.dialog.modal = !modal;
468         this.dialog.show();
469         this.dialog.el.unmask(); 
470         this.resizeToLogo.defer(1000,this);
471         
472          
473         this.form.setValues({
474             'username' : Roo.state.Manager.get('Pman.Login.username.'+appNameShort, ''),
475             'lang' : Roo.state.Manager.get('Pman.Login.lang.'+appNameShort, 'en')
476         });
477         Pman.Login.switchLang(Roo.state.Manager.get('Pman.Login.lang.'+appNameShort, ''));
478         if (this.form.findField('username').getValue().length > 0 ){
479             this.form.findField('password').focus();
480         } else {
481            this.form.findField('username').focus();
482         }
483         
484         
485     },
486  
487     
488      
489     logout: function()
490     {
491         window.onbeforeunload = function() { }; // false does not work for IE..
492         Pman.Login.authUserId = -1;
493         Roo.Ajax.request({  
494             url: baseURL + '/Login.html',  
495             params: {
496                 logout: 1
497             },  
498             method: 'GET',
499             failure : function() {
500                 Roo.MessageBox.alert("Error", "Error logging out. - continuing anyway.", function() {
501                     document.location = baseURL + '?ts=' + Math.random();
502                 });
503                 
504             },
505             success : function() {
506                 Pman.Login.authUserId = -1;
507                 Pman.Login.checkFails =0;
508                 // remove the 
509                 document.location = baseURL + '?ts=' + Math.random();
510             }
511               
512               
513         }); 
514     },
515     switchLang : function (lang) {
516         if (!lang || !lang.length) {
517             return;
518         }
519         if (typeof(_T.en) == 'undefined') {
520             _T.en = {};
521             Roo.apply(_T.en, _T);
522         }
523         
524         if (typeof(_T[lang]) == 'undefined') {
525             Roo.MessageBox.alert("Sorry", "Language not available yet (" + lang +')');
526             return;
527         }
528         
529         
530         Roo.apply(_T, _T[lang]);
531         // just need to set the text values for everything...
532         if (this.form) {
533             
534                
535             function formLabel(name, val) {
536                 
537                 var lbl = Pman.Login.form.findField( name ).el.dom.parentNode.parentNode;
538                 if (lbl.getElementsByTagName('label').length) {
539                     lbl = lbl.getElementsByTagName('label')[0];
540                 } else  {
541                     lbl = lbl.parentNode.getElementsByTagName('label')[0];
542                 }
543                    
544                 lbl.innerHTML = val;
545             }
546             
547             formLabel('password', "Password"+':');
548             formLabel('username', "Email Address"+':');
549             formLabel('lang', "Language"+':');
550             this.dialog.setTitle("Login");
551             this.dialog.buttons[0].setText("Forgot Password");
552             this.dialog.buttons[1].setText("Login");
553         }
554         
555         
556     },
557     
558     inGroup : function(g)
559     {
560         return this.authUser && this.authUser.groups && 
561             this.authUser.groups.indexOf(g) > -1;
562     },
563     isOwner : function()
564     {
565         return this.authUser && this.authUser.company_id_comptype && 
566             this.authUser.company_id_comptype == 'OWNER';
567     },
568     
569     /**
570      * Depreciated = use Pman.I18n
571      */
572     
573     i18nList: function (type, codes)
574     {
575         
576         return Pman.I18n.listToNames(type, codes);
577     },
578     i18n: function(type, code) 
579     {
580         return Pman.I18n.toName(type, code);
581         
582     }
583     
584     
585 });
586
587
588
589
590