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