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