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