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