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