b9ade57449da35629d5b664502496cac8f550367
[aaf/authz.git] / auth / auth-gui / src / main / java / org / onap / aaf / auth / gui / Page.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21
22 package org.onap.aaf.auth.gui;
23
24 import static org.onap.aaf.misc.xgen.html.HTMLGen.A;
25 import static org.onap.aaf.misc.xgen.html.HTMLGen.H1;
26 import static org.onap.aaf.misc.xgen.html.HTMLGen.LI;
27 import static org.onap.aaf.misc.xgen.html.HTMLGen.TITLE;
28 import static org.onap.aaf.misc.xgen.html.HTMLGen.UL;
29
30 import java.io.File;
31 import java.io.FileInputStream;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Properties;
38 import java.util.TreeMap;
39
40 import javax.servlet.http.Cookie;
41 import javax.servlet.http.HttpServletRequest;
42
43 import org.onap.aaf.auth.common.Define;
44 import org.onap.aaf.auth.env.AuthzEnv;
45 import org.onap.aaf.auth.env.AuthzTrans;
46 import org.onap.aaf.auth.gui.pages.Home;
47 import org.onap.aaf.cadi.Permission;
48 import org.onap.aaf.cadi.aaf.AAFPermission;
49 import org.onap.aaf.cadi.config.Config;
50 import org.onap.aaf.cadi.principal.TaggedPrincipal;
51 import org.onap.aaf.misc.env.APIException;
52 import org.onap.aaf.misc.env.Env;
53 import org.onap.aaf.misc.env.Slot;
54 import org.onap.aaf.misc.env.StaticSlot;
55 import org.onap.aaf.misc.env.util.Split;
56 import org.onap.aaf.misc.xgen.Cache;
57 import org.onap.aaf.misc.xgen.CacheGen;
58 import org.onap.aaf.misc.xgen.Code;
59 import org.onap.aaf.misc.xgen.DynamicCode;
60 import org.onap.aaf.misc.xgen.Mark;
61 import org.onap.aaf.misc.xgen.html.HTMLCacheGen;
62 import org.onap.aaf.misc.xgen.html.HTMLGen;
63 import org.onap.aaf.misc.xgen.html.Imports;
64
65 /**
66  * A Base "Mobile First" Page
67  *
68  * @author Jonathan
69  *
70  */
71 public class Page extends HTMLCacheGen {
72     public static final String AAF_THEME = "aaf_theme";
73     public static final String AAFURL_TOOLS = "aaf_url.tools";
74     public static final String AAF_URL_TOOL_DOT = "aaf_url.tool.";
75     public static final String AAF_URL_CUIGUI = "aaf_url.cuigui"; // link to help
76     public static final String AAF_URL_GUI_ONBOARD = "aaf_url.gui_onboard";
77     public static final String AAF_URL_AAF_HELP = "aaf_url.aaf_help";
78     public static final String AAF_URL_CADI_HELP = "aaf_url.cadi_help";
79     public static final String PERM_CA_TYPE = "certman";
80     public static final String PERM_NS = Define.ROOT_NS();
81     public static final String HREF = "href=";
82     public static final String TARGET_BLANK = "target=_blank";
83
84     public enum BROWSER {IPHONE, HTML5, IE, IEOLD};
85
86     public static final int MAX_LINE = 20;
87     protected static final String[] NO_FIELDS = new String[0];
88     private static final String BROWSER_TYPE = "BROWSER_TYPE";
89
90     private final String bcName;
91     private final String bcUrl;
92     private final String[] fields;
93
94     public final boolean noCache;
95
96     // Note: Only access is synchronized in "getPerm"
97     private static final Map<String,Map<String,Permission>> perms = new HashMap<>();
98
99     /*
100      *      Relative path, Menu Name, Full Path
101      */
102     protected static final String[][] MENU_ITEMS = new String[][] {
103             {"myperms","My Permissions","/gui/myperms"},
104             {"myroles","My Roles","/gui/myroles"},
105             {"ns","My Namespaces","/gui/ns"},
106             {"approve","My Approvals","/gui/approve"},
107             {"myrequests","My Pending Requests","/gui/myrequests"},
108              // Enable later
109              //{"onboard","Onboarding"},
110             {"passwd","Password Management","/gui/passwd"},
111             {"cui","Command Prompt","/gui/cui"},
112             {"api","AAF API","/gui/api"},
113             {"clear","Clear Preferences","/gui/clear"}
114     };
115
116     public String name() {
117         return bcName;
118     }
119
120     public String url() {
121         return bcUrl;
122     }
123
124     public String[] fields() {
125         return fields;
126     }
127
128     public Page(AuthzEnv env, String name, String url, Enum<?>[] en, final NamedCode ...content) throws APIException, IOException {
129         super(CacheGen.PRETTY, new PageCode(env, 1, content));
130         fields = new String[en.length];
131         int i=-1;
132         for (Enum<?> p : en) {
133             fields[++i]=p.name();
134         }
135
136         bcName = name;
137         bcUrl = url;
138         // Mark which fields must be "no_cache"
139         boolean noCacheTemp=false;
140         for (NamedCode nc : content) {
141             if (nc.noCache()) {
142                 noCacheTemp=true;
143                 break;
144             }
145         }
146         noCache =noCacheTemp;
147     }
148     public Page(AuthzEnv env, String name, String url, String [] fields, final NamedCode ... content) throws APIException,IOException {
149         this(env,name,url,1,fields,content);
150     }
151
152     public Page(AuthzEnv env, String name, String url, int backdots, String [] fields, final NamedCode ... content) throws APIException,IOException {
153         super(CacheGen.PRETTY, new PageCode(env, backdots, content));
154         if (fields==null) {
155             this.fields = new String[0];
156         } else {
157             this.fields = fields;
158         }
159         bcName = name;
160         bcUrl = url;
161         // Mark which fields must be "no_cache"
162         boolean noCacheTemp=false;
163         for (NamedCode nc : content) {
164             if (nc.noCache()) {
165                 noCacheTemp=true;
166                 break;
167             }
168         }
169         noCache =noCacheTemp;
170     }
171
172
173     private static class PageCode implements Code<HTMLGen> {
174             private static final String AAF_GUI_THEME = "aaf.gui.theme";
175             private static final String AAF_GUI_TITLE = "aaf_gui_title";
176
177             private final ContentCode[] content;
178             private final Slot browserSlot;
179             private final int backdots;
180             protected AuthzEnv env;
181             private StaticSlot sTheme;
182             private static Map<String,List<String>> themes;
183             private static Map<String,Properties> themeProps;
184
185             public PageCode(AuthzEnv env, int backdots, final ContentCode[] content) {
186                 this.content = content;
187                 this.backdots = backdots;
188                 browserSlot = env.slot(BROWSER_TYPE);
189                 sTheme = env.staticSlot(AAF_GUI.AAF_GUI_THEME);
190                 this.env = env;
191                    getThemeFiles(env,""); //
192             }
193
194             private static synchronized List<String> getThemeFiles(Env env, String theme) {
195                 if(themes==null) {
196                     themes = new TreeMap<>();
197                     File themeD = new File("theme");
198                     if(themeD.exists() && themeD.isDirectory()) {
199                         for (File t : themeD.listFiles()) {
200                             if(t.isDirectory()) {
201                                 List<String> la = new ArrayList<>();
202                                 for(File f : t.listFiles()) {
203                                     if(f.isFile()) {
204                                         if(f.getName().endsWith(".props")) {
205                                             Properties props;
206                                             if(themeProps == null) {
207                                                 themeProps = new TreeMap<>();
208                                                 props = null;
209                                             } else {
210                                                 props = themeProps.get(t.getName());
211                                             }
212                                             if(props==null) {
213                                                 props = new Properties();
214                                                 themeProps.put(t.getName(), props);
215                                             }
216
217                                             try {
218                                                 FileInputStream fis = new FileInputStream(f);
219                                                 try {
220                                                     props.load(fis);
221                                                 } finally {
222                                                     fis.close();
223                                                 }
224                                             } catch (IOException e) {
225                                                 env.error().log(e);
226                                             }
227                                         } else {
228                                             la.add(f.getName());
229                                         }
230                                     }
231                                 }
232                                 themes.put(t.getName(),la);
233                             }
234                         }
235                     }
236                 }
237                 return themes.get(theme);
238             }
239
240             protected Imports getImports(Env env, String theme, int backdots, BROWSER browser) {
241                 List<String> ls = getThemeFiles(env,theme);
242                 Imports imp = new Imports(backdots);
243                 String prefix = "theme/" + theme + '/';
244                 for(String f : ls) {
245                     if(f.endsWith(".js")) {
246                         imp.js(prefix + f);
247                     } else if(f.endsWith(".css")) {
248                         if(f.endsWith("iPhone.css")) {
249                             if(BROWSER.IPHONE.equals(browser)) {
250                                 imp.css(prefix + f);
251                             }
252                         } else if (f.endsWith("Desktop.css")){
253                             if(!BROWSER.IPHONE.equals(browser)) {
254                                 imp.css(prefix + f);
255                             }
256                         // Make Console specific to Console page
257                         } else if (!"console.js".equals(f)) {
258                             imp.css(prefix + f);
259                         }
260                     }
261                 }
262                 return imp;
263             }
264
265             @Override
266             public void code(final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException {
267                 // Note: I found that App Storage saves everything about the page, or not.  Thus, if you declare the page uncacheable, none of the
268                 // Artifacts, like JPGs are stored, which makes this feature useless for Server driven elements
269                 cache.dynamic(hgen,  new DynamicCode<HTMLGen,AAF_GUI,AuthzTrans>() {
270                     @Override
271                     public void code(AAF_GUI state, AuthzTrans trans, final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException {
272                         switch(browser(trans,browserSlot)) {
273                             case IEOLD:
274                             case IE:
275                                 hgen.directive("!DOCTYPE html");
276                                 hgen.directive("meta", "http-equiv=X-UA-Compatible","content=IE=11");
277                             default:
278                         }
279                     }
280                 });
281                 hgen.html();
282                 final String title = env.getProperty(AAF_GUI_TITLE,"Authentication/Authorization Framework");
283                 final String defaultTheme = env.get(sTheme,"onap");
284
285                 Mark head = hgen.head();
286                     hgen.leaf(TITLE).text(title).end();
287                     cache.dynamic(hgen, new DynamicCode<HTMLGen,AAF_GUI,AuthzTrans>() {
288                         @Override
289                         public void code(AAF_GUI state, AuthzTrans trans, final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException {
290                             BROWSER browser = browser(trans,browserSlot);
291                             String theme = null;
292                             Cookie[] cookies = trans.hreq().getCookies();
293                             if(cookies!=null) {
294                                 for(Cookie c : cookies) {
295                                     if(AAF_GUI_THEME.equals(c.getName())) {
296                                         theme=c.getValue();
297                                         if(!(themes.containsKey(theme))) {
298                                             theme = defaultTheme;
299                                         }
300                                         break;
301                                     }
302                                 }
303                             }
304
305                             if(theme==null) {
306                                 for(String t : themes.keySet()) {
307                                     if(!t.equals(defaultTheme) && trans.fish(new AAFPermission(null,trans.user()+":id", AAF_GUI_THEME, t))) {
308                                         theme=t;
309                                         break;
310                                     }
311                                 }
312                                 if(theme==null) {
313                                     theme = defaultTheme;
314                                 }
315                                 List<String> ls = getThemeFiles(trans, theme);
316                                 if(ls==null) {
317                                     throw new APIException("Theme " + theme + " does not exist.");
318                                 }
319                                 Cookie cookie = new Cookie(AAF_GUI_THEME,theme);
320                                 cookie.setMaxAge(604_800); // one week
321                                 trans.hresp().addCookie(cookie);
322                             }
323                             trans.setProperty(Page.AAF_THEME, theme);
324
325                             hgen.imports(getImports(env,theme,backdots,browser));
326                             switch(browser) {
327                                 case IE:
328                                 case IEOLD:
329                                     hgen.js().text("document.createElement('header');")
330                                             .text("document.createElement('nav');")
331                                             .done();
332                                     break;
333                                 default:
334                             }
335
336                         }
337                     });
338                     hgen.end(head);
339
340                 Mark body = hgen.body();
341                     Mark header = hgen.header();
342                     cache.dynamic(hgen, new DynamicCode<HTMLGen,AAF_GUI,AuthzTrans>() {
343                         @Override
344                         public void code(AAF_GUI state, AuthzTrans trans,Cache<HTMLGen> cache, HTMLGen xgen)
345                                 throws APIException, IOException {
346                             // Obtain Server Info, and print
347                             // AT&T Only
348                             String env = trans.getProperty(Config.AAF_ENV,"N/A");
349                             xgen.leaf(H1).text(title + " on " + env).end();
350                             xgen.leaf("p","id=version").text("AAF Version: " + state.deployedVersion).end();
351
352                             // Obtain User Info, and print
353                             TaggedPrincipal p = trans.getUserPrincipal();
354                             String user;
355                             String secured;
356                             if (p==null) {
357                                 user = "please choose a Login Authority";
358                                 secured = "NOT Secure!";
359                             } else {
360                                 user = p.personalName();
361                                 secured = p.tag();
362                             }
363                             xgen.leaf("p","id=welcome").text("Welcome, ")
364                                 .text(user)
365                                 .text("<sup>")
366                                 .text(secured)
367                                 .text("</sup>").end();
368
369                             switch(browser(trans,browserSlot)) {
370                                 case IEOLD:
371                                 case IE:
372                                     xgen.incr("h5").text("This app is Mobile First HTML5.  Internet Explorer "
373                                             + " does not support all HTML5 standards. Old, non TSS-Standard versions may not function correctly.").br()
374                                             .text("  For best results, use a highly compliant HTML5 browser like Firefox.")
375                                         .end();
376                                     break;
377                                 default:
378                             }
379                         }
380                     });
381
382                     hgen.hr();
383
384                     int cIdx;
385                     ContentCode nc;
386                     // If BreadCrumbs, put here
387                     if (content.length>0 && content[0] instanceof BreadCrumbs) {
388                         nc = content[0];
389                         Mark ctnt = hgen.divID(nc.idattrs());
390                         nc.code(cache, hgen);
391                         hgen.end(ctnt);
392                         cIdx = 1;
393                     } else {
394                         cIdx = 0;
395                     }
396
397                     hgen.end(header);
398
399                     hgen.divID("pageContent");
400                     Mark inner = hgen.divID("inner");
401                         // Content
402                         for (int i=cIdx;i<content.length;++i) {
403                             nc = content[i];
404                             Mark ctnt = hgen.divID(nc.idattrs());
405                             nc.code(cache, hgen);
406                             hgen.end(ctnt);
407                         }
408
409                     hgen.end(inner);
410
411
412                     cache.dynamic(hgen, new DynamicCode<HTMLGen,AAF_GUI,AuthzTrans>() {
413                         @Override
414                         public void code(AAF_GUI state, AuthzTrans trans,Cache<HTMLGen> cache, HTMLGen xgen) throws APIException, IOException {
415                             String theme = trans.getProperty(Page.AAF_THEME);
416                             Properties props;
417                             if(theme==null) {
418                                 props = null;
419                             } else {
420                                 props = themeProps==null?null:themeProps.get(theme);
421                             }
422
423                             if(props!=null && "TRUE".equalsIgnoreCase(props.getProperty("enable_nav_btn"))) {
424                                     xgen.leaf("button", "id=navBtn").end();
425                             }
426                         }
427                     });
428                     // Adding "nav Hamburger button"
429                     // Navigation - Using older Nav to work with decrepit   IE versions
430                     Mark nav = hgen.divID("nav");
431                     cache.dynamic(hgen, new DynamicCode<HTMLGen,AAF_GUI,AuthzTrans>() {
432                         @Override
433                         public void code(AAF_GUI state, AuthzTrans trans,Cache<HTMLGen> cache, HTMLGen xgen) throws APIException, IOException {
434                             String theme = trans.getProperty(Page.AAF_THEME);
435                             Properties props;
436                             if(theme==null) {
437                                 props = null;
438                             } else {
439                                 props = themeProps==null?null:themeProps.get(theme);
440                             }
441
442                             if((props!=null) && ("TRUE".equalsIgnoreCase(props.getProperty("main_menu_in_nav")))) {
443                                     xgen.incr("h2").text("Navigation").end();
444                                     Mark mark = new Mark();
445                                     boolean selected = isSelected(trans.path(),Home.HREF);
446                                     xgen.incr(mark,HTMLGen.UL)
447                                         .incr(HTMLGen.LI,selected?"class=selected":"")
448                                         .incr(HTMLGen.A, "href=home")
449                                         .text("Home")
450                                         .end(2);
451                                     boolean noSelection = !selected;
452                                     for(String[] mi : MENU_ITEMS) {
453                                         if(noSelection) {
454                                             selected = isSelected(trans.path(),mi[2]);
455                                             noSelection = !selected;
456                                         } else {
457                                             selected = false;
458                                         }
459                                         xgen.incr(HTMLGen.LI,selected?"class=selected":"")
460                                             .incr(HTMLGen.A, HREF+mi[2])
461                                             .text(mi[1])
462                                             .end(2);
463                                     }
464                                     xgen.end(mark);
465                             }
466                         }
467
468                         private boolean isSelected(String path, String item) {
469                             if(item.equals(path)) {
470                                 return true;
471                             } else {
472                                 for(ContentCode c : content) {
473                                     if(c instanceof BreadCrumbs) {
474                                         Page[] bc = ((BreadCrumbs)c).breadcrumbs;
475                                         if(bc!=null) {
476                                             for(int i = bc.length-1;i>0;--i) {
477                                                 if(bc[i].url().equals(item)) {
478                                                     return true;
479                                                 }
480                                             }
481                                             return false;
482                                         }
483                                     }
484                                 }
485                             }
486                             return false;
487                         }
488                     });
489                     hgen.incr("h2").text("Related Links").end();
490                     hgen.incr(UL);
491                     String aafHelp = env.getProperty(AAF_URL_AAF_HELP,null);
492                     if (aafHelp!=null) {
493                         hgen.leaf(LI).leaf(A,HREF+env.getProperty(AAF_URL_AAF_HELP),TARGET_BLANK).text("AAF WIKI").end(2);
494                         String sub = env.getProperty(AAF_URL_AAF_HELP+".sub");
495                         if (sub!=null) {
496                             hgen.incr(UL,"style=margin-left:5%");
497                             for (String s : Split.splitTrim(',', sub)) {
498                                 hgen.leaf(LI).leaf(A,HREF+env.getProperty(AAF_URL_AAF_HELP+".sub."+s),TARGET_BLANK).text(s.replace('+', ' ')).end(2);
499                             }
500                             hgen.end();
501                         }
502                     }
503                     aafHelp = env.getProperty(AAF_URL_CADI_HELP,null);
504                     if (aafHelp!=null) {
505                         hgen.leaf(LI).leaf(A,HREF+aafHelp,TARGET_BLANK).text("CADI WIKI").end(2);
506                     }
507                     String tools = env.getProperty(AAFURL_TOOLS);
508                     if (tools!=null) {
509                         hgen.hr()
510                             .incr(HTMLGen.UL,"style=margin-left:5%")
511                              .leaf(HTMLGen.H3).text("Related Tools").end();
512
513                         for (String tool : Split.splitTrim(',',tools)) {
514                             hgen.leaf(LI).leaf(A,HREF+env.getProperty(AAF_URL_TOOL_DOT+tool),TARGET_BLANK).text(tool.replace('+', ' ')).end(2);
515                         }
516                         hgen.end();
517                     }
518                     hgen.end();
519
520                     hgen.hr();
521
522                     hgen.end(nav);
523                     // Footer - Using older Footer to work with decrepit IE versions
524                     Mark footer = hgen.divID("footer");
525                         hgen.textCR(1, env.getProperty(AAF_GUI.AAF_GUI_COPYRIGHT))
526                         .end(footer);
527
528                     hgen.end(body);
529                 hgen.endAll();
530         }
531     }
532
533     public static String getBrowserType() {
534         return BROWSER_TYPE;
535     }
536
537     /**
538      * It's IE if int >=0
539      *
540      * Use int found in "ieVersion"
541      *
542      * Official IE 7
543      *         Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322;
544      *         .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
545      * Official IE 8
546      *         Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2;
547      *         .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; ATT)
548      *
549      * IE 11 Compatibility
550      *         Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727;
551      *         .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; InfoPath.3; HVD; ATT)
552      *
553      * IE 11 (not Compatiblity)
554      *         Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727;
555      *         .NET CLR 3.5.30729; .NET CLR 3.0.30729;    Media Center PC 6.0; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; InfoPath.3; HVD; ATT)
556      *
557      * @param trans
558      * @return
559      */
560     public static BROWSER browser(AuthzTrans trans, Slot slot) {
561         BROWSER br = trans.get(slot, null);
562         if (br==null) {
563             String agent = trans.agent();
564             int msie;
565             if (agent.contains("iPhone") /* other phones? */) {
566                 br=BROWSER.IPHONE;
567             } else if ((msie = agent.indexOf("MSIE"))>=0) {
568                 msie+=5;
569                 int end = agent.indexOf(';',msie);
570                 float ver;
571                 try {
572                     ver = Float.valueOf(agent.substring(msie,end));
573                     br = ver<8f?BROWSER.IEOLD :BROWSER.IE;
574                 } catch (Exception e) {
575                     br = BROWSER.IE;
576                 }
577             } else {
578                 br = BROWSER.HTML5;
579             }
580             trans.put(slot,br);
581         }
582         return br;
583     }
584
585     /*
586      * Get, rather than create each time, permissions for validations
587      */
588     protected static synchronized Permission getPerm(String instance, String action) {
589         Map<String,Permission> msp = perms.get(instance);
590         Permission p;
591         if (msp==null) {
592             msp = new HashMap<>();
593             perms.put(instance, msp);
594             p=null;
595         } else {
596             p = msp.get(instance);
597         }
598         if (p==null) {
599             p=new AAFPermission(PERM_NS, PERM_CA_TYPE,instance,action);
600             msp.put(action, p);
601         }
602         return p;
603      }
604
605     protected static String getSingleParam(HttpServletRequest req, String tag) {
606         String[] values = req.getParameterValues(tag);
607         return values.length<1?null:values[0];
608     }
609
610 }
611