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