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