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