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