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