Fix checkstyle if-statements must use braces in aaa-idmlight
[aaa.git] / aaa-idmlight / src / main / java / org / opendaylight / aaa / idm / IdmLightProxy.java
1 /* Copyright (c) 2014 Hewlett-Packard Development Company, L.P. and others.
2  * All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.aaa.idm;
9
10 import static org.opendaylight.aaa.idm.persistence.StoreBuilder.DEFAULT_DOMAIN;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.concurrent.ConcurrentHashMap;
16
17 import org.opendaylight.aaa.ClaimBuilder;
18 import org.opendaylight.aaa.api.AuthenticationException;
19 import org.opendaylight.aaa.api.Claim;
20 import org.opendaylight.aaa.api.CredentialAuth;
21 import org.opendaylight.aaa.api.IdMService;
22 import org.opendaylight.aaa.api.PasswordCredentials;
23 import org.opendaylight.aaa.idm.model.Domain;
24 import org.opendaylight.aaa.idm.model.Domains;
25 import org.opendaylight.aaa.idm.model.Grant;
26 import org.opendaylight.aaa.idm.model.Grants;
27 import org.opendaylight.aaa.idm.model.Role;
28 import org.opendaylight.aaa.idm.model.User;
29 import org.opendaylight.aaa.idm.model.Users;
30 import org.opendaylight.aaa.idm.persistence.DomainStore;
31 import org.opendaylight.aaa.idm.persistence.GrantStore;
32 import org.opendaylight.aaa.idm.persistence.RoleStore;
33 import org.opendaylight.aaa.idm.persistence.StoreException;
34 import org.opendaylight.aaa.idm.persistence.UserStore;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * An OSGi proxy for the IdmLight server.
40  *
41  */
42 public class IdmLightProxy implements CredentialAuth<PasswordCredentials>,
43         IdMService {
44
45     private static Logger logger = LoggerFactory.getLogger(IdmLightProxy.class);
46     private static UserStore userStore = new UserStore();
47     private static GrantStore grantStore = new GrantStore();
48     private static DomainStore domainStore = new DomainStore();
49     private static RoleStore roleStore = new RoleStore();
50
51     // Simple map of claim cache by domain names
52     private static Map<String, Map<PasswordCredentials, Claim>> claimCache = new ConcurrentHashMap<>();
53     static {
54         claimCache.put(DEFAULT_DOMAIN, new ConcurrentHashMap<PasswordCredentials, Claim>());
55     }
56
57     @Override
58     public Claim authenticate(PasswordCredentials creds, String domain) {
59         String domainName = (domain == null) ? DEFAULT_DOMAIN : domain;
60         // FIXME: Add cache invalidation
61         Map<PasswordCredentials, Claim> cache = claimCache.get(domainName);
62         if (cache == null) {
63             cache = new ConcurrentHashMap<PasswordCredentials, Claim>();
64             claimCache.put(domainName, cache);
65         }
66         Claim claim = cache.get(creds);
67         if (claim == null) {
68             synchronized (claimCache) {
69                 claim = cache.get(creds);
70                 if (claim == null) {
71                     claim = dbAuthenticate(creds, domainName);
72                     if (claim != null) {
73                         cache.put(creds, claim);
74                     }
75                 }
76             }
77         }
78         return claim;
79     }
80
81     public static synchronized void clearClaimCache() {
82         for (Map<PasswordCredentials, Claim> cache : claimCache.values()) {
83             cache.clear();
84         }
85     }
86
87     private static Claim dbAuthenticate(PasswordCredentials creds, String domainName) {
88         Domain domain=null;
89         User user=null;
90         // check to see domain exists
91         // TODO: ensure domain names are unique change to 'getDomain'
92         debug("get domain");
93         try {
94            Domains domains = domainStore.getDomains(domainName);
95            List<Domain> domainList = domains.getDomains();
96            if (domainList.size()==0) {
97               throw new AuthenticationException("Domain :" + domainName + " does not exist");
98            }
99            domain = domainList.get(0);
100         }
101         catch (StoreException se) {
102            throw new AuthenticationException("idm data store exception :" + se.toString());
103         }
104
105         // check to see user exists and passes cred check
106         try {
107            debug("check user / pwd");
108            Users users = userStore.getUsers(creds.username());
109            List<User> userList = users.getUsers();
110            if (userList.size()==0) {
111               throw new AuthenticationException("User :" + creds.username() + " does not exist");
112            }
113            user = userList.get(0);
114            if (!creds.password().equalsIgnoreCase(user.getPassword())) {
115               throw new AuthenticationException("UserName / Password not found");
116            }
117
118            // get all grants & roles for this domain and user
119            debug("get grants");
120            List<String> roles = new ArrayList<String>();
121            Grants grants = grantStore.getGrants(domain.getDomainid(),user.getUserid());
122            List<Grant> grantList = grants.getGrants();
123            for (int z=0;z<grantList.size();z++) {
124               Grant grant = grantList.get(z);
125               Role role = roleStore.getRole(grant.getRoleid());
126               roles.add(role.getName());
127            }
128
129            // build up the claim
130            debug("build a claim");
131            ClaimBuilder claim = new ClaimBuilder();
132            claim.setUserId(user.getUserid().toString());
133            claim.setUser(creds.username());
134            claim.setDomain(domainName);
135            for (int z=0;z<roles.size();z++) {
136               claim.addRole(roles.get(z));
137            }
138            return claim.build();
139         }
140         catch (StoreException se) {
141            throw new AuthenticationException("idm data store exception :" + se.toString());
142         }
143     }
144
145     @Override
146     public String getUserId(String userName) {
147         debug("getUserid for userName:" + userName);
148         try {
149            Users users = userStore.getUsers(userName);
150            List<User> userList = users.getUsers();
151            if (userList.size()==0) {
152               return null;
153            }
154            User user = userList.get(0);
155            return user.getUserid().toString();
156         }
157         catch (StoreException se) {
158            logger.warn("error getting user " + se.toString());
159            return null;
160         }
161     }
162
163     @Override
164     public List<String> listDomains(String userId) {
165         debug("list Domains for userId:" + userId);
166         List<String> domains = new ArrayList<String>();
167         long uid=0;
168         try {
169            uid = Long.parseLong(userId);
170         }
171         catch (NumberFormatException nfe) {
172            logger.warn("not a valid userid:" + userId);
173            return domains;
174         }
175         try {
176            Grants grants = grantStore.getGrants(uid);
177            List<Grant> grantList = grants.getGrants();
178            for (int z=0;z<grantList.size();z++) {
179               Grant grant = grantList.get(z);
180               Domain domain = domainStore.getDomain(grant.getDomainid());
181               domains.add(domain.getName());
182            }
183            return domains;
184         }
185         catch (StoreException se) {
186            logger.warn("error getting domains " + se.toString());
187            return domains;
188         }
189
190     }
191
192     @Override
193     public List<String> listRoles(String userId, String domainName) {
194         debug("listRoles");
195         List<String> roles = new ArrayList<String>();
196
197         try {
198            // find domain name for specied domain name
199            Domains domains = domainStore.getDomains(domainName);
200            List<Domain> domainList = domains.getDomains();
201            if (domainList.size()==0) {
202               debug("DomainName: " + domainName + " Not found!");
203               return roles;
204            }
205            long did = domainList.get(0).getDomainid();
206
207            // validate userId
208            long uid=0;
209            try {
210               uid = Long.parseLong(userId);
211            }
212            catch (NumberFormatException nfe) {
213               logger.warn("not a valid userid:" + userId);
214               return roles;
215            }
216
217            // find all grants for uid and did
218            Grants grants = grantStore.getGrants(did,uid);
219            List<Grant> grantList = grants.getGrants();
220            for (int z=0;z<grantList.size();z++) {
221               Grant grant = grantList.get(z);
222               Role role = roleStore.getRole(grant.getRoleid());
223               roles.add(role.getName());
224            }
225
226            return roles;
227         }
228         catch (StoreException se) {
229            logger.warn("error getting roles " + se.toString());
230            return roles;
231         }
232     }
233
234     private static final void debug(String msg) {
235         if (logger.isDebugEnabled()) {
236             logger.debug(msg);
237         }
238     }
239 }
240