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