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