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