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