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 = 1 for periodic checking that sesion is valid.
12 *    passwordRequest = email request password
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.form = this.items[0];
238             this.form.dialog = dlg;
239             this.buttons[0].form = this.form;
240             this.buttons[0].dialog = dlg
241             this.buttons[1].form = this.form;
242             this.buttons[1].dialog = dlg
243         }
244     },
245     items : [
246         {
247        
248             xtype : 'Form',
249             xns : Roo.form,
250             labelWidth: 100,
251             
252             listeners : {
253                 actionfailed : function(f, act) {
254                     // form can return { errors: .... }
255                         
256                     //act.result.errors // invalid form element list...
257                     //act.result.errorMsg// invalid form element list...
258                     
259                     this.dialog.el.unmask();
260                     Roo.MessageBox.alert("Error", act.result.errorMsg ? act.result.errorMsg : 
261                                 "Login failed - communication error - try again.");
262                               
263                 },
264                 actioncomplete: function(re, act) {
265                      
266                     Roo.state.Manager.set(
267                         this.dialog.realm + '.' + this.dialog.params.username,  
268                             this.form.findField(this.dialog.params.username).getValue() 
269                     );
270                     Roo.state.Manager.set(
271                         this.dialog.realm + '.lang',  
272                         Pman.Login.form.findField('lang').getValue() 
273                     );
274                     
275                     this.dialog.fillAuth(act.result.data);
276                       
277                     this.dialog.hide();
278                     
279                     if (Roo.get('loading-mask')) {
280                         Roo.get('loading-mask').show();
281                     }
282                     Roo.XComponent.build();
283                     
284                      
285                     
286                 }
287             },
288             items : [
289                 {
290                     xtype : 'TextField',
291                     xns : Roo.form,
292                     fieldLabel: "Email Address",
293                     name: 'username',
294                     width:200,
295                     autoCreate : {tag: "input", type: "text", size: "20"}
296                 },
297                 {
298                     xtype : 'TextField',
299                     xns : Roo.form,
300                     fieldLabel: "Password",
301                     inputType: 'password',
302                     name: 'password',
303                     width:200,
304                     autoCreate : {tag: "input", type: "text", size: "20"},
305                     listeners : {
306                         specialkey : function(e,ev) {
307                             if (ev.keyCode == 13) {
308                                 this.form.dialog.el.mask("Logging in");
309                                 this.form.doAction('submit', {
310                                     url: this.form.dialog.url,
311                                     method: this.form.dialog.method,
312                                 });
313                             }
314                         }
315                     }  
316                 },
317                 {
318                     xtype : 'ComboBox',
319                     xns : Roo.form,
320                     fieldLabel: "Language",
321                     name : 'langdisp',
322                     store: {
323                         xtype : 'SimpleStore',
324                         fields: ['lang', 'ldisp'],
325                         data : [
326                             [ 'en', 'English' ],
327                             [ 'zh_HK' , '\u7E41\u4E2D' ],
328                             [ 'zh_CN', '\u7C21\u4E2D' ]
329                         ]
330                     },
331                     
332                     valueField : 'lang',
333                     hiddenName:  'lang',
334                     width: 200,
335                     displayField:'ldisp',
336                     typeAhead: false,
337                     editable: false,
338                     mode: 'local',
339                     triggerAction: 'all',
340                     emptyText:'Select a Language...',
341                     selectOnFocus:true,
342                     listeners : {
343                         select :  function(cb, rec, ix) {
344                             this.form.switchLang(rec.data.lang);
345                         }
346                     }
347                 
348                 }
349             ]
350         },
351           
352         
353     ],
354     buttons : [
355         {
356             xtype : 'Button',
357             xns : 'Roo',
358             label : "Forgot Password",
359             listeners : {
360                 click : function() {
361             
362                     var n = this.form.findField('username').getValue();
363                     if (!n.length) {
364                         Roo.MessageBox.alert("Error", "Fill in your email address");
365                         return;
366                     }
367                     Roo.Ajax.request({
368                         url: this.dialog.url
369                         params: {
370                             passwordRequest: n
371                         },
372                         method: this.dialog.method,
373                         success:  function(response, opts)  {  // check successfull...
374                         
375                             var res = Pman.processResponse(response);
376                             if (!res.success) { // error!
377                                Roo.MessageBox.alert("Error" ,
378                                     res.errorMsg ? res.errorMsg  : "Problem Requesting Password Reset");
379                                return;
380                             }
381                             Roo.MessageBox.alert("Notice" ,
382                                 "Please check you email for the Password Reset message");
383                         },
384                         failure : function() {
385                             Roo.MessageBox.alert("Error" , "Problem Requesting Password Reset");
386                         }
387                         
388                     });
389                 });
390             }
391         },
392         {
393             xtype : 'Button',
394             xns : 'Roo',
395             label : "Login",
396             {
397                     
398                 this.dialog.el.mask("Logging in");
399                 this.form.doAction('submit', {
400                         url: this.dialog.url
401                         method: this.dialog.method
402                 });
403         });
404          
405 }
406
407 Pman.Login =  new Roo.util.Observable({
408     
409     events : {
410         
411         'render' : true
412     },
413     disabled : false,
414     
415     dialog : false,
416     form: false,
417     haslogo : false,
418     
419     authUserId: 0,
420     authUser: { id : false },
421        
422     checkFails : 0,
423     versionWarn: false,
424     sending : false,
425     
426     
427      
428     
429     
430     intervalID : false,   /// the login refresher...
431     
432     lastChecked : false,
433     
434      
435         
436         
437         
438         this.dialog.addButton("Forgot Password", function()
439         {
440             
441             var n = _this.form.findField('username').getValue();
442             if (!n.length) {
443                 Roo.MessageBox.alert("Error", "Fill in your email address");
444                 return;
445             }
446             Roo.Ajax.request({
447                 url: baseURL + '/Login.js',  
448                 params: {
449                     passwordRequest: n
450                 },
451                 method: 'POST',  
452                 success:  function(response, opts)  {  // check successfull...
453                 
454                     var res = Pman.processResponse(response);
455                     if (!res.success) { // error!
456                        Roo.MessageBox.alert("Error" , res.errorMsg ? res.errorMsg  : "Problem Requesting Password Reset");
457                        return;
458                     }
459                     Roo.MessageBox.alert("Notice" , "Please check you email for the Password Reset message");
460                 },
461                 failure : function() {
462                     Roo.MessageBox.alert("Error" , "Problem Requesting Password Reset");
463                 }
464                 
465             });
466         });
467         
468         this.dialog.addButton("Login", function()
469         {
470             Pman.Login.dialog.el.mask("Logging in");
471             Pman.Login.form.doAction('submit', {
472                     url: baseURL + '/Login',
473                     method: 'POST'
474             });
475         });
476         this.layout = this.dialog.getLayout();
477         this.layout.beginUpdate();
478         
479         //layout.add('center', new Roo.ContentPanel('center', {title: 'The First Tab'}));
480         // generate some other tabs
481         this.form = new Roo.form.Form({
482             labelWidth: 100 ,
483             
484             listeners : {
485                 actionfailed : function(f, act) {
486                     // form can return { errors: .... }
487                         
488                     //act.result.errors // invalid form element list...
489                     //act.result.errorMsg// invalid form element list...
490                     
491                     Pman.Login.dialog.el.unmask();
492                     Roo.MessageBox.alert("Error", act.result.errorMsg ? act.result.errorMsg : 
493                                 "Login failed - communication error - try again.");
494                               
495                 },
496                 actioncomplete: function(re, act) {
497                      
498                     Roo.state.Manager.set('Pman.Login.username.'+appNameShort,  Pman.Login.form.findField('username').getValue() );
499                     Roo.state.Manager.set('Pman.Login.lang.'+appNameShort,  Pman.Login.form.findField('lang').getValue() );
500                     Pman.Login.fillAuth(act.result.data);
501                       
502                     Pman.Login.dialog.hide();
503                     if (Roo.get('loading-mask')) {
504                         //Roo.get('loading').show();
505                         Roo.get('loading-mask').show();
506                     }
507                    
508                     Pman.onload();
509                     
510                      
511                     
512                 }
513             }
514         
515             
516             
517              
518         });
519           
520         
521         
522         this.form.add( 
523        
524            
525
526         );
527          
528         
529         var ef = this.dialog.getLayout().getEl().createChild({tag: 'div'});
530         ef.dom.style.margin = 10;
531           
532         this.form.render(ef.dom);
533          // logoprefix comes from base config.
534         Pman.Login.form.el.createChild({
535                 tag: 'img', 
536                 src: rootURL + '/Pman/'+appNameShort + '/templates/images/logo.gif',
537                 style: 'margin-bottom: 10px;'
538             },
539             Pman.Login.form.el.dom.firstChild 
540         );
541        
542         var vp = this.dialog.getLayout().add('center', new Roo.ContentPanel(ef, {
543             autoCreate : true,
544             //title: 'Org Details',
545             //toolbar: this.tb,
546             width: 250,
547             maxWidth: 250,
548             fitToFrame:true
549         }));
550         
551         this.layout.endUpdate();
552         
553         this.fireEvent('render', this);
554         
555         
556         
557         
558         
559     },
560     resizeToLogo : function()
561     {
562         var sz = Roo.get(Pman.Login.form.el.query('img')[0]).getSize();
563         if (!sz) {
564             this.resizeToLogo.defer(1000,this);
565             return;
566         }
567         var w = Ext.lib.Dom.getViewWidth() - 100;
568         var h = Ext.lib.Dom.getViewHeight() - 100;
569         Pman.Login.dialog.resizeTo(Math.max(350, Math.min(sz.width + 30, w)),Math.min(sz.height+200, h));
570         Pman.Login.dialog.center();
571     },
572     
573      
574     
575     show: function (modal) 
576     {
577         if (this.disabled) {
578             return;
579         }
580         modal = modal || false;
581         if (Pman.Login.authUserId < 0) { // logout!?
582             return;
583         }
584         
585         if (Pman.Login.intervalID) {
586             // remove the timer
587             window.clearInterval(Pman.Login.intervalID);
588             Pman.Login.intervalID = false;
589         }
590         
591         this.create();
592         
593         
594         
595         if (Roo.get('loading')) {
596             Roo.get('loading').remove();
597         }
598         if (Roo.get('loading-mask')) {
599             Roo.get('loading-mask').hide();
600         }
601         
602         //incomming._node = tnode;
603         this.form.reset();
604         this.dialog.modal = !modal;
605         this.dialog.show();
606         this.dialog.el.unmask(); 
607         this.resizeToLogo.defer(1000,this);
608         
609          
610         this.form.setValues({
611             'username' : Roo.state.Manager.get('Pman.Login.username.'+appNameShort, ''),
612             'lang' : Roo.state.Manager.get('Pman.Login.lang.'+appNameShort, 'en')
613         });
614         Pman.Login.switchLang(Roo.state.Manager.get('Pman.Login.lang.'+appNameShort, ''));
615         if (this.form.findField('username').getValue().length > 0 ){
616             this.form.findField('password').focus();
617         } else {
618            this.form.findField('username').focus();
619         }
620         
621         
622     },
623  
624     
625      
626     logout: function()
627     {
628         window.onbeforeunload = function() { }; // false does not work for IE..
629         Pman.Login.authUserId = -1;
630         Roo.Ajax.request({  
631             url: baseURL + '/Login.html',  
632             params: {
633                 logout: 1
634             },  
635             method: 'GET',
636             failure : function() {
637                 Roo.MessageBox.alert("Error", "Error logging out. - continuing anyway.", function() {
638                     document.location = baseURL + '?ts=' + Math.random();
639                 });
640                 
641             },
642             success : function() {
643                 Pman.Login.authUserId = -1;
644                 Pman.Login.checkFails =0;
645                 // remove the 
646                 document.location = baseURL + '?ts=' + Math.random();
647             }
648               
649               
650         }); 
651     },
652     switchLang : function (lang) {
653         if (!lang.length) {
654             return;
655         }
656         if (typeof(_T.en) == 'undefined') {
657             _T.en = {};
658             Roo.apply(_T.en, _T);
659         }
660         
661         if (typeof(_T[lang]) == 'undefined') {
662             Roo.MessageBox.alert("Sorry", "Language not available yet (" + lang +')');
663             return;
664         }
665         
666         
667         Roo.apply(_T, _T[lang]);
668         // just need to set the text values for everything...
669         if (this.form) {
670             
671                
672             function formLabel(name, val) {
673                 
674                 var lbl = Pman.Login.form.findField( name ).el.dom.parentNode.parentNode;
675                 if (lbl.getElementsByTagName('label').length) {
676                     lbl = lbl.getElementsByTagName('label')[0];
677                 } else  {
678                     lbl = lbl.parentNode.getElementsByTagName('label')[0];
679                 }
680                    
681                 lbl.innerHTML = val;
682             }
683             
684             formLabel('password', "Password"+':');
685             formLabel('username', "Email Address"+':');
686             formLabel('lang', "Language"+':');
687             this.dialog.setTitle("Login");
688             this.dialog.buttons[0].setText("Forgot Password");
689             this.dialog.buttons[1].setText("Login");
690         }
691         
692         
693     },
694     
695     inGroup : function(g)
696     {
697         return this.authUser && this.authUser.groups && 
698             this.authUser.groups.indexOf(g) > -1;
699     },
700     isOwner : function()
701     {
702         return this.authUser && this.authUser.company_id_comptype && 
703             this.authUser.company_id_comptype == 'OWNER';
704     },
705     
706     /**
707      * Depreciated = use Pman.I18n
708      */
709     
710     i18nList: function (type, codes)
711     {
712         
713         return Pman.I18n.listToNames(type, codes);
714     },
715     i18n: function(type, code) 
716     {
717         return Pman.I18n.toName(type, code);
718         
719     }
720     
721     
722 });
723
724
725
726
727