cleanup
[cdm-vaadin.git] / src / main / java / eu / etaxonomy / cdm / vaadin / util / CdmVaadinAuthentication.java
1 /**
2 * Copyright (C) 2015 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9 package eu.etaxonomy.cdm.vaadin.util;
10
11 import java.util.HashMap;
12 import java.util.Map;
13
14 import org.apache.logging.log4j.LogManager;
15 import org.apache.logging.log4j.Logger;
16 import org.springframework.security.core.Authentication;
17 import org.springframework.security.core.context.SecurityContextHolder;
18
19 import eu.etaxonomy.cdm.common.URI;
20
21 /**
22 * @author cmathew
23 * @since 28 Apr 2015
24 */
25 public class CdmVaadinAuthentication {
26
27 private static final Logger logger = LogManager.getLogger();
28
29 public static final String KEY = "key_authentication";
30
31 Map<String, Authentication> hostAuthenticationMap = new HashMap<>();
32
33 public void addAuthentication(URI requestSourceUri, String requestSourceContext, Authentication authentication) {
34 addAuthentication(getRequestSource(requestSourceUri, requestSourceContext), authentication);
35 }
36
37 public void addAuthentication(String requestSource, Authentication authentication) {
38 if(requestSource == null || requestSource.isEmpty()) {
39 throw new IllegalStateException("When setting authentication, host cannot be null or empty");
40 }
41
42 if(authentication == null) {
43 throw new IllegalStateException("When setting authentication, authentication object cannot be null");
44 }
45 hostAuthenticationMap.put(requestSource, authentication);
46 }
47
48 public boolean isAuthenticated(URI uri, String context) {
49 if(uri != null && context != null && !context.isEmpty()) {
50 Authentication authentication = hostAuthenticationMap.get(getRequestSource(uri, context));
51 if(authentication != null) {
52 return authentication.isAuthenticated();
53 }
54 }
55 return false;
56 }
57
58 public Authentication getAuthentication(URI uri, String context){
59 return hostAuthenticationMap.get(getRequestSource(uri, context));
60 }
61
62 public boolean setSecurityContextAuthentication(URI uri, String context) {
63 if(uri != null && context != null && !context.isEmpty()) {
64 Authentication authentication = hostAuthenticationMap.get(getRequestSource(uri, context));
65 if(authentication != null && authentication.isAuthenticated()) {
66 SecurityContextHolder.getContext().setAuthentication(authentication);
67 return true;
68 }
69 }
70 return false;
71 }
72
73 public static String getRequestSource(URI uri, String context) {
74 String source = uri.getHost() + ":" + String.valueOf(uri.getPort()) + context;
75 logger.warn(" request source : " + source);
76 return source;
77 }
78
79
80
81 }