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