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();
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             // this is all related to resizing for logos..
382             //var sz = Roo.get(Pman.Login.form.el.query('img')[0]).getSize();
383            //// if (!sz) {
384              //   this.resizeToLogo.defer(1000,this);
385              //   return;
386            // }
387             //var w = Ext.lib.Dom.getViewWidth() - 100;
388             //var h = Ext.lib.Dom.getViewHeight() - 100;
389             //this.resizeTo(Math.max(350, Math.min(sz.width + 30, w)),Math.min(sz.height+200, h));
390             //this.center();
391             if (this.disabled) {
392                 this.hide();
393                 return;
394             }
395             
396             if (this.user.id < 0) { // used for inital setup situations.
397                 return;
398             }
399             
400             if (this.intervalID) {
401                 // remove the timer
402                 window.clearInterval(this.intervalID);
403                 this.intervalID = false;
404             }
405             
406             
407             if (Roo.get('loading')) {
408                 Roo.get('loading').remove();
409             }
410             if (Roo.get('loading-mask')) {
411                 Roo.get('loading-mask').hide();
412             }
413             
414             //incomming._node = tnode;
415             this.form.reset();
416             //this.dialog.modal = !modal;
417             //this.dialog.show();
418             this.dialog.el.unmask(); 
419             
420             
421             this.form.setValues({
422                 'username' : Roo.state.Manager.get(this.realm + '.username', ''),
423                 'lang' : Roo.state.Manager.get(this.realm + '.lang', 'en')
424             });
425             
426             this.switchLang(Roo.state.Manager.get(this.realm + '.lang', ''));
427             if (this.form.findField('username').getValue().length > 0 ){
428                 this.form.findField('password').focus();
429             } else {
430                this.form.findField('username').focus();
431             }
432     
433         }
434     },
435     items : [
436          {
437        
438             xtype : 'ContentPanel',
439             xns : Roo,
440             region: 'center',
441             fitToFrame : true,
442             items : [
443     
444                 {
445                
446                     xtype : 'Form',
447                     xns : Roo.form,
448                     labelWidth: 100,
449                     style : 'margin : 10px;',
450                     listeners : {
451                         actionfailed : function(f, act) {
452                             // form can return { errors: .... }
453                                 
454                             //act.result.errors // invalid form element list...
455                             //act.result.errorMsg// invalid form element list...
456                             
457                             this.dialog.el.unmask();
458                             Roo.MessageBox.alert("Error", act.result.errorMsg ? act.result.errorMsg : 
459                                         "Login failed - communication error - try again.");
460                                       
461                         },
462                         actioncomplete: function(re, act) {
463                              
464                             Roo.state.Manager.set(
465                                 this.dialog.realm + '.username',  
466                                     this.findField('username').getValue()
467                             );
468                             Roo.state.Manager.set(
469                                 this.dialog.realm + '.lang',  
470                                 this.findField('lang').getValue() 
471                             );
472                             
473                             this.dialog.fillAuth(act.result.data);
474                               
475                             this.dialog.hide();
476                             
477                             if (Roo.get('loading-mask')) {
478                                 Roo.get('loading-mask').show();
479                             }
480                             Roo.XComponent.build();
481                             
482                              
483                             
484                         }
485                     },
486                     items : [
487                         {
488                             xtype : 'TextField',
489                             xns : Roo.form,
490                             fieldLabel: "Email Address",
491                             name: 'username',
492                             width:200,
493                             autoCreate : {tag: "input", type: "text", size: "20"}
494                         },
495                         {
496                             xtype : 'TextField',
497                             xns : Roo.form,
498                             fieldLabel: "Password",
499                             inputType: 'password',
500                             name: 'password',
501                             width:200,
502                             autoCreate : {tag: "input", type: "text", size: "20"},
503                             listeners : {
504                                 specialkey : function(e,ev) {
505                                     if (ev.keyCode == 13) {
506                                         this.form.dialog.el.mask("Logging in");
507                                         this.form.doAction('submit', {
508                                             url: this.form.dialog.url,
509                                             method: this.form.dialog.method,
510                                         });
511                                     }
512                                 }
513                             }  
514                         },
515                         {
516                             xtype : 'ComboBox',
517                             xns : Roo.form,
518                             fieldLabel: "Language",
519                             name : 'langdisp',
520                             store: {
521                                 xtype : 'SimpleStore',
522                                 fields: ['lang', 'ldisp'],
523                                 data : [
524                                     [ 'en', 'English' ],
525                                     [ 'zh_HK' , '\u7E41\u4E2D' ],
526                                     [ 'zh_CN', '\u7C21\u4E2D' ]
527                                 ]
528                             },
529                             
530                             valueField : 'lang',
531                             hiddenName:  'lang',
532                             width: 200,
533                             displayField:'ldisp',
534                             typeAhead: false,
535                             editable: false,
536                             mode: 'local',
537                             triggerAction: 'all',
538                             emptyText:'Select a Language...',
539                             selectOnFocus:true,
540                             listeners : {
541                                 select :  function(cb, rec, ix) {
542                                     this.form.switchLang(rec.data.lang);
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                     
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