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