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