Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Api key #34

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.upc.gessi.qrapids.app.config.security;

import com.upc.gessi.qrapids.app.domain.models.AppUser;
import com.upc.gessi.qrapids.app.domain.repositories.AppUser.UserRepository;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ApiKeyAuthFilter extends OncePerRequestFilter {

private final UserRepository m_userRepository;
private final boolean m_enable;

public ApiKeyAuthFilter(UserRepository userRepository, boolean enable) {
this.m_userRepository = userRepository;
this.m_enable = enable;
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

String requestUri = request.getRequestURI();

// Check if the URI contains "/api"
if (requestUri.contains("/api") && this.m_enable) {

// Get the API key and secret from request headers
String requestApiKey = request.getHeader("X-API-KEY");

if (requestApiKey != null) {

//Get the username from the request api key
String username = requestApiKey.substring("apiKey_".length());

//Get the user with the username to check if exists
AppUser appUser = this.m_userRepository.findByUsername(username);

if (appUser == null) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().write("Unauthorized");
} else {
filterChain.doFilter(request, response);
}
}
else {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().write("Unauthorized");
}
}
else {
// If the URI does not contain "/api", proceed without filtering
filterChain.doFilter(request, response);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
Expand Down Expand Up @@ -43,17 +44,19 @@ public class WebSecurity extends WebSecurityConfigurerAdapter {
@Value("${security.api.enable}")
private boolean apiEnable;

@Value("${security.apiKey}")
private boolean apiKeyEnable;

public WebSecurity(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}

@Override
protected void configure( HttpSecurity http ) throws Exception {

String public_and_secure = ( this.securityEnable )? "/resources/**" : "/**";
String public_api = ( this.apiEnable )? "/api/**" : "/fonts/**";
protected void configure(HttpSecurity http) throws Exception {

String publicAndSecure = (this.securityEnable) ? "/resources/**" : "/**";
String publicApi = (this.apiEnable) ? "/api/**" : "/fonts/**";

http.cors().and().csrf().disable().authorizeRequests()

Expand All @@ -62,20 +65,21 @@ protected void configure( HttpSecurity http ) throws Exception {
.antMatchers(HttpMethod.GET, LOGIN_VIEW_URL).permitAll()
.antMatchers(PUBLIC_MATCHERS).permitAll()

.antMatchers(public_api).permitAll()
.antMatchers(public_and_secure).permitAll()
.antMatchers(publicAndSecure).permitAll()

.antMatchers(publicApi).hasAuthority("X-API-KEY") // Require API key for /api/**

.anyRequest().authenticated()
.and()

.addFilter(new JWTAuthenticationFilter(authenticationManager(),usersController))
.addFilter(new JWTAuthorizationFilter(authenticationManager(), userRepository, routeRepository ))
.addFilterBefore(new ApiKeyAuthFilter(userRepository, this.apiKeyEnable), UsernamePasswordAuthenticationFilter.class) // Add API key filter before other filters
.addFilter(new JWTAuthenticationFilter(authenticationManager(), usersController))
.addFilter(new JWTAuthorizationFilter(authenticationManager(), userRepository, routeRepository))

// this disables session creation on Spring Security
.sessionManagement().enableSessionUrlRewriting(false)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

}

@Override
Expand Down
3 changes: 3 additions & 0 deletions src/main/resources/static/js/categoriesScripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ $('#accept').click(function () {
else {
$.ajax({
url: '../api/categories',
headers: {
'X-API-KEY': 'apiKey_admin'
},
data: formData,
type: "POST",
contentType: false,
Expand Down
19 changes: 17 additions & 2 deletions src/main/resources/static/js/configMet.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@ app.controller('TablesCtrl', function($scope, $http) {

this.$onInit = function () {
var url = "../api/metrics/list";

$http({
method: "GET",
url: url
url: url,
headers: {
'X-API-KEY': 'apiKey_admin'
}
}).then(function mySuccess(response) {
$scope.metricCategory = response.data;
})
Expand All @@ -18,9 +22,13 @@ app.controller('TablesCtrl', function($scope, $http) {
console.log("IN getMetricsConfig");

var url = "../api/metrics";

$http({
method: "GET",
url: url
url: url,
headers: {
'X-API-KEY': 'apiKey_admin'
}
}).then(function mySuccess(response) {
var data = [];
response.data.forEach(function (metric) {
Expand Down Expand Up @@ -55,6 +63,9 @@ app.controller('TablesCtrl', function($scope, $http) {

$.ajax({
url: "../api/metrics/"+id,
headers: {
'X-API-KEY': 'apiKey_admin'
},
data: formData,
type: "PUT",
contentType: false,
Expand Down Expand Up @@ -87,8 +98,12 @@ app.controller('TablesCtrl', function($scope, $http) {
formData.append("url", url);
formData.append("categoryName", categoryName);
++cont;

$.ajax({
url: "../api/metrics/" + id,
headers: {
'X-API-KEY': 'apiKey_admin'
},
data: formData,
type: "PUT",
contentType: false,
Expand Down
36 changes: 36 additions & 0 deletions src/main/resources/static/js/configQRPattern.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ function buildTree() {
jQuery.ajax({
dataType: "json",
url: url,
headers: {
'X-API-KEY': 'apiKey_admin'
},
cache: false,
type: "GET",
async: false,
Expand Down Expand Up @@ -121,6 +124,9 @@ function getChosenPattern(currentPatternId) {
jQuery.ajax({
dataType: "json",
url: url,
headers: {
'X-API-KEY': 'apiKey_admin'
},
cache: false,
type: "GET",
async: true,
Expand Down Expand Up @@ -364,6 +370,9 @@ function getChosenClassifier(currentClassifierId) {
jQuery.ajax({
dataType: "json",
url: url,
headers: {
'X-API-KEY': 'apiKey_admin'
},
cache: false,
type: "GET",
async: true,
Expand Down Expand Up @@ -698,6 +707,9 @@ function savePattern() {

$.ajax({
url: url,
headers: {
'X-API-KEY': 'apiKey_admin'
},
data: formData,
type: saveMethod,
contentType: false,
Expand Down Expand Up @@ -756,6 +768,9 @@ function deletePattern() {

$.ajax({
url: url,
headers: {
'X-API-KEY': 'apiKey_admin'
},
type: "DELETE",
contentType: false,
processData: false,
Expand Down Expand Up @@ -894,6 +909,9 @@ function saveClassifier() {

$.ajax({
url: url,
headers: {
'X-API-KEY': 'apiKey_' + sessionStorage.getItem("userName")
},
data: formData,
type: saveMethod,
contentType: false,
Expand Down Expand Up @@ -1005,6 +1023,9 @@ function deleteClassifier() {

$.ajax({
url: url,
headers: {
'X-API-KEY': 'apiKey_' + sessionStorage.getItem("userName")
},
type: "DELETE",
contentType: false,
processData: false,
Expand Down Expand Up @@ -1063,6 +1084,9 @@ function fillParameterMetricSelect(parameterMetricSelect, selectedMetricId) {
jQuery.ajax({
dataType: "json",
url: urlMetrics,
headers: {
'X-API-KEY': 'apiKey_' + sessionStorage.getItem("userName")
},
cache: false,
type: "GET",
async: true,
Expand Down Expand Up @@ -1127,6 +1151,9 @@ function buildTreeMetrics() {
jQuery.ajax({
dataType: "json",
url: url,
headers: {
'X-API-KEY': 'apiKey_' + sessionStorage.getItem("userName")
},
cache: false,
type: "GET",
async: false,
Expand Down Expand Up @@ -1171,6 +1198,9 @@ function getChosenMetric(currentMetricId) {
jQuery.ajax({
dataType: "json",
url: url,
headers: {
'X-API-KEY': 'apiKey_' + sessionStorage.getItem("userName")
},
cache: false,
type: "GET",
async: true,
Expand Down Expand Up @@ -1295,6 +1325,9 @@ function saveMetric() {

$.ajax({
url: url,
headers: {
'X-API-KEY': 'apiKey_' + sessionStorage.getItem("userName")
},
data: formData,
type: saveMethod_metric,
contentType: false,
Expand Down Expand Up @@ -1344,6 +1377,9 @@ function deleteMetric() {

$.ajax({
url: url,
headers: {
'X-API-KEY': 'apiKey_' + sessionStorage.getItem("userName")
},
type: "DELETE",
contentType: false,
processData: false,
Expand Down
18 changes: 18 additions & 0 deletions src/main/resources/static/js/configSI.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ function getAssessSIUrl () {
jQuery.ajax({
dataType: "json",
url: url,
headers: {
'X-API-KEY': 'apiKey_admin'
},
cache: false,
type: "GET",
async: true,
Expand All @@ -37,6 +40,9 @@ function buildSIList() {
jQuery.ajax({
dataType: "json",
url: url,
headers: {
'X-API-KEY': 'apiKey_admin'
},
cache: false,
type: "GET",
async: true,
Expand Down Expand Up @@ -76,6 +82,9 @@ function clickOnTree(e){
jQuery.ajax({
dataType: "json",
url: postUrl,
headers: {
'X-API-KEY': 'apiKey_admin'
},
cache: false,
type: "GET",
async: true,
Expand Down Expand Up @@ -171,6 +180,9 @@ function loadFactors (show) {
// get factors from DB
$.ajax({
url: "../api/qualityFactors",
headers: {
'X-API-KEY': 'apiKey_admin'
},
type: "GET",
async: true,
success: function(data) {
Expand Down Expand Up @@ -405,6 +417,9 @@ $("#saveSI").click(function () {
formData.append("quality_factors", qualityFactors);
$.ajax({
url: postUrl,
headers: {
'X-API-KEY': 'apiKey_admin'
},
data: formData,
type: httpMethod,
contentType: false,
Expand All @@ -429,6 +444,9 @@ $("#deleteSI").click(function () {
if (confirm("\t\t This operation cannot be undone. \t\n Are you sure you want to delete this strategic indicator?")) {
jQuery.ajax({
url: deleteUrl,
headers: {
'X-API-KEY': 'apiKey_admin'
},
cache: false,
type: "DELETE",
async: true,
Expand Down
9 changes: 9 additions & 0 deletions src/main/resources/static/js/feedback.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ function getStrategicIndicators() {
jQuery.ajax({
dataType: "json",
url: '../api/strategicIndicators/current?profile='+profileId,
headers: {
'X-API-KEY': 'apiKey_admin'
},
cache: false,
type: "GET",
async: true,
Expand All @@ -24,6 +27,9 @@ function getFactors(strategicIndicators) {
jQuery.ajax({
dataType: "json",
url: '../api/strategicIndicators/qualityFactors/current?profile='+profileId,
headers: {
'X-API-KEY': 'apiKey_admin'
},
cache: false,
type: "GET",
async: true,
Expand Down Expand Up @@ -196,6 +202,9 @@ function newFeedback(strategicIndicator, newvalue){

$.ajax({
url: '../api/strategicIndicators/' + strategicIndicator.dbId + "/feedback",
headers: {
'X-API-KEY': 'apiKey_admin'
},
data: formData,
type: "POST",
contentType: false,
Expand Down
Loading