allow string based values for comboboxarray
[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  **/
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         au.lang = au.lang || 'en';
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         _T = typeof(_T) == 'undefined' ? false : _T;
297           if (!_T || !lang.length) {
298             return;
299         }
300         
301         if (!_T && lang != 'en') {
302             Roo.MessageBox.alert("Sorry", "Language not available yet (" + lang +')');
303             return;
304         }
305         
306         if (typeof(_T.en) == 'undefined') {
307             _T.en = {};
308             Roo.apply(_T.en, _T);
309         }
310         
311         if (typeof(_T[lang]) == 'undefined') {
312             Roo.MessageBox.alert("Sorry", "Language not available yet (" + lang +')');
313             return;
314         }
315         
316         
317         Roo.apply(_T, _T[lang]);
318         // just need to set the text values for everything...
319         var _this = this;
320         /* this will not work ...
321         if (this.form) { 
322             
323                
324             function formLabel(name, val) {
325                 _this.form.findField(name).fieldEl.child('label').dom.innerHTML  = val;
326             }
327             
328             formLabel('password', "Password"+':');
329             formLabel('username', "Email Address"+':');
330             formLabel('lang', "Language"+':');
331             this.dialog.setTitle("Login");
332             this.dialog.buttons[0].setText("Forgot Password");
333             this.dialog.buttons[1].setText("Login");
334         }
335         */
336         
337         
338     },
339     
340     
341     title: "Login",
342     modal: true,
343     width:  350,
344     //height: 230,
345     height: 180,
346     shadow: true,
347     minWidth:200,
348     minHeight:180,
349     //proxyDrag: true,
350     closable: false,
351     draggable: false,
352     collapsible: false,
353     resizable: false,
354     center: {  // needed??
355         autoScroll:false,
356         titlebar: false,
357        // tabPosition: 'top',
358         hideTabs: true,
359         closeOnTab: true,
360         alwaysShowTabs: false
361     } ,
362     listeners : {
363         
364         show  : function(dlg)
365         {
366             //console.log(this);
367             this.form = this.layout.getRegion('center').activePanel.form;
368             this.form.dialog = dlg;
369             this.buttons[0].form = this.form;
370             this.buttons[0].dialog = dlg;
371             this.buttons[1].form = this.form;
372             this.buttons[1].dialog = dlg;
373            
374            //this.resizeToLogo.defer(1000,this);
375             // this is all related to resizing for logos..
376             //var sz = Roo.get(Pman.Login.form.el.query('img')[0]).getSize();
377            //// if (!sz) {
378              //   this.resizeToLogo.defer(1000,this);
379              //   return;
380            // }
381             //var w = Ext.lib.Dom.getViewWidth() - 100;
382             //var h = Ext.lib.Dom.getViewHeight() - 100;
383             //this.resizeTo(Math.max(350, Math.min(sz.width + 30, w)),Math.min(sz.height+200, h));
384             //this.center();
385             if (this.disabled) {
386                 this.hide();
387                 return;
388             }
389             
390             if (this.user.id < 0) { // used for inital setup situations.
391                 return;
392             }
393             
394             if (this.intervalID) {
395                 // remove the timer
396                 window.clearInterval(this.intervalID);
397                 this.intervalID = false;
398             }
399             
400             
401             if (Roo.get('loading')) {
402                 Roo.get('loading').remove();
403             }
404             if (Roo.get('loading-mask')) {
405                 Roo.get('loading-mask').hide();
406             }
407             
408             //incomming._node = tnode;
409             this.form.reset();
410             //this.dialog.modal = !modal;
411             //this.dialog.show();
412             this.el.unmask(); 
413             
414             
415             this.form.setValues({
416                 'username' : Roo.state.Manager.get(this.realm + '.username', ''),
417                 'lang' : Roo.state.Manager.get(this.realm + '.lang', 'en')
418             });
419             
420             this.switchLang(Roo.state.Manager.get(this.realm + '.lang', 'en'));
421             if (this.form.findField('username').getValue().length > 0 ){
422                 this.form.findField('password').focus();
423             } else {
424                this.form.findField('username').focus();
425             }
426     
427         }
428     },
429     items : [
430          {
431        
432             xtype : 'ContentPanel',
433             xns : Roo,
434             region: 'center',
435             fitToFrame : true,
436             
437             items : [
438     
439                 {
440                
441                     xtype : 'Form',
442                     xns : Roo.form,
443                     labelWidth: 100,
444                     style : 'margin: 10px;',
445                     
446                     listeners : {
447                         actionfailed : function(f, act) {
448                             // form can return { errors: .... }
449                                 
450                             //act.result.errors // invalid form element list...
451                             //act.result.errorMsg// invalid form element list...
452                             
453                             this.dialog.el.unmask();
454                             Roo.MessageBox.alert("Error", act.result.errorMsg ? act.result.errorMsg : 
455                                         "Login failed - communication error - try again.");
456                                       
457                         },
458                         actioncomplete: function(re, act) {
459                              
460                             Roo.state.Manager.set(
461                                 this.dialog.realm + '.username',  
462                                     this.findField('username').getValue()
463                             );
464                             Roo.state.Manager.set(
465                                 this.dialog.realm + '.lang',  
466                                 this.findField('lang').getValue() 
467                             );
468                             
469                             this.dialog.fillAuth(act.result.data);
470                               
471                             this.dialog.hide();
472                             
473                             if (Roo.get('loading-mask')) {
474                                 Roo.get('loading-mask').show();
475                             }
476                             Roo.XComponent.build();
477                             
478                              
479                             
480                         }
481                     },
482                     items : [
483                         {
484                             xtype : 'TextField',
485                             xns : Roo.form,
486                             fieldLabel: "Email Address",
487                             name: 'username',
488                             width:200,
489                             autoCreate : {tag: "input", type: "text", size: "20"}
490                         },
491                         {
492                             xtype : 'TextField',
493                             xns : Roo.form,
494                             fieldLabel: "Password",
495                             inputType: 'password',
496                             name: 'password',
497                             width:200,
498                             autoCreate : {tag: "input", type: "text", size: "20"},
499                             listeners : {
500                                 specialkey : function(e,ev) {
501                                     if (ev.keyCode == 13) {
502                                         this.form.dialog.el.mask("Logging in");
503                                         this.form.doAction('submit', {
504                                             url: this.form.dialog.url,
505                                             method: this.form.dialog.method
506                                         });
507                                     }
508                                 }
509                             }  
510                         },
511                         {
512                             xtype : 'ComboBox',
513                             xns : Roo.form,
514                             fieldLabel: "Language",
515                             name : 'langdisp',
516                             store: {
517                                 xtype : 'SimpleStore',
518                                 fields: ['lang', 'ldisp'],
519                                 data : [
520                                     [ 'en', 'English' ],
521                                     [ 'zh_HK' , '\u7E41\u4E2D' ],
522                                     [ 'zh_CN', '\u7C21\u4E2D' ]
523                                 ]
524                             },
525                             
526                             valueField : 'lang',
527                             hiddenName:  'lang',
528                             width: 200,
529                             displayField:'ldisp',
530                             typeAhead: false,
531                             editable: false,
532                             mode: 'local',
533                             triggerAction: 'all',
534                             emptyText:'Select a Language...',
535                             selectOnFocus:true,
536                             listeners : {
537                                 select :  function(cb, rec, ix) {
538                                     this.form.switchLang(rec.data.lang);
539                                 }
540                             }
541                         
542                         }
543                     ]
544                 }
545                   
546                 
547             ]
548         }
549     ],
550     buttons : [
551         {
552             xtype : 'Button',
553             xns : 'Roo',
554             text : "Forgot Password",
555             listeners : {
556                 click : function() {
557                     //console.log(this);
558                     var n = this.form.findField('username').getValue();
559                     if (!n.length) {
560                         Roo.MessageBox.alert("Error", "Fill in your email address");
561                         return;
562                     }
563                     Roo.Ajax.request({
564                         url: this.dialog.url,
565                         params: {
566                             passwordRequest: n
567                         },
568                         method: this.dialog.method,
569                         success:  function(response, opts)  {  // check successfull...
570                         
571                             var res = this.dialog.processResponse(response);
572                             if (!res.success) { // error!
573                                Roo.MessageBox.alert("Error" ,
574                                     res.errorMsg ? res.errorMsg  : "Problem Requesting Password Reset");
575                                return;
576                             }
577                             Roo.MessageBox.alert("Notice" ,
578                                 "Please check you email for the Password Reset message");
579                         },
580                         failure : function() {
581                             Roo.MessageBox.alert("Error" , "Problem Requesting Password Reset");
582                         }
583                         
584                     });
585                 }
586             }
587         },
588         {
589             xtype : 'Button',
590             xns : 'Roo',
591             text : "Login",
592             listeners : {
593                 
594                 click : function () {
595                         
596                     this.dialog.el.mask("Logging in");
597                     this.form.doAction('submit', {
598                             url: this.dialog.url,
599                             method: this.dialog.method
600                     });
601                 }
602             }
603         }
604     ]
605   
606   
607 })
608  
609
610
611