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