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