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