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