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