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