Some bug fixes and Minor Chages.
[music.git] / src / main / java / org / onap / music / authentication / MusicAuthorizationFilter.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  *  Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *  Licensed under the Apache License, Version 2.0 (the "License");
10  *  you may not use this file except in compliance with the License.
11  *  You may obtain a copy of the License at
12  *
13  *     http://www.apache.org/licenses/LICENSE-2.0
14  *
15  *  Unless required by applicable law or agreed to in writing, software
16  *  distributed under the License is distributed on an "AS IS" BASIS,
17  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  *  See the License for the specific language governing permissions and
19  *  limitations under the License.
20  *
21  * ============LICENSE_END=============================================
22  * ====================================================================
23  */
24
25 package org.onap.music.authentication;
26
27 import java.io.IOException;
28 import java.util.Base64;
29 import java.util.Enumeration;
30 import java.util.HashMap;
31 import java.util.Map;
32
33 import javax.servlet.Filter;
34 import javax.servlet.FilterChain;
35 import javax.servlet.FilterConfig;
36 import javax.servlet.ServletException;
37 import javax.servlet.ServletRequest;
38 import javax.servlet.ServletResponse;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41
42 import org.onap.music.eelf.logging.EELFLoggerDelegate;
43 import org.onap.music.main.MusicUtil;
44 import com.fasterxml.jackson.databind.ObjectMapper;
45
46 /**
47  * This filter class does authorization from AAF
48  *  
49  * @author sp931a
50  *
51  */
52 //@PropertySource(value = {"file:/opt/app/music/etc/music.properties"})
53 public class MusicAuthorizationFilter implements Filter {
54
55     private String musicNS = MusicUtil.getMusicAafNs();
56     
57     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAuthorizationFilter.class);
58
59     public MusicAuthorizationFilter() throws ServletException {
60         super();
61     }
62
63     @Override
64     public void init(FilterConfig filterConfig) throws ServletException {
65
66     }
67
68     @Override
69     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
70         throws IOException, ServletException {
71         HttpServletResponse httpResponse = null;
72
73         boolean isAuthAllowed = false;
74
75         if (null != servletRequest && null != servletResponse) {
76             httpResponse = (HttpServletResponse) servletResponse;
77             long startTime = 0;
78             if( null != servletRequest.getAttribute("startTime")) {
79                 startTime = ((Long)servletRequest.getAttribute("startTime")).longValue();
80             } else {
81                 startTime = System.currentTimeMillis(); // this will set only incase the request attribute not found
82             }
83
84             try {
85                 isAuthAllowed = AuthUtil.isAccessAllowed(servletRequest, musicNS);
86             } catch (Exception e) {
87                 logger.error(EELFLoggerDelegate.securityLogger,
88                     "Error while checking authorization Music Namespace: " + musicNS + " : " + e.getMessage());
89             }
90
91             long endTime = System.currentTimeMillis();
92             
93             //startTime set in <code>CadiAuthFilter</code> doFilter
94             logger.debug(EELFLoggerDelegate.securityLogger,
95                 "Time took for authentication & authorization : " 
96                 + (endTime - startTime) + " milliseconds");
97
98             if (!isAuthAllowed) {
99                 logger.info(EELFLoggerDelegate.securityLogger,
100                     "Unauthorized Access");
101                 AuthorizationError authError = new AuthorizationError();
102                 authError.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED);
103                 authError.setResponseMessage("Unauthorized Access - Please make sure you are "
104                     + "onboarded and have proper access to MUSIC. ");
105
106                 byte[] responseToSend = restResponseBytes(authError);
107                 httpResponse.setHeader("Content-Type", "application/json");
108
109                 httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
110                 servletResponse.getOutputStream().write(responseToSend);
111                 return;
112             } else {
113                 filterChain.doFilter(servletRequest, servletResponse);
114             }
115         }
116     }
117
118     private byte[] restResponseBytes(AuthorizationError eErrorResponse) throws IOException {
119         String serialized = new ObjectMapper().writeValueAsString(eErrorResponse);
120         return serialized.getBytes();
121     }
122
123     private Map<String, String> getHeadersInfo(HttpServletRequest request) {
124
125         Map<String, String> map = new HashMap<String, String>();
126
127         Enumeration headerNames = request.getHeaderNames();
128         while (headerNames.hasMoreElements()) {
129             String key = (String) headerNames.nextElement();
130             String value = request.getHeader(key);
131             map.put(key, value);
132         }
133
134         return map;
135     }
136
137     private static String getUserNamefromRequest(HttpServletRequest httpRequest) {
138         String authHeader = httpRequest.getHeader("Authorization");
139         String username = null;
140         if (authHeader != null) {
141             String[] split = authHeader.split("\\s+");
142             if (split.length > 0) {
143                 String basic = split[0];
144
145                 if ("Basic".equalsIgnoreCase(basic)) {
146                     byte[] decodedBytes = Base64.getDecoder().decode(split[1]);
147                     String decodedString = new String(decodedBytes);
148                     int p = decodedString.indexOf(":");
149                     if (p != -1) {
150                         username = decodedString.substring(0, p);
151                     }
152                 }
153             }
154         }
155         return username;
156     }
157 }