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