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