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