CADI and a few small updates.
[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.springframework.beans.factory.annotation.Value;
44 import org.springframework.context.annotation.PropertySource;
45
46 import com.fasterxml.jackson.databind.ObjectMapper;
47
48 /**
49  * This filter class does authorization from AAF
50  *  
51  * @author sp931a
52  *
53  */
54 @PropertySource(value = {"file:/opt/app/music/etc/music.properties"})
55 public class MusicAuthorizationFilter implements Filter {
56
57     @Value("${music.aaf.ns}")
58     private String musicNS;
59     
60     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAuthorizationFilter.class);
61
62     public MusicAuthorizationFilter() throws ServletException {
63         super();
64     }
65
66     @Override
67     public void init(FilterConfig filterConfig) throws ServletException {
68
69     }
70
71     @Override
72     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
73             throws IOException, ServletException {
74
75         logger.debug(EELFLoggerDelegate.applicationLogger,
76                 "In MusicAuthorizationFilter doFilter start() ::::::::::::::::::::::::");
77
78         HttpServletResponse httpResponse = null;
79
80         boolean isAuthAllowed = false;
81
82         if (null != servletRequest && null != servletResponse) {
83             httpResponse = (HttpServletResponse) servletResponse;
84
85             logger.debug(EELFLoggerDelegate.applicationLogger,
86                     "Music NS defined in music property file  --------------------------" + musicNS);
87             
88             long startTime = 0;
89             if( null != servletRequest.getAttribute("startTime")) {
90                 startTime = ((Long)servletRequest.getAttribute("startTime")).longValue();
91             } else {
92                 startTime = System.currentTimeMillis(); // this will set only incase the request attribute not found
93             }
94
95             try {
96                 isAuthAllowed = AuthUtil.isAccessAllowed(servletRequest, musicNS);
97             } catch (Exception e) {
98                 logger.error(EELFLoggerDelegate.applicationLogger,
99                         "Error while checking authorization :::" + e.getMessage());
100             }
101
102             long endTime = System.currentTimeMillis();
103             
104             //startTime set in <code>CadiAuthFilter</code> doFilter
105             logger.debug(EELFLoggerDelegate.applicationLogger,
106                     "Time took for authentication & authorization : " 
107                     + (endTime - startTime) + " milliseconds");
108
109             if (!isAuthAllowed) {
110                 logger.debug(EELFLoggerDelegate.applicationLogger,
111                     "Unauthorized Access");
112                 AuthorizationError authError = new AuthorizationError();
113                 authError.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED);
114                 authError.setResponseMessage("Unauthorized Access - Please make sure you are "
115                     + "onboarded and have proper access to MUSIC. ");
116
117                 byte[] responseToSend = restResponseBytes(authError);
118                 httpResponse.setHeader("Content-Type", "application/json");
119
120                 httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
121                 servletResponse.getOutputStream().write(responseToSend);
122                 return;
123             } else {
124                 filterChain.doFilter(servletRequest, servletResponse);
125             }
126         }
127         logger.debug(EELFLoggerDelegate.applicationLogger,
128                 "In MusicAuthorizationFilter doFilter exit() ::::::::::::::::::::::::");
129     }
130
131     private byte[] restResponseBytes(AuthorizationError eErrorResponse) throws IOException {
132         String serialized = new ObjectMapper().writeValueAsString(eErrorResponse);
133         return serialized.getBytes();
134     }
135
136     private Map<String, String> getHeadersInfo(HttpServletRequest request) {
137
138         Map<String, String> map = new HashMap<String, String>();
139
140         Enumeration headerNames = request.getHeaderNames();
141         while (headerNames.hasMoreElements()) {
142             String key = (String) headerNames.nextElement();
143             String value = request.getHeader(key);
144             map.put(key, value);
145         }
146
147         return map;
148     }
149
150     private static String getUserNamefromRequest(HttpServletRequest httpRequest) {
151         String authHeader = httpRequest.getHeader("Authorization");
152         String username = null;
153         if (authHeader != null) {
154             String[] split = authHeader.split("\\s+");
155             if (split.length > 0) {
156                 String basic = split[0];
157
158                 if ("Basic".equalsIgnoreCase(basic)) {
159                     byte[] decodedBytes = Base64.getDecoder().decode(split[1]);
160                     String decodedString = new String(decodedBytes);
161                     int p = decodedString.indexOf(":");
162                     if (p != -1) {
163                         username = decodedString.substring(0, p);
164                     }
165                 }
166             }
167         }
168         return username;
169     }
170 }