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