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