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