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