<artifactId>aaa-authn-api</artifactId>
<version>0.3.0-SNAPSHOT</version>
<packaging>bundle</packaging>
-
+ <dependencies>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-server</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
<build>
<plugins>
<plugin>
--- /dev/null
+package org.opendaylight.aaa.api;
+
+@SuppressWarnings("serial")
+public class IDMStoreException extends Exception{
+ public IDMStoreException(String msg){
+ super(msg);
+ }
+}
--- /dev/null
+package org.opendaylight.aaa.api;
+
+public class IDMStoreUtil {
+ public static String createDomainid(String domainName){
+ return domainName;
+ }
+
+ public static String createUserid(String username,String domainid){
+ return username+"@"+domainid;
+ }
+
+ public static String createRoleid(String rolename,String domainid){
+ return rolename+"@"+domainid;
+ }
+
+ public static String createGrantid(String userid,String domainid,String roleid){
+ return userid+"@"+roleid+"@"+domainid;
+ }
+}
--- /dev/null
+package org.opendaylight.aaa.api;
+
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Domains;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Grants;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.Roles;
+import org.opendaylight.aaa.api.model.User;
+import org.opendaylight.aaa.api.model.Users;
+
+public interface IIDMStore {
+ public static final String DEFAULT_DOMAIN = "sdn";
+ public static final int MAX_FIELD_LEN = 256;
+ //Domain methods
+ public Domain writeDomain(Domain domain) throws IDMStoreException;
+ public Domain readDomain(String domainid) throws IDMStoreException;
+ public Domain deleteDomain(String domainid) throws IDMStoreException;
+ public Domain updateDomain(Domain domain) throws IDMStoreException;
+ public Domains getDomains() throws IDMStoreException;
+ //Role methods
+ public Role writeRole(Role role) throws IDMStoreException;
+ public Role readRole(String roleid) throws IDMStoreException;
+ public Role deleteRole(String roleid) throws IDMStoreException;
+ public Role updateRole(Role role) throws IDMStoreException;
+ public Roles getRoles() throws IDMStoreException;
+ //User methods
+ public User writeUser(User user) throws IDMStoreException;
+ public User readUser(String userid) throws IDMStoreException;
+ public User deleteUser(String userid) throws IDMStoreException;
+ public User updateUser(User user) throws IDMStoreException;
+ public Users getUsers() throws IDMStoreException;
+ public Users getUsers(String username,String domain) throws IDMStoreException;
+ //Grant methods
+ public Grant writeGrant(Grant grant) throws IDMStoreException;
+ public Grant readGrant(String grantid) throws IDMStoreException;
+ public Grant deleteGrant(String grantid) throws IDMStoreException;
+ public Grants getGrants(String domainid,String userid) throws IDMStoreException;
+ public Grants getGrants(String userid) throws IDMStoreException;
+ public Grant readGrant(String domainid,String userid,String roleid) throws IDMStoreException;
+}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.api;
import java.security.MessageDigest;
import java.util.concurrent.locks.ReentrantReadWriteLock;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
this.description = description;
}
- public Boolean getEnabled() {
+ public Boolean isEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
-}
\ No newline at end of file
+
+ @Override
+ public int hashCode() {
+ return this.name.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ Domain other = (Domain)obj;
+ if(other==null)
+ return false;
+ if(compareValues(getName(), other.getName()) &&
+ compareValues(getDomainid(), other.getDomainid()) &&
+ compareValues(getDescription(), other.getDescription()))
+ return true;
+ return false;
+ }
+
+ private boolean compareValues(Object a,Object b){
+ if(a==null && b!=null)
+ return false;
+ if(a!=null && b==null)
+ return false;
+ if(a==null && b==null)
+ return true;
+ if(a.equals(b))
+ return true;
+ return false;
+ }
+}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
public void setRoleid(String id) {
this.roleid = id;
}
-}
+ @Override
+ public int hashCode() {
+ return this.getUserid().hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ Grant other = (Grant)obj;
+ if(other==null)
+ return false;
+ if(compareValues(getDomainid(), other.getDomainid()) &&
+ compareValues(getRoleid(), other.getRoleid()) &&
+ compareValues(getUserid(), other.getUserid()))
+ return true;
+ return false;
+ }
+
+ private boolean compareValues(Object a,Object b){
+ if(a==null && b!=null)
+ return false;
+ if(a!=null && b==null)
+ return false;
+ if(a==null && b==null)
+ return true;
+ if(a.equals(b))
+ return true;
+ return false;
+ }
+}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
return Response.status(this.code).entity(this).build();
}
-}
+}
\ No newline at end of file
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
public void setDescription(String description) {
this.description = description;
}
+ @Override
+ public int hashCode() {
+ return this.name.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ Role other = (Role)obj;
+ if(other==null)
+ return false;
+ if(compareValues(getName(), other.getName()) &&
+ compareValues(getRoleid(), other.getRoleid()) &&
+ compareValues(getDescription(), other.getDescription()))
+ return true;
+ return false;
+ }
- public void setDomainID(String domainid){
+ public void setDomainid(String domainid){
this.domainid = domainid;
}
- public String getDomainID(){
+ public String getDomainid(){
return this.domainid;
}
+
+ private boolean compareValues(Object a,Object b){
+ if(a==null && b!=null)
+ return false;
+ if(a!=null && b==null)
+ return false;
+ if(a==null && b==null)
+ return true;
+ if(a.equals(b))
+ return true;
+ return false;
+ }
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
this.description = description;
}
- public Boolean getEnabled() {
+ public Boolean isEnabled() {
return enabled;
}
return this.salt;
}
- public String getDomainID(){
+ public String getDomainid(){
return domainid;
}
- public void setDomainID(String domainid){
+ public void setDomainid(String domainid){
this.domainid = domainid;
}
-}
+ @Override
+ public int hashCode() {
+ return this.name.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ User other = (User)obj;
+ if(other==null)
+ return false;
+ if(compareValues(getName(), other.getName()) &&
+ compareValues(getEmail(), other.getEmail()) &&
+ compareValues(isEnabled(), other.isEnabled()) &&
+ compareValues(getPassword(), other.getPassword()) &&
+ compareValues(getSalt(), other.getSalt()) &&
+ compareValues(getUserid(), other.getUserid()) &&
+ compareValues(getDescription(), other.getDescription()))
+ return true;
+ return false;
+ }
+
+ private boolean compareValues(Object a,Object b){
+ if(a==null && b!=null)
+ return false;
+ if(a!=null && b==null)
+ return false;
+ if(a==null && b==null)
+ return true;
+ if(a.equals(b))
+ return true;
+ return false;
+ }
+}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.model;
+package org.opendaylight.aaa.api.model;
/**
*
<version>0.3.0-SNAPSHOT</version>
<dependencies>
+ <dependency>
+ <groupId>org.opendaylight.aaa</groupId>
+ <artifactId>aaa-authn-api</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>yang-binding</artifactId>
}
}
}
+
+ //authentication model is for generating objects to be stores in the
+ //data store for all the prev idm model objects.
+ container authentication{
+ list domain{
+ key domainid;
+ leaf domainid {
+ type string;
+ }
+ leaf name {
+ type string;
+ }
+ leaf description {
+ type string;
+ }
+ leaf enabled {
+ type boolean;
+ }
+ }
+
+ list user {
+ key userid;
+ leaf userid {
+ type string;
+ }
+ leaf name {
+ type string;
+ }
+ leaf description {
+ type string;
+ }
+ leaf enabled {
+ type boolean;
+ }
+ leaf email {
+ type string;
+ }
+ leaf password {
+ type string;
+ }
+ leaf salt {
+ type string;
+ }
+ leaf domainid {
+ type string;
+ }
+ }
+ list role {
+ key roleid;
+ leaf roleid {
+ type string;
+ }
+ leaf name {
+ type string;
+ }
+ leaf description {
+ type string;
+ }
+ leaf domainid {
+ type string;
+ }
+ }
+
+ list grant {
+ key grantid;
+ leaf grantid {
+ type string;
+ }
+ leaf domainid {
+ type string;
+ }
+ leaf userid {
+ type string;
+ }
+ leaf roleid {
+ type string;
+ }
+ }
+ }
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.aaa.authn.mdsal.store;
+
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+
+import org.opendaylight.aaa.api.IDMStoreException;
+import org.opendaylight.aaa.api.IDMStoreUtil;
+import org.opendaylight.aaa.api.SHA256Calculator;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.Authentication;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Domain;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.DomainBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.DomainKey;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.GrantBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.GrantKey;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Role;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.RoleBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.RoleKey;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.UserBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.UserKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.CheckedFuture;
+
+/**
+ * @author Sharon Aicler - saichler@cisco.com
+ *
+ */
+public class IDMMDSALStore {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(IDMMDSALStore.class);
+ private final DataBroker dataBroker;
+
+ public IDMMDSALStore(DataBroker dataBroker){
+ this.dataBroker = dataBroker;
+ }
+
+ public static final String getString(String aValue,String bValue){
+ if(aValue!=null)
+ return aValue;
+ return bValue;
+ }
+
+ public static final Boolean getBoolean(Boolean aValue,Boolean bValue){
+ if(aValue!=null)
+ return aValue;
+ return bValue;
+ }
+
+ public static boolean waitForSubmit(CheckedFuture<Void, TransactionCommitFailedException> submit){
+ //This can happen only when testing
+ if(submit==null)
+ return false;
+ while(!submit.isDone() && !submit.isCancelled()){
+ try{Thread.sleep(1000);}catch(Exception err){LOGGER.error("Interrupted",err);}
+ }
+ return submit.isCancelled();
+ }
+
+ //Domain methods
+ public Domain writeDomain(Domain domain) {
+ Preconditions.checkNotNull(domain);
+ Preconditions.checkNotNull(domain.getName());
+ Preconditions.checkNotNull(domain.isEnabled());
+ DomainBuilder b = new DomainBuilder();
+ b.setDescription(domain.getDescription());
+ b.setDomainid(domain.getName());
+ b.setEnabled(domain.isEnabled());
+ b.setName(domain.getName());
+ b.setKey(new DomainKey(b.getName()));
+ domain = b.build();
+ InstanceIdentifier<Domain> ID = InstanceIdentifier.create(Authentication.class).child(Domain.class,new DomainKey(domain.getDomainid()));
+ WriteTransaction wrt = dataBroker.newWriteOnlyTransaction();
+ wrt.put(LogicalDatastoreType.CONFIGURATION, ID, domain,true);
+ CheckedFuture<Void, TransactionCommitFailedException> submit = wrt.submit();
+ if(!waitForSubmit(submit)){
+ return domain;
+ }else{
+ return null;
+ }
+ }
+
+ public Domain readDomain(String domainid){
+ Preconditions.checkNotNull(domainid);
+ InstanceIdentifier<Domain> ID = InstanceIdentifier.create(Authentication.class).child(Domain.class,new DomainKey(domainid));
+ ReadOnlyTransaction rot = dataBroker.newReadOnlyTransaction();
+ CheckedFuture<Optional<Domain>, ReadFailedException> read = rot.read(LogicalDatastoreType.CONFIGURATION, ID);
+ if(read==null){
+ LOGGER.error("Failed to read domain from data store");
+ return null;
+ }
+ Optional<Domain> optional = null;
+ try {
+ optional = read.get();
+ } catch (InterruptedException | ExecutionException e1) {
+ LOGGER.error("Failed to read domain from data store",e1);
+ return null;
+ }
+
+ if(optional==null)
+ return null;
+
+ if(!optional.isPresent())
+ return null;
+
+ return optional.get();
+ }
+
+ public Domain deleteDomain(String domainid){
+ Preconditions.checkNotNull(domainid);
+ Domain domain = readDomain(domainid);
+ if(domain==null){
+ LOGGER.error("Failed to delete domain from data store, unknown domain");
+ return null;
+ }
+ InstanceIdentifier<Domain> ID = InstanceIdentifier.create(Authentication.class).child(Domain.class,new DomainKey(domainid));
+ WriteTransaction wrt = dataBroker.newWriteOnlyTransaction();
+ wrt.delete(LogicalDatastoreType.CONFIGURATION, ID);
+ wrt.submit();
+ return domain;
+ }
+
+ public Domain updateDomain(Domain domain) throws IDMStoreException {
+ Preconditions.checkNotNull(domain);
+ Preconditions.checkNotNull(domain.getDomainid());
+ Domain existing = readDomain(domain.getDomainid());
+ DomainBuilder b = new DomainBuilder();
+ b.setDescription(getString(domain.getDescription(), existing.getDescription()));
+ b.setName(existing.getName());
+ b.setEnabled(getBoolean(domain.isEnabled(), existing.isEnabled()));
+ return writeDomain(b.build());
+ }
+
+ public List<Domain> getAllDomains(){
+ InstanceIdentifier<Authentication> id = InstanceIdentifier.create(Authentication.class);
+ ReadOnlyTransaction rot = dataBroker.newReadOnlyTransaction();
+ CheckedFuture<Optional<Authentication>, ReadFailedException> read = rot.read(LogicalDatastoreType.CONFIGURATION, id);
+ if(read==null)
+ return null;
+
+ try{
+ if(read.get()==null)
+ return null;
+ if(read.get().isPresent()){
+ Authentication auth = read.get().get();
+ return auth.getDomain();
+ }
+ }catch(Exception err){
+ LOGGER.error("Failed to read domains",err);
+ }
+ return null;
+ }
+
+ public List<Role> getAllRoles(){
+ InstanceIdentifier<Authentication> id = InstanceIdentifier.create(Authentication.class);
+ ReadOnlyTransaction rot = dataBroker.newReadOnlyTransaction();
+ CheckedFuture<Optional<Authentication>, ReadFailedException> read = rot.read(LogicalDatastoreType.CONFIGURATION, id);
+ if(read==null)
+ return null;
+
+ try{
+ if(read.get()==null)
+ return null;
+ if(read.get().isPresent()){
+ Authentication auth = read.get().get();
+ return auth.getRole();
+ }
+ }catch(Exception err){
+ LOGGER.error("Failed to read domains",err);
+ }
+ return null;
+ }
+
+ public List<User> getAllUsers(){
+ InstanceIdentifier<Authentication> id = InstanceIdentifier.create(Authentication.class);
+ ReadOnlyTransaction rot = dataBroker.newReadOnlyTransaction();
+ CheckedFuture<Optional<Authentication>, ReadFailedException> read = rot.read(LogicalDatastoreType.CONFIGURATION, id);
+ if(read==null)
+ return null;
+
+ try{
+ if(read.get()==null)
+ return null;
+ if(read.get().isPresent()){
+ Authentication auth = read.get().get();
+ return auth.getUser();
+ }
+ }catch(Exception err){
+ LOGGER.error("Failed to read domains",err);
+ }
+ return null;
+ }
+
+ public List<Grant> getAllGrants(){
+ InstanceIdentifier<Authentication> id = InstanceIdentifier.create(Authentication.class);
+ ReadOnlyTransaction rot = dataBroker.newReadOnlyTransaction();
+ CheckedFuture<Optional<Authentication>, ReadFailedException> read = rot.read(LogicalDatastoreType.CONFIGURATION, id);
+ if(read==null)
+ return null;
+
+ try{
+ if(read.get()==null)
+ return null;
+ if(read.get().isPresent()){
+ Authentication auth = read.get().get();
+ return auth.getGrant();
+ }
+ }catch(Exception err){
+ LOGGER.error("Failed to read domains",err);
+ }
+ return null;
+ }
+
+ //Role methods
+ public Role writeRole(Role role) {
+ Preconditions.checkNotNull(role);
+ Preconditions.checkNotNull(role.getName());
+ Preconditions.checkNotNull(role.getDomainid());
+ Preconditions.checkNotNull(readDomain(role.getDomainid()));
+ RoleBuilder b = new RoleBuilder();
+ b.setDescription(role.getDescription());
+ b.setRoleid(IDMStoreUtil.createRoleid(role.getName(), role.getDomainid()));
+ b.setKey(new RoleKey(b.getRoleid()));
+ b.setName(role.getName());
+ b.setDomainid(role.getDomainid());
+ role = b.build();
+ InstanceIdentifier<Role> ID = InstanceIdentifier.create(Authentication.class).child(Role.class,new RoleKey(role.getRoleid()));
+ WriteTransaction wrt = dataBroker.newWriteOnlyTransaction();
+ wrt.put(LogicalDatastoreType.CONFIGURATION, ID, role,true);
+ CheckedFuture<Void, TransactionCommitFailedException> submit = wrt.submit();
+ if(!waitForSubmit(submit)){
+ return role;
+ }else{
+ return null;
+ }
+ }
+
+ public Role readRole(String roleid){
+ Preconditions.checkNotNull(roleid);
+ InstanceIdentifier<Role> ID = InstanceIdentifier.create(Authentication.class).child(Role.class,new RoleKey(roleid));
+ ReadOnlyTransaction rot = dataBroker.newReadOnlyTransaction();
+ CheckedFuture<Optional<Role>, ReadFailedException> read = rot.read(LogicalDatastoreType.CONFIGURATION, ID);
+ if(read==null){
+ LOGGER.error("Failed to read role from data store");
+ return null;
+ }
+ Optional<Role> optional = null;
+ try {
+ optional = read.get();
+ } catch (InterruptedException | ExecutionException e1) {
+ LOGGER.error("Failed to read role from data store",e1);
+ return null;
+ }
+
+ if(optional==null)
+ return null;
+
+ if(!optional.isPresent())
+ return null;
+
+ return optional.get();
+ }
+
+ public Role deleteRole(String roleid){
+ Preconditions.checkNotNull(roleid);
+ Role role = readRole(roleid);
+ if(role==null){
+ LOGGER.error("Failed to delete role from data store, unknown role");
+ return null;
+ }
+ InstanceIdentifier<Role> ID = InstanceIdentifier.create(Authentication.class).child(Role.class,new RoleKey(roleid));
+ WriteTransaction wrt = dataBroker.newWriteOnlyTransaction();
+ wrt.delete(LogicalDatastoreType.CONFIGURATION, ID);
+ wrt.submit();
+ return role;
+ }
+
+ public Role updateRole(Role role) {
+ Preconditions.checkNotNull(role);
+ Preconditions.checkNotNull(role.getRoleid());
+ Role existing = readRole(role.getRoleid());
+ RoleBuilder b = new RoleBuilder();
+ b.setDescription(getString(role.getDescription(), existing.getDescription()));
+ b.setName(existing.getName());
+ b.setDomainid(existing.getDomainid());
+ return writeRole(b.build());
+ }
+
+ //User methods
+ public User writeUser(User user) throws IDMStoreException {
+ Preconditions.checkNotNull(user);
+ Preconditions.checkNotNull(user.getName());
+ Preconditions.checkNotNull(user.getDomainid());
+ Preconditions.checkNotNull(readDomain(user.getDomainid()));
+ UserBuilder b = new UserBuilder();
+ if(user.getSalt()==null){
+ b.setSalt(SHA256Calculator.generateSALT());
+ }else{
+ b.setSalt(user.getSalt());
+ }
+ b.setUserid(IDMStoreUtil.createUserid(user.getName(), user.getDomainid()));
+ b.setDescription(user.getDescription());
+ b.setDomainid(user.getDomainid());
+ b.setEmail(user.getEmail());
+ b.setEnabled(user.isEnabled());
+ b.setKey(new UserKey(b.getUserid()));
+ b.setName(user.getName());
+ b.setPassword(SHA256Calculator.getSHA256(user.getPassword(), b.getSalt()));
+ user = b.build();
+ InstanceIdentifier<User> ID = InstanceIdentifier.create(Authentication.class).child(User.class,new UserKey(user.getUserid()));
+ WriteTransaction wrt = dataBroker.newWriteOnlyTransaction();
+ wrt.put(LogicalDatastoreType.CONFIGURATION, ID, user,true);
+ CheckedFuture<Void, TransactionCommitFailedException> submit = wrt.submit();
+ if(!waitForSubmit(submit)){
+ return user;
+ }else{
+ return null;
+ }
+ }
+
+ public User readUser(String userid){
+ Preconditions.checkNotNull(userid);
+ InstanceIdentifier<User> ID = InstanceIdentifier.create(Authentication.class).child(User.class,new UserKey(userid));
+ ReadOnlyTransaction rot = dataBroker.newReadOnlyTransaction();
+ CheckedFuture<Optional<User>, ReadFailedException> read = rot.read(LogicalDatastoreType.CONFIGURATION, ID);
+ if(read==null){
+ LOGGER.error("Failed to read user from data store");
+ return null;
+ }
+ Optional<User> optional = null;
+ try {
+ optional = read.get();
+ } catch (InterruptedException | ExecutionException e1) {
+ LOGGER.error("Failed to read domain from data store",e1);
+ return null;
+ }
+
+ if(optional==null)
+ return null;
+
+ if(!optional.isPresent())
+ return null;
+
+ return optional.get();
+ }
+
+ public User deleteUser(String userid){
+ Preconditions.checkNotNull(userid);
+ User user = readUser(userid);
+ if(user==null){
+ LOGGER.error("Failed to delete user from data store, unknown user");
+ return null;
+ }
+ InstanceIdentifier<User> ID = InstanceIdentifier.create(Authentication.class).child(User.class,new UserKey(userid));
+ WriteTransaction wrt = dataBroker.newWriteOnlyTransaction();
+ wrt.delete(LogicalDatastoreType.CONFIGURATION, ID);
+ wrt.submit();
+ return user;
+ }
+
+ public User updateUser(User user) throws IDMStoreException {
+ Preconditions.checkNotNull(user);
+ Preconditions.checkNotNull(user.getUserid());
+ User existing = readUser(user.getUserid());
+ UserBuilder b = new UserBuilder();
+ b.setName(existing.getName());
+ b.setDomainid(existing.getDomainid());
+ b.setDescription(getString(user.getDescription(), existing.getDescription()));
+ b.setEmail(getString(user.getEmail(), existing.getEmail()));
+ b.setEnabled(getBoolean(user.isEnabled(), existing.isEnabled()));
+ b.setPassword(getString(user.getPassword(), existing.getPassword()));
+ b.setSalt(getString(user.getSalt(), existing.getSalt()));
+ return writeUser(b.build());
+ }
+
+ //Grant methods
+ public Grant writeGrant(Grant grant) throws IDMStoreException {
+ Preconditions.checkNotNull(grant);
+ Preconditions.checkNotNull(grant.getDomainid());
+ Preconditions.checkNotNull(grant.getUserid());
+ Preconditions.checkNotNull(grant.getRoleid());
+ Preconditions.checkNotNull(readDomain(grant.getDomainid()));
+ Preconditions.checkNotNull(readUser(grant.getUserid()));
+ Preconditions.checkNotNull(readRole(grant.getRoleid()));
+ GrantBuilder b = new GrantBuilder();
+ b.setDomainid(grant.getDomainid());
+ b.setRoleid(grant.getRoleid());
+ b.setUserid(grant.getUserid());
+ b.setGrantid(IDMStoreUtil.createGrantid(grant.getUserid(), grant.getDomainid(), grant.getRoleid()));
+ b.setKey(new GrantKey(b.getGrantid()));
+ grant = b.build();
+ InstanceIdentifier<Grant> ID = InstanceIdentifier.create(Authentication.class).child(Grant.class,new GrantKey(grant.getGrantid()));
+ WriteTransaction wrt = dataBroker.newWriteOnlyTransaction();
+ wrt.put(LogicalDatastoreType.CONFIGURATION, ID, grant,true);
+ CheckedFuture<Void, TransactionCommitFailedException> submit = wrt.submit();
+ if(!waitForSubmit(submit)){
+ return grant;
+ }else{
+ return null;
+ }
+ }
+
+ public Grant readGrant(String grantid){
+ Preconditions.checkNotNull(grantid);
+ InstanceIdentifier<Grant> ID = InstanceIdentifier.create(Authentication.class).child(Grant.class,new GrantKey(grantid));
+ ReadOnlyTransaction rot = dataBroker.newReadOnlyTransaction();
+ CheckedFuture<Optional<Grant>, ReadFailedException> read = rot.read(LogicalDatastoreType.CONFIGURATION, ID);
+ if(read==null){
+ LOGGER.error("Failed to read grant from data store");
+ return null;
+ }
+ Optional<Grant> optional = null;
+ try {
+ optional = read.get();
+ } catch (InterruptedException | ExecutionException e1) {
+ LOGGER.error("Failed to read domain from data store",e1);
+ return null;
+ }
+
+ if(optional==null)
+ return null;
+
+ if(!optional.isPresent())
+ return null;
+
+ return optional.get();
+ }
+
+ public Grant deleteGrant(String grantid){
+ Preconditions.checkNotNull(grantid);
+ Grant grant = readGrant(grantid);
+ if(grant==null){
+ LOGGER.error("Failed to delete grant from data store, unknown grant");
+ return null;
+ }
+ InstanceIdentifier<Grant> ID = InstanceIdentifier.create(Authentication.class).child(Grant.class,new GrantKey(grantid));
+ WriteTransaction wrt = dataBroker.newWriteOnlyTransaction();
+ wrt.delete(LogicalDatastoreType.CONFIGURATION, ID);
+ wrt.submit();
+ return grant;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.aaa.authn.mdsal.store;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.User;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.DomainBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.GrantBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.RoleBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.UserBuilder;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+/**
+ *
+ * @author saichler@gmail.com
+ *
+ * This class is a codec to convert between MDSAL objects and IDM model objects. It is doing so via reflection when it assumes that the MDSAL
+ * Object and the IDM model object has the same method names.
+ */
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+public abstract class IDMObject2MDSAL {
+ private static final Logger LOGGER = LoggerFactory.getLogger(IDMObject2MDSAL.class);
+ //this is a Map mapping between the class type of the IDM Model object to a structure containing the corresponding setters and getter methods
+ //in MDSAL object
+ private static Map<Class<?>,ConvertionMethods> typesMethods = new HashMap<Class<?>,ConvertionMethods>();
+ //This method generically via reflection receive a MDSAL object and the corresponding IDM model object class type and
+ //creates an IDM model element from the MDSAL element
+ private static Object fromMDSALObject(Object mdsalObject,Class<?> type) throws Exception{
+ if(mdsalObject==null)
+ return null;
+ Object result = type.newInstance();
+ ConvertionMethods cm = typesMethods.get(type);
+ if(cm==null){
+ cm = new ConvertionMethods();
+ typesMethods.put(type, cm);
+ Method methods[] = type.getMethods();
+ for(Method m:methods){
+ if(m.getName().startsWith("set")){
+ cm.setMethods.add(m);
+ Method gm = null;
+ if(m.getParameterTypes()[0].equals(Boolean.class) || m.getParameterTypes()[0].equals(boolean.class))
+ gm = ((DataObject)mdsalObject).getImplementedInterface().getMethod("is"+m.getName().substring(3), (Class[])null);
+ else{
+ try{
+ gm = ((DataObject)mdsalObject).getImplementedInterface().getMethod("get"+m.getName().substring(3), (Class[])null);
+ }catch(Exception err){
+ err.printStackTrace();
+ }
+ }
+ cm.getMethods.put(m.getName(), gm);
+ }
+ }
+ }
+ for(Method m:cm.setMethods){
+ try{
+ m.invoke(result, new Object[]{cm.getMethods.get(m.getName()).invoke(mdsalObject, (Object[])null)});
+ }catch(Exception err){
+ err.printStackTrace();
+ }
+ }
+ return result;
+ }
+ //This method generically use reflection to receive an IDM model object and the corresponsing MDSAL object and creates
+ //a MDSAL object out of the IDM model object
+ private static Object toMDSALObject(Object object,Class<?> mdSalBuilderType) throws Exception{
+ if(object==null)
+ return null;
+ Object result = mdSalBuilderType.newInstance();
+ ConvertionMethods cm = typesMethods.get(mdSalBuilderType);
+ if(cm==null){
+ cm = new ConvertionMethods();
+ typesMethods.put(mdSalBuilderType, cm);
+ Method methods[] = mdSalBuilderType.getMethods();
+ for(Method m:methods){
+ if(m.getName().startsWith("set")){
+ try{
+ Method gm = null;
+ if(m.getParameterTypes()[0].equals(Boolean.class) || m.getParameterTypes()[0].equals(boolean.class))
+ gm = object.getClass().getMethod("is"+m.getName().substring(3), (Class[])null);
+ else
+ gm = object.getClass().getMethod("get"+m.getName().substring(3), (Class[])null);
+ cm.getMethods.put(m.getName(), gm);
+ cm.setMethods.add(m);
+ }catch(NoSuchMethodException err){}
+ }
+ }
+ cm.builderMethod = mdSalBuilderType.getMethod("build",(Class[])null);
+ }
+ for(Method m:cm.setMethods){
+ m.invoke(result, new Object[]{cm.getMethods.get(m.getName()).invoke(object, (Object[])null)});
+ }
+
+ return cm.builderMethod.invoke(result, (Object[])null);
+ }
+
+ // A struccture class to hold the getters & setters of each type to speed things up
+ private static class ConvertionMethods {
+ private List<Method> setMethods = new ArrayList<Method>();
+ private Map<String,Method> getMethods = new HashMap<String,Method>();
+ private Method builderMethod = null;
+ }
+
+ //Convert Domain
+ public static org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Domain toMDSALDomain(Domain domain){
+ try{
+ return (org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Domain)toMDSALObject(domain, DomainBuilder.class);
+ }catch(Exception err){
+ err.printStackTrace();
+ return null;
+ }
+ }
+
+ public static Domain toIDMDomain(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Domain domain){
+ try{
+ return (Domain)fromMDSALObject(domain, Domain.class);
+ }catch(Exception err){
+ err.printStackTrace();
+ return null;
+ }
+ }
+ //Convert Role
+ public static org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Role toMDSALRole(Role role){
+ try{
+ return (org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Role)toMDSALObject(role, RoleBuilder.class);
+ }catch(Exception err){
+ err.printStackTrace();
+ return null;
+ }
+ }
+
+ public static Role toIDMRole(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Role role){
+ try{
+ return (Role)fromMDSALObject(role, Role.class);
+ }catch(Exception err){
+ err.printStackTrace();
+ return null;
+ }
+ }
+ //Convert User
+ public static org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User toMDSALUser(User user){
+ try{
+ return (org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User)toMDSALObject(user, UserBuilder.class);
+ }catch(Exception err){
+ err.printStackTrace();
+ return null;
+ }
+ }
+
+ public static User toIDMUser(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User user){
+ try{
+ return (User)fromMDSALObject(user, User.class);
+ }catch(Exception err){
+ err.printStackTrace();
+ return null;
+ }
+ }
+ //Convert Grant
+ public static org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant toMDSALGrant(Grant grant){
+ try{
+ return (org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant)toMDSALObject(grant, GrantBuilder.class);
+ }catch(Exception err){
+ err.printStackTrace();
+ return null;
+ }
+ }
+
+ public static Grant toIDMGrant(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant grant){
+ try{
+ return (Grant)fromMDSALObject(grant, Grant.class);
+ }catch(Exception err){
+ err.printStackTrace();
+ return null;
+ }
+ }
+}
--- /dev/null
+package org.opendaylight.aaa.authn.mdsal.store;
+
+import java.util.List;
+
+import org.opendaylight.aaa.api.IDMStoreException;
+import org.opendaylight.aaa.api.IDMStoreUtil;
+import org.opendaylight.aaa.api.IIDMStore;
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Domains;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Grants;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.Roles;
+import org.opendaylight.aaa.api.model.User;
+import org.opendaylight.aaa.api.model.Users;
+
+public class IDMStore implements IIDMStore{
+ private final IDMMDSALStore mdsalStore;
+
+ public IDMStore(IDMMDSALStore mdsalStore){
+ this.mdsalStore = mdsalStore;
+ }
+
+ @Override
+ public Domain writeDomain(Domain domain) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMDomain(mdsalStore.writeDomain(IDMObject2MDSAL.toMDSALDomain(domain)));
+ }
+
+ @Override
+ public Domain readDomain(String domainid) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMDomain(mdsalStore.readDomain(domainid));
+ }
+
+ @Override
+ public Domain deleteDomain(String domainid) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMDomain(mdsalStore.deleteDomain(domainid));
+ }
+
+ @Override
+ public Domain updateDomain(Domain domain) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMDomain(mdsalStore.updateDomain(IDMObject2MDSAL.toMDSALDomain(domain)));
+ }
+
+ @Override
+ public Domains getDomains() throws IDMStoreException {
+ Domains domains = new Domains();
+ List<org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Domain> mdSalDomains = mdsalStore.getAllDomains();
+ for(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Domain d:mdSalDomains){
+ domains.getDomains().add(IDMObject2MDSAL.toIDMDomain(d));
+ }
+ return domains;
+ }
+
+ @Override
+ public Role writeRole(Role role) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMRole(mdsalStore.writeRole(IDMObject2MDSAL.toMDSALRole(role)));
+ }
+
+ @Override
+ public Role readRole(String roleid) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMRole(mdsalStore.readRole(roleid));
+ }
+
+ @Override
+ public Role deleteRole(String roleid) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMRole(mdsalStore.deleteRole(roleid));
+ }
+
+ @Override
+ public Role updateRole(Role role) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMRole(mdsalStore.writeRole(IDMObject2MDSAL.toMDSALRole(role)));
+ }
+
+ @Override
+ public User writeUser(User user) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMUser(mdsalStore.writeUser(IDMObject2MDSAL.toMDSALUser(user)));
+ }
+
+ @Override
+ public User readUser(String userid) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMUser(mdsalStore.readUser(userid));
+ }
+
+ @Override
+ public User deleteUser(String userid) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMUser(mdsalStore.deleteUser(userid));
+ }
+
+ @Override
+ public User updateUser(User user) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMUser(mdsalStore.writeUser(IDMObject2MDSAL.toMDSALUser(user)));
+ }
+
+ @Override
+ public Grant writeGrant(Grant grant) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMGrant(mdsalStore.writeGrant(IDMObject2MDSAL.toMDSALGrant(grant)));
+ }
+
+ @Override
+ public Grant readGrant(String grantid) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMGrant(mdsalStore.readGrant(grantid));
+ }
+
+ @Override
+ public Grant deleteGrant(String grantid) throws IDMStoreException {
+ return IDMObject2MDSAL.toIDMGrant(mdsalStore.readGrant(grantid));
+ }
+
+ @Override
+ public Roles getRoles() throws IDMStoreException {
+ Roles roles = new Roles();
+ List<org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Role> mdSalRoles = mdsalStore.getAllRoles();
+ for(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Role r:mdSalRoles){
+ roles.getRoles().add(IDMObject2MDSAL.toIDMRole(r));
+ }
+ return roles;
+ }
+
+ @Override
+ public Users getUsers() throws IDMStoreException {
+ Users users = new Users();
+ List<org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User> mdSalUsers = mdsalStore.getAllUsers();
+ for(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User u:mdSalUsers){
+ users.getUsers().add(IDMObject2MDSAL.toIDMUser(u));
+ }
+ return users;
+ }
+
+ @Override
+ public Users getUsers(String username, String domain) throws IDMStoreException {
+ Users users = new Users();
+ List<org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User> mdSalUsers = mdsalStore.getAllUsers();
+ for(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User u:mdSalUsers){
+ if(u.getDomainid().equals(domain) && u.getName().equals(username)){
+ users.getUsers().add(IDMObject2MDSAL.toIDMUser(u));
+ }
+ }
+ return users;
+ }
+
+ @Override
+ public Grants getGrants(String domainid, String userid) throws IDMStoreException {
+ Grants grants = new Grants();
+ List<org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant> mdSalGrants = mdsalStore.getAllGrants();
+ for(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant g:mdSalGrants){
+ grants.getGrants().add(IDMObject2MDSAL.toIDMGrant(g));
+ }
+ return grants;
+ }
+
+ @Override
+ public Grants getGrants(String userid) throws IDMStoreException {
+ Grants grants = new Grants();
+ List<org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant> mdSalGrants = mdsalStore.getAllGrants();
+ for(org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant g:mdSalGrants){
+ if(g.getUserid().equals(userid)){
+ grants.getGrants().add(IDMObject2MDSAL.toIDMGrant(g));
+ }
+ }
+ return grants;
+ }
+
+ @Override
+ public Grant readGrant(String domainid, String userid, String roleid) throws IDMStoreException {
+ return readGrant(IDMStoreUtil.createGrantid(userid, domainid, roleid));
+ }
+}
package org.opendaylight.yang.gen.v1.config.aaa.authn.mdsal.store.rev141031;
+import org.opendaylight.aaa.api.IIDMStore;
import org.opendaylight.aaa.api.TokenStore;
import org.opendaylight.aaa.authn.mdsal.store.AuthNStore;
+import org.opendaylight.aaa.authn.mdsal.store.IDMMDSALStore;
+import org.opendaylight.aaa.authn.mdsal.store.IDMStore;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
DataBroker dataBrokerService = getDataBrokerDependency();
final AuthNStore authNStore = new AuthNStore(dataBrokerService, getPassword());
+ final IDMMDSALStore mdsalStore = new IDMMDSALStore(dataBrokerService);
+ final IDMStore idmStore = new IDMStore(mdsalStore);
authNStore.setTimeToLive(getTimeToLive());
//Register the MD-SAL Token store with OSGI
final ServiceRegistration<?> serviceRegistration = bundleContext.registerService(TokenStore.class.getName(), authNStore, null);
-
+ final ServiceRegistration<?> idmServiceRegistration = bundleContext.registerService(IIDMStore.class.getName(), idmStore, null);
final class AutoCloseableStore implements AutoCloseable {
@Override
public void close() throws Exception {
serviceRegistration.unregister();
+ idmServiceRegistration.unregister();
authNStore.close();
}
}
--- /dev/null
+package org.opendaylight.aaa.authn.mdsal.store;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class DataBrokerReadMocker implements InvocationHandler {
+ private Map<Method, List<StubContainer>> stubs = new HashMap<Method, List<StubContainer>>();
+ private Class<?> mokingClass = null;
+
+ @Override
+ public Object invoke(Object arg0, Method arg1, Object[] arg2)
+ throws Throwable {
+ List<StubContainer> stList = stubs.get(arg1);
+ if (stList != null) {
+ for (StubContainer sc : stList) {
+ if (sc.fitGeneric(arg2)) {
+ return sc.returnObject;
+ }
+ }
+ }
+ return null;
+ }
+
+ public DataBrokerReadMocker(Class<?> cls) {
+ this.mokingClass = cls;
+ }
+
+ public static Object addMock(Class<?> cls) {
+ return Proxy.newProxyInstance(cls.getClassLoader(),
+ new Class[] { cls }, new DataBrokerReadMocker(cls));
+ }
+
+ public static DataBrokerReadMocker getMocker(Object o) {
+ return (DataBrokerReadMocker) Proxy.getInvocationHandler(o);
+ }
+
+ public static Method findMethod(Class<?> cls, String name, Object args[]) {
+ Method methods[] = cls.getMethods();
+ for (Method m : methods) {
+ if (m.getName().equals(name)) {
+ if ((m.getParameterTypes() == null || m.getParameterTypes().length == 0)
+ && args == null) {
+ return m;
+ }
+ boolean match = true;
+ for (int i = 0; i < m.getParameterTypes().length; i++) {
+ if (!m.getParameterTypes()[i].isAssignableFrom(args[i]
+ .getClass())) {
+ match = false;
+ }
+ }
+ if (match)
+ return m;
+ }
+ }
+ return null;
+ }
+
+ public void addWhen(String methodName, Object[] args, Object returnThis)
+ throws NoSuchMethodException, SecurityException {
+ Method m = findMethod(this.mokingClass, methodName, args);
+ if (m == null)
+ throw new IllegalArgumentException("Unable to find method");
+ StubContainer sc = new StubContainer(args, returnThis);
+ List<StubContainer> lst = stubs.get(m);
+ if (lst == null) {
+ lst = new ArrayList<>();
+ }
+ lst.add(sc);
+ stubs.put(m, lst);
+ }
+
+ private class StubContainer {
+ private Class<?>[] parameters = null;
+ private Class<?>[] generics = null;
+ private Object args[] = null;
+ private Object returnObject;
+
+ public StubContainer(Object[] _args, Object ret) {
+ this.args = _args;
+ this.returnObject = ret;
+ }
+
+ public boolean fitGeneric(Object _args[]) {
+ if (args == null && _args != null)
+ return false;
+ if (args != null && _args == null)
+ return false;
+ if (args == null && _args == null)
+ return true;
+ if (args.length != _args.length)
+ return false;
+ for (int i = 0; i < args.length; i++) {
+ if (!args[i].equals(_args[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.opendaylight.aaa.authn.mdsal.store;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.aaa.api.IDMStoreUtil;
+import org.opendaylight.aaa.api.SHA256Calculator;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Domain;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Role;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User;
+public class IDMStoreTest {
+
+ @Test
+ public void testWriteDomain () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoFordomain();
+ Domain domain = testedObject.writeDomain(util.domain);
+ Assert.assertNotNull(domain);
+ Assert.assertEquals(domain.getDomainid(), util.domain.getName());
+ }
+
+ @Test
+ public void testReadDomain () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoFordomain();
+ Domain domain = testedObject.readDomain(util.domain.getDomainid());
+ Assert.assertNotNull(domain);
+ Assert.assertEquals(domain, util.domain);
+ }
+
+ @Test
+ public void testDeleteDomain () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoFordomain();
+ Domain domain = testedObject.deleteDomain(util.domain.getDomainid());
+ Assert.assertEquals(domain, util.domain);
+ }
+
+ @Test
+ public void testUpdateDomain () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoFordomain();
+ Domain domain = testedObject.updateDomain(util.domain);
+ Assert.assertEquals(domain, util.domain);
+ }
+
+ @Test
+ public void testWriteRole () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForrole();
+ util.addMokitoFordomain();
+ Role role = testedObject.writeRole(util.role);
+ Assert.assertNotNull(role);
+ Assert.assertEquals(role.getRoleid(), IDMStoreUtil.createRoleid(role.getName(),role.getDomainid()));
+ }
+
+ @Test
+ public void testReadRole () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForrole();
+ Role role = testedObject.readRole(util.role.getRoleid());
+ Assert.assertNotNull(role);
+ Assert.assertEquals(role, util.role);
+ }
+
+ @Test
+ public void testDeleteRole () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForrole();
+ Role role = testedObject.deleteRole(util.role.getRoleid());
+ Assert.assertNotNull(role);
+ Assert.assertEquals(role, util.role);
+ }
+
+ @Test
+ public void testUpdateRole () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForrole();
+ Role role = testedObject.updateRole(util.role);
+ Assert.assertNotNull(role);
+ Assert.assertEquals(role, util.role);
+ }
+
+ @Test
+ public void testWriteUser () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForuser();
+ User user = testedObject.writeUser(util.user);
+ Assert.assertNotNull(user);
+ Assert.assertEquals(user.getUserid(), IDMStoreUtil.createUserid(user.getName(),util.user.getDomainid()));
+ }
+
+ @Test
+ public void testReadUser () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForuser();
+ User user = testedObject.readUser(util.user.getUserid());
+ Assert.assertNotNull(user);
+ Assert.assertEquals(user, util.user);
+ }
+
+ @Test
+ public void testDeleteUser () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForuser();
+ User user = testedObject.deleteUser(util.user.getUserid());
+ Assert.assertNotNull(user);
+ Assert.assertEquals(user, util.user);
+ }
+
+ @Test
+ public void testUpdateUser () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForuser();
+ User user = testedObject.updateUser(util.user);
+ Assert.assertNotNull(user);
+ Assert.assertEquals(user.getPassword(), SHA256Calculator.getSHA256(util.user.getPassword(),util.user.getSalt()));
+ }
+
+ @Test
+ public void testWriteGrant () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoFordomain();
+ util.addMokitoForrole();
+ util.addMokitoForuser();
+ util.addMokitoForgrant();
+ Grant grant = testedObject.writeGrant(util.grant);
+ Assert.assertNotNull(grant);
+ }
+
+ @Test
+ public void testReadGrant () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForgrant();
+ Grant grant = testedObject.readGrant(util.grant.getGrantid());
+ Assert.assertNotNull(grant);
+ Assert.assertEquals(grant, util.grant);
+ }
+
+ @Test
+ public void testDeleteGrant () throws Exception{
+ IDMStoreTestUtil util = new IDMStoreTestUtil();
+ IDMMDSALStore testedObject = new IDMMDSALStore(util.dataBroker);
+ util.addMokitoForgrant();
+ Grant grant = testedObject.deleteGrant(util.grant.getGrantid());
+ Assert.assertNotNull(grant);
+ Assert.assertEquals(grant, util.grant);
+ }
+}
--- /dev/null
+package org.opendaylight.aaa.authn.mdsal.store;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.concurrent.ExecutionException;
+
+import org.opendaylight.aaa.api.IDMStoreUtil;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.Authentication;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Domain;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.DomainBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.DomainKey;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.GrantBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.GrantKey;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Role;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.RoleBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.RoleKey;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.UserBuilder;
+import org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.UserKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+public class IDMStoreTestUtil {
+ /* DataBroker mocked with Mokito */
+ protected static DataBroker dataBroker = mock(DataBroker.class);
+ protected static WriteTransaction wrt = mock(WriteTransaction.class);
+ protected static ReadOnlyTransaction rot = null;
+
+ static {
+ rot = (ReadOnlyTransaction)DataBrokerReadMocker.addMock(ReadOnlyTransaction.class);
+ when(dataBroker.newReadOnlyTransaction()).thenReturn(rot);
+ when(dataBroker.newWriteOnlyTransaction()).thenReturn(wrt);
+ }
+
+ /* Domain Data Object Instance */
+ public Domain domain = createdomain();
+ /* Domain create Method */
+ public Domain createdomain(){
+ /* Start of Domain builder */
+ DomainBuilder domainbuilder = new DomainBuilder();
+ domainbuilder.setName("SETNAME");
+ domainbuilder.setDomainid("SETNAME");
+ domainbuilder.setKey(new DomainKey("SETNAME"));
+ domainbuilder.setDescription("SETDESCRIPTION");
+ domainbuilder.setEnabled(true);
+ /* End of Domain builder */
+ return domainbuilder.build();
+ }
+ /* Role Data Object Instance */
+ public Role role = createrole();
+ /* Role create Method */
+ public Role createrole(){
+ /* Start of Role builder */
+ RoleBuilder rolebuilder = new RoleBuilder();
+ rolebuilder.setRoleid("SETNAME@SETNAME");
+ rolebuilder.setName("SETNAME");
+ rolebuilder.setKey(new RoleKey(rolebuilder.getRoleid()));
+ rolebuilder.setDomainid(createdomain().getDomainid());
+ rolebuilder.setDescription("SETDESCRIPTION");
+ /* End of Role builder */
+ return rolebuilder.build();
+ }
+ /* User Data Object Instance */
+ public User user = createuser();
+ /* User create Method */
+ public User createuser(){
+ /* Start of User builder */
+ UserBuilder userbuilder = new UserBuilder();
+ userbuilder.setUserid("SETNAME@SETNAME");
+ userbuilder.setName("SETNAME");
+ userbuilder.setKey(new UserKey(userbuilder.getUserid()));
+ userbuilder.setDomainid(createdomain().getDomainid());
+ userbuilder.setEmail("SETEMAIL");
+ userbuilder.setPassword("SETPASSWORD");
+ userbuilder.setSalt("SETSALT");
+ userbuilder.setEnabled(true);
+ userbuilder.setDescription("SETDESCRIPTION");
+ /* End of User builder */
+ return userbuilder.build();
+ }
+ /* Grant Data Object Instance */
+ public Grant grant = creategrant();
+ /* Grant create Method */
+ public Grant creategrant(){
+ /* Start of Grant builder */
+ GrantBuilder grantbuilder = new GrantBuilder();
+ grantbuilder.setDomainid(createdomain().getDomainid());
+ grantbuilder.setRoleid(createrole().getRoleid());
+ grantbuilder.setUserid(createuser().getUserid());
+ grantbuilder.setGrantid(IDMStoreUtil.createGrantid(grantbuilder.getUserid(), grantbuilder.getDomainid(), grantbuilder.getRoleid()));
+ grantbuilder.setKey(new GrantKey(grantbuilder.getGrantid()));
+ /* End of Grant builder */
+ return grantbuilder.build();
+ }
+ /* InstanceIdentifier for Grant instance grant */
+ public InstanceIdentifier<Grant> grantID = InstanceIdentifier
+ .create(Authentication.class)
+ .child(Grant.class, creategrant().getKey());
+
+ /* Mokito DataBroker method for grant Data Object */
+ public void addMokitoForgrant() {
+ CheckedFuture<Optional<Grant>, ReadFailedException> read = mock(CheckedFuture.class);
+ try{
+ DataBrokerReadMocker.getMocker(rot).addWhen("read", new Object[]{LogicalDatastoreType.CONFIGURATION, grantID}, read);
+ }catch(Exception err){
+ err.printStackTrace();
+ }
+ Optional<Grant> optional = mock(Optional.class);
+ try {when(read.get()).thenReturn(optional);} catch (InterruptedException | ExecutionException e) {}
+ when(optional.get()).thenReturn(grant);
+ when(optional.isPresent()).thenReturn(true);
+ }
+ /* InstanceIdentifier for Domain instance domain */
+ public InstanceIdentifier<Domain> domainID = InstanceIdentifier
+ .create(Authentication.class)
+ .child(Domain.class, new DomainKey(new String("SETNAME")));
+
+ /* Mokito DataBroker method for domain Data Object */
+ public void addMokitoFordomain() {
+ CheckedFuture<Optional<Domain>, ReadFailedException> read = mock(CheckedFuture.class);
+ try{
+ DataBrokerReadMocker.getMocker(rot).addWhen("read", new Object[]{LogicalDatastoreType.CONFIGURATION, domainID}, read);
+ }catch(Exception err){
+ err.printStackTrace();
+ }
+ Optional<Domain> optional = mock(Optional.class);
+ try {when(read.get()).thenReturn(optional);} catch (InterruptedException | ExecutionException e) {}
+ when(optional.get()).thenReturn(domain);
+ when(optional.isPresent()).thenReturn(true);
+ }
+ /* InstanceIdentifier for Role instance role */
+ public InstanceIdentifier<Role> roleID = InstanceIdentifier
+ .create(Authentication.class)
+ .child(Role.class, createrole().getKey());
+
+ /* Mokito DataBroker method for role Data Object */
+ public void addMokitoForrole() {
+ CheckedFuture<Optional<Role>, ReadFailedException> read = mock(CheckedFuture.class);
+ try{
+ DataBrokerReadMocker.getMocker(rot).addWhen("read", new Object[]{LogicalDatastoreType.CONFIGURATION, roleID}, read);
+ }catch(Exception err){
+ err.printStackTrace();
+ }
+ Optional<Role> optional = mock(Optional.class);
+ try {when(read.get()).thenReturn(optional);} catch (InterruptedException | ExecutionException e) {}
+ when(optional.get()).thenReturn(role);
+ when(optional.isPresent()).thenReturn(true);
+ }
+ /* InstanceIdentifier for User instance user */
+ public InstanceIdentifier<User> userID = InstanceIdentifier
+ .create(Authentication.class)
+ .child(User.class, createuser().getKey());
+
+ /* Mokito DataBroker method for user Data Object */
+ public void addMokitoForuser() {
+ CheckedFuture<Optional<User>, ReadFailedException> read = mock(CheckedFuture.class);
+ try{
+ DataBrokerReadMocker.getMocker(rot).addWhen("read", new Object[]{LogicalDatastoreType.CONFIGURATION, userID}, read);
+ }catch(Exception err){
+ err.printStackTrace();
+ }
+ Optional<User> optional = mock(Optional.class);
+ try {when(read.get()).thenReturn(optional);} catch (InterruptedException | ExecutionException e) {}
+ when(optional.get()).thenReturn(user);
+ when(optional.isPresent()).thenReturn(true);
+ }
+}
--- /dev/null
+package org.opendaylight.aaa.authn.mdsal.store;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.User;
+
+public class MDSALConvertTest {
+ @Test
+ public void testConvertDomain(){
+ Domain d = new Domain();
+ d.setDescription("hello");
+ d.setDomainid("hello");
+ d.setEnabled(true);
+ d.setName("Hello");
+ org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Domain mdsalDomain = IDMObject2MDSAL.toMDSALDomain(d);
+ Assert.assertNotNull(mdsalDomain);
+ Domain d2 = IDMObject2MDSAL.toIDMDomain(mdsalDomain);
+ Assert.assertNotNull(d2);
+ Assert.assertEquals(d, d2);
+ }
+
+ @Test
+ public void testConvertRole(){
+ Role r = new Role();
+ r.setDescription("hello");
+ r.setRoleid("Hello@hello");
+ r.setName("Hello");
+ r.setDomainid("hello");
+ org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Role mdsalRole = IDMObject2MDSAL.toMDSALRole(r);
+ Assert.assertNotNull(mdsalRole);
+ Role r2 = IDMObject2MDSAL.toIDMRole(mdsalRole);
+ Assert.assertNotNull(r2);
+ Assert.assertEquals(r, r2);
+ }
+
+ @Test
+ public void testConvertUser(){
+ User u = new User();
+ u.setDescription("hello");
+ u.setDomainid("hello");
+ u.setUserid("hello@hello");
+ u.setName("Hello");
+ u.setEmail("email");
+ u.setEnabled(true);
+ u.setPassword("pass");
+ u.setSalt("salt");
+ org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.User mdsalUser = IDMObject2MDSAL.toMDSALUser(u);
+ Assert.assertNotNull(mdsalUser);
+ User u2 = IDMObject2MDSAL.toIDMUser(mdsalUser);
+ Assert.assertNotNull(u2);
+ Assert.assertEquals(u, u2);
+ }
+
+ @Test
+ public void testConvertGrant(){
+ Grant g = new Grant();
+ g.setDomainid("hello");
+ g.setUserid("hello@hello");
+ g.setRoleid("hello@hello");
+ g.setGrantid("hello@hello@Hello");
+ org.opendaylight.yang.gen.v1.urn.aaa.yang.authn.claims.rev141029.authentication.Grant mdsalGrant = IDMObject2MDSAL.toMDSALGrant(g);
+ Assert.assertNotNull(mdsalGrant);
+ Grant g2 = IDMObject2MDSAL.toIDMGrant(mdsalGrant);
+ Assert.assertNotNull(g2);
+ Assert.assertEquals(g, g2);
+ }
+}
--- /dev/null
+/target/
+/target/
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.aaa</groupId>
+ <artifactId>aaa-parent</artifactId>
+ <version>0.3.0-SNAPSHOT</version>
+ <relativePath>../parent</relativePath>
+ </parent>
+
+ <artifactId>aaa-h2-store</artifactId>
+ <version>0.3.0-SNAPSHOT</version>
+ <packaging>bundle</packaging>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.aaa</groupId>
+ <artifactId>aaa-authn-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.aaa</groupId>
+ <artifactId>aaa-authn</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.dependencymanager</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <!-- JDBC -->
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ </dependency>
+ <!-- Testing Dependencies -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Import-Package>com.google.*,org.opendaylight.aaa.api.*,org.apache.felix.*,org.slf4j.*</Import-Package>
+ <Export-Package>org.opendaylight.aaa.h2.*</Export-Package>
+ <Private-Package>org.h2.*</Private-Package>
+ <Embed-Dependency>h2</Embed-Dependency>
+ <Bundle-Activator>org.opendaylight.aaa.h2.Activator</Bundle-Activator>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
--- /dev/null
+package org.opendaylight.aaa.h2;
+
+import org.apache.felix.dm.DependencyActivatorBase;
+import org.apache.felix.dm.DependencyManager;
+import org.opendaylight.aaa.api.IIDMStore;
+import org.opendaylight.aaa.h2.persistence.H2Store;
+import org.osgi.framework.BundleContext;
+
+public class Activator extends DependencyActivatorBase {
+
+ @Override
+ public void init(BundleContext context, DependencyManager manager) throws Exception {
+ manager.add(createComponent().setInterface(
+ new String[] { IIDMStore.class.getName()}, null).setImplementation(new H2Store()));
+ }
+
+ @Override
+ public void destroy(BundleContext context, DependencyManager manager)
+ throws Exception {
+ }
+}
+
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.config;
+package org.opendaylight.aaa.h2.config;
/**
*
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
/**
*
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.aaa.idm.IdmLightApplication;
-import org.opendaylight.aaa.idm.model.Domain;
-import org.opendaylight.aaa.idm.model.Domains;
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Domains;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
protected final static String SQL_NAME = "name";
protected final static String SQL_DESCR = "description";
protected final static String SQL_ENABLED = "enabled";
-
+
+ protected DomainStore(){
+ }
+
protected Connection getDBConnect() throws StoreException {
- dbConnection = IdmLightApplication.getConnection(dbConnection);
+ dbConnection = H2Store.getConnection(dbConnection);
return dbConnection;
}
return domain;
}
- public Domains getDomains() throws StoreException {
+ protected Domains getDomains() throws StoreException {
Domains domains = new Domains();
List<Domain> domainList = new ArrayList<Domain>();
Connection conn = dbConnect();
return domains;
}
- public Domains getDomains(String domainName) throws StoreException {
+ protected Domains getDomains(String domainName) throws StoreException {
debug("getDomains for:" + domainName);
Domains domains = new Domains();
List<Domain> domainList = new ArrayList<Domain>();
}
- public Domain getDomain(String id) throws StoreException {
+ protected Domain getDomain(String id) throws StoreException {
Connection conn = dbConnect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM DOMAINS WHERE domainid = ? ");
}
}
- public Domain createDomain(Domain domain) throws StoreException {
+ protected Domain createDomain(Domain domain) throws StoreException {
Preconditions.checkNotNull(domain);
Preconditions.checkNotNull(domain.getName());
- Preconditions.checkNotNull(domain.getEnabled());
+ Preconditions.checkNotNull(domain.isEnabled());
Connection conn = dbConnect();
try {
String query = "insert into DOMAINS (domainid,name,description,enabled) values(?, ?, ?, ?)";
statement.setString(1,domain.getName());
statement.setString(2,domain.getName());
statement.setString(3,domain.getDescription());
- statement.setInt(4,domain.getEnabled()?1:0);
+ statement.setInt(4,domain.isEnabled()?1:0);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new StoreException("Creating domain failed, no rows affected.");
}
}
- public Domain putDomain(Domain domain) throws StoreException {
+ protected Domain putDomain(Domain domain) throws StoreException {
Domain savedDomain = this.getDomain(domain.getDomainid());
if (savedDomain==null) {
return null;
if (domain.getName()!=null) {
savedDomain.setName(domain.getName());
}
- if (domain.getEnabled()!=null) {
- savedDomain.setEnabled(domain.getEnabled());
+ if (domain.isEnabled()!=null) {
+ savedDomain.setEnabled(domain.isEnabled());
}
Connection conn = dbConnect();
String query = "UPDATE DOMAINS SET description = ?, enabled = ? WHERE domainid = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, savedDomain.getDescription());
- statement.setInt(2, savedDomain.getEnabled()?1:0);
+ statement.setInt(2, savedDomain.isEnabled()?1:0);
statement.setString(3,savedDomain.getDomainid());
statement.executeUpdate();
statement.close();
return savedDomain;
}
- public Domain deleteDomain(Domain domain) throws StoreException {
- Domain deletedDomain = this.getDomain(domain.getDomainid());
+ protected Domain deleteDomain(String domainid) throws StoreException {
+ Domain deletedDomain = this.getDomain(domainid);
if (deletedDomain==null) {
return null;
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
/**
*
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.aaa.idm.IdmLightApplication;
-import org.opendaylight.aaa.idm.model.Grant;
-import org.opendaylight.aaa.idm.model.Grants;
+import org.opendaylight.aaa.api.IDMStoreUtil;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Grants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
protected final static String SQL_USERID = "userid";
protected final static String SQL_ROLEID = "roleid";
+ protected GrantStore(){
+ }
+
protected Connection getDBConnect() throws StoreException {
- dbConnection = IdmLightApplication.getConnection(dbConnection);
+ dbConnection = H2Store.getConnection(dbConnection);
return dbConnection;
}
return grant;
}
- public Grants getGrants(String did, String uid) throws StoreException {
+ protected Grants getGrants(String did, String uid) throws StoreException {
Grants grants = new Grants();
List<Grant> grantList = new ArrayList<Grant>();
Connection conn = dbConnect();
return grants;
}
- public Grants getGrants(int uid) throws StoreException {
+ protected Grants getGrants(String userid) throws StoreException {
Grants grants = new Grants();
List<Grant> grantList = new ArrayList<Grant>();
Connection conn = dbConnect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM GRANTS WHERE userid = ? ");
- pstmt.setInt(1, uid);
+ pstmt.setString(1, userid);
debug("query string: " + pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
}
- public Grant getGrant(String id) throws StoreException {
+ protected Grant getGrant(String id) throws StoreException {
Connection conn = dbConnect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM GRANTS WHERE grantid = ? ");
}
}
- public Grant getGrant(String did,String uid,String rid) throws StoreException {
+ protected Grant getGrant(String did,String uid,String rid) throws StoreException {
Connection conn = dbConnect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM GRANTS WHERE domainid = ? AND userid = ? AND roleid = ? ");
}
}
-
- public Grant createGrant(Grant grant) throws StoreException {
+ protected Grant createGrant(Grant grant) throws StoreException {
Connection conn = dbConnect();
try {
String query = "insert into grants (grantid,domainid,userid,roleid) values(?,?,?,?)";
PreparedStatement statement = conn.prepareStatement(query);
- statement.setString(1,grant.getUserid()+"@"+grant.getDomainid()+"@"+grant.getRoleid());
+ statement.setString(1,IDMStoreUtil.createGrantid(grant.getUserid(),grant.getDomainid(),grant.getRoleid()));
statement.setString(2,grant.getDomainid());
statement.setString(3,grant.getUserid());
statement.setString(4,grant.getRoleid());
if (affectedRows == 0) {
throw new StoreException("Creating grant failed, no rows affected.");
}
+ grant.setGrantid(IDMStoreUtil.createGrantid(grant.getUserid(),grant.getDomainid(),grant.getRoleid()));
return grant;
}
catch (SQLException s) {
}
}
- public Grant deleteGrant(Grant grant) throws StoreException {
- Grant savedGrant = this.getGrant(grant.getGrantid());
+ protected Grant deleteGrant(String grantid) throws StoreException {
+ Grant savedGrant = this.getGrant(grantid);
if (savedGrant==null) {
return null;
}
Connection conn = dbConnect();
try {
- String query = "DELETE FROM GRANTS WHERE grantid = ?";
- PreparedStatement statement = conn.prepareStatement(query);
- statement.setString(1, savedGrant.getGrantid());
- int deleteCount = statement.executeUpdate(query);
+ String query = "DELETE FROM GRANTS WHERE grantid = '"+grantid+"'";
+ Statement st = conn.createStatement();//PreparedStatement statement = conn.prepareStatement(query);
+ //statement.setString(1, savedGrant.getGrantid());
+ int deleteCount = st.executeUpdate(query);
debug("deleted " + deleteCount + " records");
- statement.close();
+ st.close();
return savedGrant;
}
catch (SQLException s) {
--- /dev/null
+package org.opendaylight.aaa.h2.persistence;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+
+import org.opendaylight.aaa.api.IDMStoreException;
+import org.opendaylight.aaa.api.IDMStoreUtil;
+import org.opendaylight.aaa.api.IIDMStore;
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Domains;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Grants;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.Roles;
+import org.opendaylight.aaa.api.model.User;
+import org.opendaylight.aaa.api.model.Users;
+import org.opendaylight.aaa.h2.config.IdmLightConfig;
+
+public class H2Store implements IIDMStore{
+ private static IdmLightConfig config = new IdmLightConfig();
+ private DomainStore domainStore = new DomainStore();
+ private UserStore userStore = new UserStore();
+ private RoleStore roleStore = new RoleStore();
+ private GrantStore grantStore = new GrantStore();
+
+ public H2Store() {
+ }
+
+ public static Connection getConnection(Connection existingConnection) throws StoreException {
+ Connection connection = existingConnection;
+ try {
+ if (existingConnection == null || existingConnection.isClosed()) {
+ new org.h2.Driver();
+ connection = DriverManager.getConnection(config.getDbPath(),
+ config.getDbUser(), config.getDbPwd());
+ }
+ } catch (Exception e) {
+ throw new StoreException("Cannot connect to database server " + e);
+ }
+
+ return connection;
+ }
+
+ public static IdmLightConfig getConfig(){
+ return config;
+ }
+
+ @Override
+ public Domain writeDomain(Domain domain) throws IDMStoreException {
+ try {
+ return domainStore.createDomain(domain);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Domain readDomain(String domainid) throws IDMStoreException {
+ try {
+ return domainStore.getDomain(domainid);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Domain deleteDomain(String domainid) throws IDMStoreException {
+ try {
+ return domainStore.deleteDomain(domainid);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Domain updateDomain(Domain domain) throws IDMStoreException {
+ try {
+ return domainStore.putDomain(domain);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Domains getDomains() throws IDMStoreException {
+ try {
+ return domainStore.getDomains();
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Role writeRole(Role role) throws IDMStoreException {
+ try{
+ return roleStore.createRole(role);
+ }catch(StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Role readRole(String roleid) throws IDMStoreException {
+ try{
+ return roleStore.getRole(roleid);
+ }catch(StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Role deleteRole(String roleid) throws IDMStoreException {
+ try{
+ return roleStore.deleteRole(roleid);
+ }catch(StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Role updateRole(Role role) throws IDMStoreException {
+ try{
+ return roleStore.putRole(role);
+ }catch(StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Roles getRoles() throws IDMStoreException {
+ try {
+ return roleStore.getRoles();
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public User writeUser(User user) throws IDMStoreException {
+ try {
+ return userStore.createUser(user);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public User readUser(String userid) throws IDMStoreException {
+ try {
+ return userStore.getUser(userid);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public User deleteUser(String userid) throws IDMStoreException {
+ try {
+ return userStore.deleteUser(userid);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public User updateUser(User user) throws IDMStoreException {
+ try {
+ return userStore.putUser(user);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Users getUsers(String username, String domain) throws IDMStoreException {
+ try {
+ return userStore.getUsers(username, domain);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Users getUsers() throws IDMStoreException {
+ try {
+ return userStore.getUsers();
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Grant writeGrant(Grant grant) throws IDMStoreException {
+ try {
+ return grantStore.createGrant(grant);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Grant readGrant(String grantid) throws IDMStoreException {
+ try {
+ return grantStore.getGrant(grantid);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Grant deleteGrant(String grantid) throws IDMStoreException {
+ try {
+ return grantStore.deleteGrant(grantid);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Grants getGrants(String domainid, String userid) throws IDMStoreException {
+ try {
+ return grantStore.getGrants(domainid, userid);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Grants getGrants(String userid) throws IDMStoreException {
+ try {
+ return grantStore.getGrants(userid);
+ } catch (StoreException e) {
+ throw new IDMStoreException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Grant readGrant(String domainid, String userid, String roleid) throws IDMStoreException {
+ return readGrant(IDMStoreUtil.createGrantid(userid, domainid, roleid));
+ }
+
+ public static Domain createDomain(String domainName,boolean enable) throws StoreException{
+ DomainStore ds = new DomainStore();
+ Domain d = new Domain();
+ d.setName(domainName);
+ d.setEnabled(enable);
+ return ds.createDomain(d);
+ }
+
+ public static User createUser(String name, String password, String domain, String description,String email,boolean enabled,String SALT) throws StoreException{
+ UserStore us = new UserStore();
+ User u = new User();
+ u.setName(name);
+ u.setDomainid(domain);
+ u.setDescription(description);
+ u.setEmail(email);
+ u.setEnabled(enabled);
+ u.setPassword(password);
+ u.setSalt(SALT);
+ return us.createUser(u);
+ }
+
+ public static Role createRole(String name, String domain, String description) throws StoreException{
+ RoleStore rs = new RoleStore();
+ Role r = new Role();
+ r.setDescription(description);
+ r.setName(name);
+ r.setDomainid(domain);
+ return rs.createRole(r);
+ }
+
+ public static Grant createGrant(String domain,String user,String role) throws StoreException{
+ GrantStore gs = new GrantStore();
+ Grant g = new Grant();
+ g.setDomainid(domain);
+ g.setRoleid(role);
+ g.setUserid(user);
+ return gs.createGrant(g);
+ }
+}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
/**
*
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.aaa.idm.IdmLightApplication;
-import org.opendaylight.aaa.idm.model.Role;
-import org.opendaylight.aaa.idm.model.Roles;
+import org.opendaylight.aaa.api.IDMStoreUtil;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.Roles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
protected final static String SQL_DESCR = "description";
public final static int MAX_FIELD_LEN = 128;
+ protected RoleStore (){
+ }
+
protected Connection getDBConnect() throws StoreException {
- dbConnection = IdmLightApplication.getConnection(dbConnection);
+ dbConnection = H2Store.getConnection(dbConnection);
return dbConnection;
}
Role role = new Role();
try {
role.setRoleid(rs.getString(SQL_ID));
- role.setDomainID(rs.getString(SQL_DOMAIN_ID));
+ role.setDomainid(rs.getString(SQL_DOMAIN_ID));
role.setName(rs.getString(SQL_NAME));
role.setDescription(rs.getString(SQL_DESCR));
}
return role;
}
- public Roles getRoles() throws StoreException {
+ protected Roles getRoles() throws StoreException {
Roles roles = new Roles();
List<Role> roleList = new ArrayList<Role>();
Connection conn = dbConnect();
return roles;
}
- public Role getRole(String id) throws StoreException {
+ protected Role getRole(String id) throws StoreException {
Connection conn = dbConnect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM ROLES WHERE roleid = ? ");
}
}
- public Role createRole(Role role) throws StoreException {
+ protected Role createRole(Role role) throws StoreException {
Preconditions.checkNotNull(role);
Preconditions.checkNotNull(role.getName());
- Preconditions.checkNotNull(role.getDomainID());
+ Preconditions.checkNotNull(role.getDomainid());
Connection conn = dbConnect();
try {
String query = "insert into roles (roleid,domainid,name,description) values(?,?,?,?)";
PreparedStatement statement = conn.prepareStatement(query);
- role.setRoleid(role.getName()+"@"+role.getDomainID());
+ role.setRoleid(IDMStoreUtil.createRoleid(role.getName(),role.getDomainid()));
statement.setString(1, role.getRoleid());
- statement.setString(2, role.getDomainID());
+ statement.setString(2, role.getDomainid());
statement.setString(3,role.getName());
statement.setString(4,role.getDescription());
int affectedRows = statement.executeUpdate();
}
}
- public Role putRole(Role role) throws StoreException {
+ protected Role putRole(Role role) throws StoreException {
Role savedRole = this.getRole(role.getRoleid());
if (savedRole==null) {
return savedRole;
}
- public Role deleteRole(Role role) throws StoreException {
- Role savedRole = this.getRole(role.getRoleid());
+ protected Role deleteRole(String roleid) throws StoreException {
+ Role savedRole = this.getRole(roleid);
if (savedRole==null) {
return null;
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
/**
*
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
/**
*
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.aaa.idm.IdmLightApplication;
-import org.opendaylight.aaa.idm.model.User;
-import org.opendaylight.aaa.idm.model.Users;
+import org.opendaylight.aaa.api.IDMStoreUtil;
+import org.opendaylight.aaa.api.SHA256Calculator;
+import org.opendaylight.aaa.api.model.User;
+import org.opendaylight.aaa.api.model.Users;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
protected final static String SQL_SALT = "salt";
public final static int MAX_FIELD_LEN = 128;
+ protected UserStore(){
+ }
+
protected Connection getDBConnect() throws StoreException {
- dbConnection = IdmLightApplication.getConnection(dbConnection);
+ dbConnection = H2Store.getConnection(dbConnection);
return dbConnection;
}
User user = new User();
try {
user.setUserid(rs.getString(SQL_ID));
- user.setDomainID(rs.getString(SQL_DOMAIN_ID));
+ user.setDomainid(rs.getString(SQL_DOMAIN_ID));
user.setName(rs.getString(SQL_NAME));
user.setEmail(rs.getString(SQL_EMAIL));
user.setPassword(rs.getString(SQL_PASSWORD));
return user;
}
- public Users getUsers() throws StoreException {
+ protected Users getUsers() throws StoreException {
Users users = new Users();
List<User> userList = new ArrayList<User>();
Connection conn = dbConnect();
return users;
}
- public Users getUsers(String username,String domain) throws StoreException {
+ protected Users getUsers(String username,String domain) throws StoreException {
debug("getUsers for:" + username + " in domain "+domain);
Users users = new Users();
Connection conn = dbConnect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM USERS WHERE userid = ? ");
- pstmt.setString(1, username+"@"+domain);
+ pstmt.setString(1, IDMStoreUtil.createUserid(username,domain));
debug("query string: " + pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
}
- public User getUser(String id) throws StoreException {
+ protected User getUser(String id) throws StoreException {
Connection conn = dbConnect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM USERS WHERE userid = ? ");
}
}
- public User createUser(User user) throws StoreException {
+ protected User createUser(User user) throws StoreException {
Preconditions.checkNotNull(user);
Preconditions.checkNotNull(user.getName());
- Preconditions.checkNotNull(user.getDomainID());
+ Preconditions.checkNotNull(user.getDomainid());
Connection conn = dbConnect();
try {
user.setSalt(SHA256Calculator.generateSALT());
String query = "insert into users (userid,domainid,name,email,password,description,enabled,salt) values(?,?,?,?,?,?,?,?)";
PreparedStatement statement = conn.prepareStatement(query);
- user.setUserid(user.getName()+"@"+user.getDomainID());
+ user.setUserid(IDMStoreUtil.createUserid(user.getName(),user.getDomainid()));
statement.setString(1,user.getUserid());
- statement.setString(2,user.getDomainID());
+ statement.setString(2,user.getDomainid());
statement.setString(3,user.getName());
statement.setString(4,user.getEmail());
statement.setString(5,SHA256Calculator.getSHA256(user.getPassword(),user.getSalt()));
statement.setString(6,user.getDescription());
- statement.setInt(7,user.getEnabled()?1:0);
+ statement.setInt(7,user.isEnabled()?1:0);
statement.setString(8, user.getSalt());
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
}
}
- public User putUser(User user) throws StoreException {
+ protected User putUser(User user) throws StoreException {
User savedUser = this.getUser(user.getUserid());
if (savedUser==null) {
if (user.getName()!=null) {
savedUser.setName(user.getName());
}
- if (user.getEnabled()!=null) {
- savedUser.setEnabled(user.getEnabled());
+ if (user.isEnabled()!=null) {
+ savedUser.setEnabled(user.isEnabled());
}
if (user.getEmail()!=null) {
savedUser.setEmail(user.getEmail());
statement.setString(1, savedUser.getEmail());
statement.setString(2, savedUser.getPassword());
statement.setString(3, savedUser.getDescription());
- statement.setInt(4, savedUser.getEnabled()?1:0);
+ statement.setInt(4, savedUser.isEnabled()?1:0);
statement.setString(5,savedUser.getUserid());
statement.executeUpdate();
statement.close();
return savedUser;
}
- public User deleteUser(User user) throws StoreException {
- User savedUser = this.getUser(user.getUserid());
+ protected User deleteUser(String userid) throws StoreException {
+ User savedUser = this.getUser(userid);
if (savedUser==null) {
return null;
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.aaa.idm.model.Domains;
+import org.opendaylight.aaa.api.model.Domains;
+import org.opendaylight.aaa.h2.persistence.DomainStore;
public class DomainStoreTest {
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.aaa.idm.model.Grants;
+import org.opendaylight.aaa.api.model.Grants;
+import org.opendaylight.aaa.h2.persistence.GrantStore;
public class GrantStoreTest {
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
import java.io.File;
import java.sql.SQLException;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.opendaylight.aaa.idm.model.Domain;
-import org.opendaylight.aaa.idm.model.Grant;
-import org.opendaylight.aaa.idm.model.Role;
-import org.opendaylight.aaa.idm.model.User;
-import org.opendaylight.aaa.idm.rest.UserHandler;
-
-public class IDMTest {
+import org.opendaylight.aaa.api.IDMStoreUtil;
+import org.opendaylight.aaa.api.IIDMStore;
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.User;
+
+public class H2StoreTest {
@BeforeClass
public static void start() {
File f = new File("idmlight.db.mv.db");
Domain d = new Domain();
Assert.assertEquals(true, d != null);
DomainStore ds = new DomainStore();
- d.setName(StoreBuilder.DEFAULT_DOMAIN);
+ d.setName(IIDMStore.DEFAULT_DOMAIN);
d.setEnabled(true);
try {
d = ds.createDomain(d);
@Test
public void testCreateTempRole() throws StoreException {
- Role role = StoreBuilder.createRole("temp","temp domain","Temp Testing role");
+ Role role = H2Store.createRole("temp","temp domain","Temp Testing role");
Assert.assertEquals(true, role != null);
}
@Test
public void testCreateUser() throws StoreException {
- User user = StoreBuilder.createUser("test","pass","domain","desc","email",true,"SALT");
+ User user = H2Store.createUser("test","pass","domain","desc","email",true,"SALT");
Assert.assertEquals(true, user != null);
}
@Test
public void testCreateGrant() throws StoreException {
- Domain d = StoreBuilder.createDomain("sdn",true);
- Role role = StoreBuilder.createRole("temp","temp domain","Temp Testing role");
- User user = StoreBuilder.createUser("test","pass","domain","desc","email",true,"SALT");
- Grant g = StoreBuilder.createGrant(d.getDomainid(), user.getUserid(), role.getRoleid());
+ Domain d = H2Store.createDomain("sdn",true);
+ Role role = H2Store.createRole("temp","temp domain","Temp Testing role");
+ User user = H2Store.createUser("test","pass","domain","desc","email",true,"SALT");
+ Grant g = H2Store.createGrant(d.getDomainid(), user.getUserid(), role.getRoleid());
Assert.assertEquals(true, g != null);
}
@Test
public void testUpdatingUserEmail() throws StoreException {
UserStore us = new UserStore();
- Domain d = StoreBuilder.createDomain("sdn",true);
- Role role = StoreBuilder.createRole("temp",d.getDomainid(),"Temp Testing role");
- User user = StoreBuilder.createUser("test","pass",d.getDomainid(),"desc","email",true,"SALT");
- Grant g = StoreBuilder.createGrant(d.getDomainid(), user.getUserid(), role.getRoleid());
+ Domain d = H2Store.createDomain("sdn",true);
+ User user = H2Store.createUser("test","pass",d.getDomainid(),"desc","email",true,"SALT");
user.setName("test");
user = us.putUser(user);
user = new User();
user.setName("test");
- user.setDomainID(d.getDomainid());
- user = us.getUser(user.getName()+"@"+user.getDomainID());
+ user.setDomainid(d.getDomainid());
+ user = us.getUser(IDMStoreUtil.createUserid(user.getName(),user.getDomainid()));
Assert.assertEquals("Test@Test.com", user.getEmail());
}
-
+ /*
@Test
public void testCreateUserViaAPI() throws StoreException {
Domain d = StoreBuilder.createDomain("sdn",true);
User user = new User();
user.setName("Hello");
user.setPassword("Hello");
- user.setDomainID(d.getDomainid());
+ user.setDomainid(d.getDomainid());
UserHandler h = new UserHandler();
h.createUser(null, user);
User u = new User();
u.setName("Hello");
- u.setDomainID(d.getDomainid());
+ u.setDomainid(d.getDomainid());
UserStore us = new UserStore();
- u = us.getUser(u.getName()+"@"+u.getDomainID());
+ u = us.getUser(IDMStoreUtil.createUserid(u.getName(),u.getDomainid()));
Assert.assertEquals(true, u != null);
}
User user = new User();
user.setName("Hello");
user.setPassword("Hello");
- user.setDomainID(d.getDomainid());
+ user.setDomainid(d.getDomainid());
UserHandler h = new UserHandler();
h.createUser(null, user);
User u = new User();
u.setName("Hello");
- u.setDomainID(d.getDomainid());
- u = us.getUser(u.getName()+"@"+u.getDomainID());
+ u.setDomainid(d.getDomainid());
+ u = us.getUser(IDMStoreUtil.createUserid(u.getName(),u.getDomainid()));
Assert.assertEquals("Hello@Hello.com", u.getEmail());
User user = new User();
user.setName("Hello");
user.setPassword("Hello");
- user.setDomainID(d.getDomainid());
+ user.setDomainid(d.getDomainid());
UserHandler h = new UserHandler();
h.createUser(null, user);
Assert.assertEquals(true, g != null);
Assert.assertEquals(g.getRoleid(), role1.getRoleid());
- g = new Grant();
- g.setUserid(user.getUserid());
- g.setDomainid(d.getDomainid());
- g.setRoleid(role1.getRoleid());
- gs.deleteGrant(g);
+ g = gs.deleteGrant(IDMStoreUtil.createGrantid(user.getUserid(), d.getDomainid(), role1.getRoleid()));
g.setRoleid(role2.getRoleid());
g = gs.createGrant(g);
User u = new User();
u.setName("Hello");
- u.setDomainID(d.getDomainid());
+ u.setDomainid(d.getDomainid());
UserStore us = new UserStore();
- u = us.getUser(u.getName()+"@"+u.getDomainID());
+ u = us.getUser(IDMStoreUtil.createUserid(u.getName(),u.getDomainid()));
Assert.assertEquals("Hello@Hello.com", u.getEmail());
String hash = SHA256Calculator.getSHA256("Test123", u.getSalt());
Assert.assertEquals(true, hash.equals(u.getPassword()));
- }
+ }*/
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.aaa.idm.model.Roles;
+import org.opendaylight.aaa.api.model.Roles;
+import org.opendaylight.aaa.h2.persistence.RoleStore;
public class RoleStoreTest {
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.aaa.idm.persistence;
+package org.opendaylight.aaa.h2.persistence;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.aaa.idm.model.Users;
+import org.opendaylight.aaa.api.model.Users;
+import org.opendaylight.aaa.h2.persistence.UserStore;
public class UserStoreTest {
<extensions>true</extensions>
<configuration>
<instructions>
- <Import-Package>javax.servlet.http,javax.ws.rs,javax.ws.rs.core,javax.xml.bind.annotation,org.apache.felix.dm,org.opendaylight.aaa,org.opendaylight.aaa.api,org.osgi.framework,org.slf4j,org.eclipse.jetty.servlets,com.sun.jersey.spi.container.servlet,com.google.*</Import-Package>
- <Private-Package>org.h2.*</Private-Package>
- <Embed-Dependency>h2</Embed-Dependency>
+ <Import-Package>javax.servlet.http,javax.ws.rs,javax.ws.rs.core,javax.xml.bind.annotation,org.apache.felix.dm,org.opendaylight.aaa,org.opendaylight.aaa.api.*,org.osgi.framework,org.slf4j,org.eclipse.jetty.servlets,com.sun.jersey.spi.container.servlet,com.google.*</Import-Package>
<Web-ContextPath>/auth</Web-ContextPath>
<!--<Web-Connectors>adminConn</Web-Connectors> -->
<Bundle-Activator>org.opendaylight.aaa.idm.Activator</Bundle-Activator>
import org.apache.felix.dm.DependencyActivatorBase;
import org.apache.felix.dm.DependencyManager;
import org.opendaylight.aaa.api.CredentialAuth;
+import org.opendaylight.aaa.api.IIDMStore;
import org.opendaylight.aaa.api.IdMService;
import org.osgi.framework.BundleContext;
new String[] { CredentialAuth.class.getName(),
IdMService.class.getName() }, null).setImplementation(
IdmLightProxy.class));
+ manager.add(createComponent()
+ .setImplementation(ServiceLocator.INSTANCE)
+ .add(createServiceDependency().setService(IIDMStore.class).setRequired(true)));
}
@Override
package org.opendaylight.aaa.idm;
-import java.sql.Connection;
-import java.sql.DriverManager;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import javax.ws.rs.core.Application;
+import org.opendaylight.aaa.api.IDMStoreException;
import org.opendaylight.aaa.idm.rest.DomainHandler;
import org.opendaylight.aaa.idm.rest.RoleHandler;
import org.opendaylight.aaa.idm.rest.UserHandler;
import org.opendaylight.aaa.idm.rest.VersionHandler;
-import org.opendaylight.aaa.idm.config.IdmLightConfig;
-import org.opendaylight.aaa.idm.persistence.StoreBuilder;
-import org.opendaylight.aaa.idm.persistence.StoreException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* A JAX-RS application for IdmLight.
*/
public class IdmLightApplication extends Application {
private static Logger logger = LoggerFactory.getLogger(IdmLightApplication.class);
- private static IdmLightConfig config = new IdmLightConfig();
public IdmLightApplication() {
- StoreBuilder storeBuilder = new StoreBuilder();
- if (!storeBuilder.exists()) {
- storeBuilder.init();
- }
- }
-
- public static IdmLightConfig getConfig() {
- return config;
- }
-
- public static Connection getConnection(Connection existingConnection)
- throws StoreException {
- Connection connection = existingConnection;
- try {
- if (existingConnection == null || existingConnection.isClosed()) {
- new org.h2.Driver();
- connection = DriverManager.getConnection(config.getDbPath(),
- config.getDbUser(), config.getDbPwd());
- }
- } catch (Exception e) {
- throw new StoreException("Cannot connect to database server " + e);
- }
-
- return connection;
+ try {
+ StoreBuilder.init();
+ } catch (IDMStoreException e) {
+ logger.error("Failed to populate the store with default values",e);
+ }
}
@Override
RoleHandler.class,
UserHandler.class));
}
-
}
package org.opendaylight.aaa.idm;
-import static org.opendaylight.aaa.idm.persistence.StoreBuilder.DEFAULT_DOMAIN;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.opendaylight.aaa.api.AuthenticationException;
import org.opendaylight.aaa.api.Claim;
import org.opendaylight.aaa.api.CredentialAuth;
+import org.opendaylight.aaa.api.IDMStoreException;
+import org.opendaylight.aaa.api.IIDMStore;
import org.opendaylight.aaa.api.IdMService;
import org.opendaylight.aaa.api.PasswordCredentials;
-import org.opendaylight.aaa.idm.model.Domain;
-import org.opendaylight.aaa.idm.model.Domains;
-import org.opendaylight.aaa.idm.model.Grant;
-import org.opendaylight.aaa.idm.model.Grants;
-import org.opendaylight.aaa.idm.model.Role;
-import org.opendaylight.aaa.idm.model.User;
-import org.opendaylight.aaa.idm.model.Users;
-import org.opendaylight.aaa.idm.persistence.DomainStore;
-import org.opendaylight.aaa.idm.persistence.GrantStore;
-import org.opendaylight.aaa.idm.persistence.RoleStore;
-import org.opendaylight.aaa.idm.persistence.SHA256Calculator;
-import org.opendaylight.aaa.idm.persistence.StoreException;
-import org.opendaylight.aaa.idm.persistence.UserStore;
+import org.opendaylight.aaa.api.SHA256Calculator;
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Grants;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.User;
+import org.opendaylight.aaa.api.model.Users;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IdmLightProxy implements CredentialAuth<PasswordCredentials>,IdMService {
private static Logger logger = LoggerFactory.getLogger(IdmLightProxy.class);
- private static UserStore userStore = new UserStore();
- private static GrantStore grantStore = new GrantStore();
- private static DomainStore domainStore = new DomainStore();
- private static RoleStore roleStore = new RoleStore();
-
- // Simple map of claim cache by domain names
private static Map<String, Map<PasswordCredentials, Claim>> claimCache = new ConcurrentHashMap<>();
static {
- claimCache.put(DEFAULT_DOMAIN, new ConcurrentHashMap<PasswordCredentials, Claim>());
+ claimCache.put(IIDMStore.DEFAULT_DOMAIN, new ConcurrentHashMap<PasswordCredentials, Claim>());
}
@Override
Preconditions.checkNotNull(creds);
Preconditions.checkNotNull(creds.username());
Preconditions.checkNotNull(creds.password());
- String domain = creds.domain() == null ? DEFAULT_DOMAIN : creds.domain();
+ String domain = creds.domain() == null ? IIDMStore.DEFAULT_DOMAIN : creds.domain();
// FIXME: Add cache invalidation
Map<PasswordCredentials, Claim> cache = claimCache.get(domain);
if (cache == null) {
private static Claim dbAuthenticate(PasswordCredentials creds) {
Domain domain=null;
User user=null;
- String credsDomain = creds.domain() == null ? DEFAULT_DOMAIN : creds.domain();
+ String credsDomain = creds.domain() == null ? IIDMStore.DEFAULT_DOMAIN : creds.domain();
// check to see domain exists
// TODO: ensure domain names are unique change to 'getDomain'
debug("get domain");
try {
- Domains domains = domainStore.getDomains(credsDomain);
- List<Domain> domainList = domains.getDomains();
- if (domainList.size()==0) {
- throw new AuthenticationException("Domain :" + credsDomain + " does not exist");
- }
- domain = domainList.get(0);
- }
- catch (StoreException se) {
- throw new AuthenticationException("idm data store exception :" + se.toString() + se);
+ domain = ServiceLocator.INSTANCE.getStore().readDomain(creds.domain());
+ if(domain==null){
+ throw new AuthenticationException("Domain :" + creds.domain() + " does not exist");
+ }
+ } catch (IDMStoreException e) {
+ throw new AuthenticationException("Error while fetching domain",e);
}
// check to see user exists and passes cred check
try {
debug("check user / pwd");
- Users users = userStore.getUsers(creds.username(),credsDomain);
+ Users users = ServiceLocator.INSTANCE.getStore().getUsers(creds.username(),creds.domain());
List<User> userList = users.getUsers();
if (userList.size()==0) {
throw new AuthenticationException("User :" + creds.username() + " does not exist in domain "+credsDomain);
// get all grants & roles for this domain and user
debug("get grants");
List<String> roles = new ArrayList<String>();
- Grants grants = grantStore.getGrants(domain.getDomainid(),user.getUserid());
+ Grants grants = ServiceLocator.INSTANCE.getStore().getGrants(domain.getDomainid(),user.getUserid());
List<Grant> grantList = grants.getGrants();
for (int z=0;z<grantList.size();z++) {
Grant grant = grantList.get(z);
- Role role = roleStore.getRole(grant.getRoleid());
+ Role role = ServiceLocator.INSTANCE.getStore().readRole(grant.getRoleid());
roles.add(role.getName());
}
}
return claim.build();
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
throw new AuthenticationException("idm data store exception :" + se.toString() + se);
}
}
public List<String> listDomains(String userId) {
debug("list Domains for userId:" + userId);
List<String> domains = new ArrayList<String>();
- int uid=0;
try {
- uid = Integer.parseInt(userId);
- }
- catch (NumberFormatException nfe) {
- logger.warn("not a valid userid:" ,userId, nfe);
- return domains;
- }
- try {
- Grants grants = grantStore.getGrants(uid);
+ Grants grants = ServiceLocator.INSTANCE.getStore().getGrants(userId);
List<Grant> grantList = grants.getGrants();
for (int z=0;z<grantList.size();z++) {
Grant grant = grantList.get(z);
- Domain domain = domainStore.getDomain(grant.getDomainid());
+ Domain domain = ServiceLocator.INSTANCE.getStore().readDomain(grant.getDomainid());
domains.add(domain.getName());
}
return domains;
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.warn("error getting domains " , se.toString(), se);
return domains;
}
try {
// find domain name for specied domain name
- Domains domains = domainStore.getDomains(domainName);
- List<Domain> domainList = domains.getDomains();
- if (domainList.size()==0) {
- debug("DomainName: " + domainName + " Not found!");
- return roles;
- }
- String did = domainList.get(0).getDomainid();
+ String did = null;
+ try {
+ Domain domain = ServiceLocator.INSTANCE.getStore().readDomain(domainName);
+ if(domain==null){
+ debug("DomainName: " + domainName + " Not found!");
+ return roles;
+ }
+ did = domain.getDomainid();
+ } catch (IDMStoreException e) {
+ return roles;
+ }
// find all grants for uid and did
- Grants grants = grantStore.getGrants(did,userId);
+ Grants grants = ServiceLocator.INSTANCE.getStore().getGrants(did,userId);
List<Grant> grantList = grants.getGrants();
for (int z=0;z<grantList.size();z++) {
Grant grant = grantList.get(z);
- Role role = roleStore.getRole(grant.getRoleid());
+ Role role = ServiceLocator.INSTANCE.getStore().readRole(grant.getRoleid());
roles.add(role.getName());
}
return roles;
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.warn("error getting roles " , se.toString(), se);
return roles;
}
--- /dev/null
+package org.opendaylight.aaa.idm;
+
+import org.opendaylight.aaa.api.IIDMStore;
+
+public enum ServiceLocator {
+ INSTANCE;
+
+ volatile IIDMStore dataStore = null;
+ public IIDMStore getStore(){
+ return dataStore;
+ }
+
+ //mainly for testing
+ public void setStore(IIDMStore _store){
+ this.dataStore = _store;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.aaa.idm;
+
+import org.opendaylight.aaa.api.IDMStoreException;
+import org.opendaylight.aaa.api.IIDMStore;
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.User;
+/**
+ *
+ * @author peter.mellquist@hp.com
+ * @author saichler@cisco.com
+ *
+ */
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class StoreBuilder {
+ private static Logger logger = LoggerFactory.getLogger(StoreBuilder.class);
+
+ public static void init() throws IDMStoreException {
+ logger.info("creating idmlight schema in store");
+ int waitingTime = 5;
+ while(ServiceLocator.INSTANCE.getStore()==null){
+ try{Thread.sleep(5000);}catch(Exception err){logger.error("Interrupted",err);}
+ logger.info("No store service is available yet, waiting up until 30 seconds, waited for "+waitingTime+" seconds..");
+ waitingTime+=5;
+ if(waitingTime>=30)
+ break;
+ }
+ if(ServiceLocator.INSTANCE.getStore()==null){
+ logger.info("Store is not available, aborting initialization");
+ return;
+ }else{
+ logger.info("Store service was found");
+ }
+
+ //Check if default domain exist, if it exist then do not create default data in the store
+ Domain defaultDomain = ServiceLocator.INSTANCE.getStore().readDomain(IIDMStore.DEFAULT_DOMAIN);
+ if(defaultDomain!=null){
+ logger.info("Found default domain in Store, skipping insertion of default data");
+ return;
+ }
+ // make domain
+ Domain domain = new Domain();
+ User adminUser = new User();
+ User userUser = new User();
+ Role adminRole = new Role();
+ Role userRole = new Role();
+ domain.setEnabled(true);
+ domain.setName(IIDMStore.DEFAULT_DOMAIN);
+ domain.setDescription("default odl sdn domain");
+ domain = ServiceLocator.INSTANCE.getStore().writeDomain(domain);
+
+ // create users
+ //admin user
+ adminUser.setEnabled(true);
+ adminUser.setName("admin");
+ adminUser.setDomainid(domain.getDomainid());
+ adminUser.setDescription("admin user");
+ adminUser.setEmail("");
+ adminUser.setPassword("admin");
+ adminUser = ServiceLocator.INSTANCE.getStore().writeUser(adminUser);
+ // user user
+ userUser.setEnabled(true);
+ userUser.setName("user");
+ userUser.setDomainid(domain.getDomainid());
+ userUser.setDescription("user user");
+ userUser.setEmail("");
+ userUser.setPassword("user");
+ userUser = ServiceLocator.INSTANCE.getStore().writeUser(userUser);
+
+ // create Roles
+ adminRole.setName("admin");
+ adminRole.setDomainid(domain.getDomainid());
+ adminRole.setDescription("a role for admins");
+ adminRole = ServiceLocator.INSTANCE.getStore().writeRole(adminRole);
+ userRole.setName("user");
+ userRole.setDomainid(domain.getDomainid());
+ userRole.setDescription("a role for users");
+ userRole = ServiceLocator.INSTANCE.getStore().writeRole(userRole);
+
+ // create grants
+ Grant grant = new Grant();
+ grant.setDomainid(domain.getDomainid());
+ grant.setUserid(userUser.getUserid());
+ grant.setRoleid(userRole.getRoleid());
+ grant = ServiceLocator.INSTANCE.getStore().writeGrant(grant);
+
+ grant.setDomainid(domain.getDomainid());
+ grant.setUserid(adminUser.getUserid());
+ grant.setRoleid(userRole.getRoleid());
+ grant = ServiceLocator.INSTANCE.getStore().writeGrant(grant);
+
+ grant.setDomainid(domain.getDomainid());
+ grant.setUserid(adminUser.getUserid());
+ grant.setRoleid(adminRole.getRoleid());
+ grant = ServiceLocator.INSTANCE.getStore().writeGrant(grant);
+ }
+}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.aaa.idm.persistence;
-
-import java.io.File;
-
-import org.opendaylight.aaa.idm.IdmLightApplication;
-import org.opendaylight.aaa.idm.model.Domain;
-import org.opendaylight.aaa.idm.model.Grant;
-import org.opendaylight.aaa.idm.model.Role;
-import org.opendaylight.aaa.idm.model.User;
-/**
- *
- * @author peter.mellquist@hp.com
- *
- */
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class StoreBuilder {
- private static Logger logger = LoggerFactory.getLogger(StoreBuilder.class);
- private static DomainStore domainStore = new DomainStore();
- private static UserStore userStore = new UserStore();
- private static RoleStore roleStore = new RoleStore();
- private static GrantStore grantStore = new GrantStore();
- public static String DEFAULT_DOMAIN = "sdn";
- // IdmLight appends ".mv.db" to the end of a database file name
- private static final String IDM_LIGHT_EXTENSION = ".mv.db";
-
- private String getIdmLightFileName(final String databaseName) {
- return databaseName + IDM_LIGHT_EXTENSION;
- }
-
- public boolean exists() {
- String idmLightFileName = this.getIdmLightFileName(IdmLightApplication.getConfig().getDbName());
- File f = new File(idmLightFileName);
- return f.exists();
- }
-
- public static Domain createDomain(String domainName,boolean enable) throws StoreException{
- DomainStore ds = new DomainStore();
- Domain d = new Domain();
- d.setName(domainName);
- d.setEnabled(enable);
- return ds.createDomain(d);
- }
-
- public static User createUser(String name, String password, String domain, String description,String email,boolean enabled,String SALT) throws StoreException{
- UserStore us = new UserStore();
- User u = new User();
- u.setName(name);
- u.setDomainID(domain);
- u.setDescription(description);
- u.setEmail(email);
- u.setEnabled(enabled);
- u.setPassword(password);
- u.setSalt(SALT);
- return us.createUser(u);
- }
-
- public static Role createRole(String name, String domain, String description) throws StoreException{
- RoleStore rs = new RoleStore();
- Role r = new Role();
- r.setDescription(description);
- r.setName(name);
- r.setDomainID(domain);
- return rs.createRole(r);
- }
-
- public static Grant createGrant(String domain,String user,String role) throws StoreException{
- GrantStore gs = new GrantStore();
- Grant g = new Grant();
- g.setDomainid(domain);
- g.setRoleid(role);
- g.setUserid(user);
- return gs.createGrant(g);
- }
-
- public void init() {
- logger.info("creating idmlight db");
- // make domain
- Domain domain = new Domain();
- User adminUser = new User();
- User userUser = new User();
- Role adminRole = new Role();
- Role userRole = new Role();
- try {
- domain.setEnabled(true);
- domain.setName(DEFAULT_DOMAIN);
- domain.setDescription("default odl sdn domain");
- domain = domainStore.createDomain(domain);
- } catch (StoreException se) {
- logger.error("StoreException : " + se);
- }
- // create users
- try {
- // admin user
- adminUser.setEnabled(true);
- adminUser.setName("admin");
- adminUser.setDomainID(domain.getDomainid());
- adminUser.setDescription("admin user");
- adminUser.setEmail("");
- adminUser.setPassword("admin");
- adminUser = userStore.createUser(adminUser);
-
- // user user
- userUser.setEnabled(true);
- userUser.setName("user");
- userUser.setDomainID(domain.getDomainid());
- userUser.setDescription("user user");
- userUser.setEmail("");
- userUser.setPassword("user");
- userUser = userStore.createUser(userUser);
- } catch (StoreException se) {
- logger.error("StoreException : " + se);
- }
-
- // create Roles
- try {
- adminRole.setName("admin");
- adminRole.setDomainID(domain.getDomainid());
- adminRole.setDescription("a role for admins");
- adminRole = roleStore.createRole(adminRole);
- userRole.setName("user");
- userRole.setDomainID(domain.getDomainid());
- userRole.setDescription("a role for users");
- userRole = roleStore.createRole(userRole);
- } catch (StoreException se) {
- logger.error("StoreException : " + se);
- }
-
- // create grants
- Grant grant = new Grant();
- try {
- grant.setDomainid(domain.getDomainid());
- grant.setUserid(userUser.getUserid());
- grant.setRoleid(userRole.getRoleid());
- grant = grantStore.createGrant(grant);
-
- grant.setDomainid(domain.getDomainid());
- grant.setUserid(adminUser.getUserid());
- grant.setRoleid(userRole.getRoleid());
- grant = grantStore.createGrant(grant);
-
- grant.setDomainid(domain.getDomainid());
- grant.setUserid(adminUser.getUserid());
- grant.setRoleid(adminRole.getRoleid());
- grant = grantStore.createGrant(grant);
- } catch (StoreException se) {
- logger.error("StoreException : " + se);
- }
-
- }
-}
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
+import org.opendaylight.aaa.api.IDMStoreException;
+import org.opendaylight.aaa.api.model.Claim;
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Domains;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Grants;
+import org.opendaylight.aaa.api.model.IDMError;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.Roles;
+import org.opendaylight.aaa.api.model.User;
+import org.opendaylight.aaa.api.model.UserPwd;
+import org.opendaylight.aaa.api.model.Users;
import org.opendaylight.aaa.idm.IdmLightProxy;
-import org.opendaylight.aaa.idm.model.Claim;
-import org.opendaylight.aaa.idm.model.Domain;
-import org.opendaylight.aaa.idm.model.Domains;
-import org.opendaylight.aaa.idm.model.Grant;
-import org.opendaylight.aaa.idm.model.Grants;
-import org.opendaylight.aaa.idm.model.IDMError;
-import org.opendaylight.aaa.idm.model.Role;
-import org.opendaylight.aaa.idm.model.Roles;
-import org.opendaylight.aaa.idm.model.User;
-import org.opendaylight.aaa.idm.model.UserPwd;
-import org.opendaylight.aaa.idm.model.Users;
-import org.opendaylight.aaa.idm.persistence.DomainStore;
-import org.opendaylight.aaa.idm.persistence.GrantStore;
-import org.opendaylight.aaa.idm.persistence.RoleStore;
-import org.opendaylight.aaa.idm.persistence.StoreException;
-import org.opendaylight.aaa.idm.persistence.UserStore;
+import org.opendaylight.aaa.idm.ServiceLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("/v1/domains")
public class DomainHandler {
private static Logger logger = LoggerFactory.getLogger(DomainHandler.class);
- private static DomainStore domainStore = new DomainStore();
- private static UserStore userStore = new UserStore();
- private static RoleStore roleStore = new RoleStore();
- private static GrantStore grantStore = new GrantStore();
@GET
@Produces("application/json")
logger.info("Get /domains");
Domains domains=null;
try {
- domains = domainStore.getDomains();
+ domains = ServiceLocator.INSTANCE.getStore().getDomains();
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domains");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
return Response.ok(domains).build();
logger.info("Get /domains/" + domainId);
Domain domain = null;
try {
- domain = domainStore.getDomain(domainId);
+ domain = ServiceLocator.INSTANCE.getStore().readDomain(domainId);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
public Response createDomain(@Context UriInfo info,Domain domain) {
logger.info("Post /domains");
try {
- if (domain.getEnabled()==null) {
+ if (domain.isEnabled()==null) {
domain.setEnabled(false);
}
if (domain.getName()==null) {
if (domain.getDescription()==null) {
domain.setDescription("");
}
- domain = domainStore.createDomain(domain);
+ domain = ServiceLocator.INSTANCE.getStore().writeDomain(domain);
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error creating domain");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
return Response.status(201).entity(domain).build();
logger.info("Put /domains/" + domainId);
try {
domain.setDomainid(domainId);
- domain = domainStore.putDomain(domain);
+ domain = ServiceLocator.INSTANCE.getStore().updateDomain(domain);
if (domain==null) {
IDMError idmerror = new IDMError();
idmerror.setMessage("Not found! Domain id :" + domainId);
IdmLightProxy.clearClaimCache();
return Response.status(200).entity(domain).build();
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error putting domain");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
}
logger.info("Delete /domains/" + domainId);
try {
- Domain domain = new Domain();
- domain.setDomainid(domainId);
- domain = domainStore.deleteDomain(domain);
+ Domain domain = ServiceLocator.INSTANCE.getStore().deleteDomain(domainId);
if (domain==null) {
IDMError idmerror = new IDMError();
idmerror.setMessage("Not found! Domain id :" + domainId);
return Response.status(404).entity(idmerror).build();
}
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error deleting Domain");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
IdmLightProxy.clearClaimCache();
// validate domain id
try {
- domain = domainStore.getDomain(domainId);
+ domain = ServiceLocator.INSTANCE.getStore().readDomain(domainId);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
if (domain==null) {
grant.setDomainid(domainId);
try {
- user = userStore.getUser(userId);
+ user = ServiceLocator.INSTANCE.getStore().readUser(userId);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting user");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
if (user==null) {
return Response.status(404).entity(idmerror).build();
}
try {
- role = roleStore.getRole(roleId);
+ role = ServiceLocator.INSTANCE.getStore().readRole(roleId);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting role");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
if (role==null) {
// see if grant already exists for this
try {
- Grant existingGrant = grantStore.getGrant(domainId,userId,roleId);
+ Grant existingGrant = ServiceLocator.INSTANCE.getStore().readGrant(domainId,userId,roleId);
if (existingGrant != null) {
IDMError idmerror = new IDMError();
idmerror.setMessage("Grant already exists for did:"+domainId+" uid:"+userId+" rid:"+roleId);
return Response.status(403).entity(idmerror).build();
}
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error creating grant");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
// create grant
try {
- grant = grantStore.createGrant(grant);
+ grant = ServiceLocator.INSTANCE.getStore().writeGrant(grant);
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error creating grant");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
List<Role> roleList = new ArrayList<Role>();
try {
- domain = domainStore.getDomain(domainId);
+ domain = ServiceLocator.INSTANCE.getStore().readDomain(domainId);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
if (domain==null) {
// find userid for user
try {
- Users users = userStore.getUsers(username,domainId);
+ Users users = ServiceLocator.INSTANCE.getStore().getUsers(username,domainId);
List<User> userList = users.getUsers();
if (userList.size()==0) {
IDMError idmerror = new IDMError();
claim.setUsername(username);
claim.setUserid(user.getUserid());
try {
- Grants grants = grantStore.getGrants(domainId,user.getUserid());
+ Grants grants = ServiceLocator.INSTANCE.getStore().getGrants(domainId,user.getUserid());
List<Grant> grantsList = grants.getGrants();
for (int i=0; i < grantsList.size(); i++) {
Grant grant = grantsList.get(i);
- Role role = roleStore.getRole(grant.getRoleid());
+ Role role = ServiceLocator.INSTANCE.getStore().readRole(grant.getRoleid());
roleList.add(role);
}
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting Roles");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
claim.setRoles(roleList);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting user");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
List<Role> roleList = new ArrayList<Role>();
try {
- domain = domainStore.getDomain(domainId);
+ domain = ServiceLocator.INSTANCE.getStore().readDomain(domainId);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
if (domain==null) {
}
try {
- user = userStore.getUser(userId);
+ user = ServiceLocator.INSTANCE.getStore().readUser(userId);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting user");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
if (user==null) {
}
try {
- Grants grants = grantStore.getGrants(domainId,userId);
+ Grants grants = ServiceLocator.INSTANCE.getStore().getGrants(domainId,userId);
List<Grant> grantsList = grants.getGrants();
for (int i=0; i < grantsList.size(); i++) {
Grant grant = grantsList.get(i);
- Role role = roleStore.getRole(grant.getRoleid());
+ Role role = ServiceLocator.INSTANCE.getStore().readRole(grant.getRoleid());
roleList.add(role);
}
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting Roles");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
Role role=null;
try {
- domain = domainStore.getDomain(domainId);
+ domain = ServiceLocator.INSTANCE.getStore().readDomain(domainId);
}
- catch(StoreException se) {
- logger.error("StoreException : " + se);
+ catch(IDMStoreException se) {
+ logger.error("Error deleting Grant : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting domain");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
if (domain==null) {
}
try {
- user = userStore.getUser(userId);
+ user = ServiceLocator.INSTANCE.getStore().readUser(userId);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting user");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
if (user==null) {
}
try {
- role = roleStore.getRole(roleId);
+ role = ServiceLocator.INSTANCE.getStore().readRole(roleId);
}
- catch(StoreException se) {
+ catch(IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error getting Role");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
if (role==null) {
// see if grant already exists
try {
- Grant existingGrant = grantStore.getGrant(domainId,userId,roleId);
+ Grant existingGrant = ServiceLocator.INSTANCE.getStore().readGrant(domainId,userId,roleId);
if (existingGrant == null) {
IDMError idmerror = new IDMError();
idmerror.setMessage("Grant does not exist for did:"+domainId+" uid:"+userId+" rid:"+roleId);
return Response.status(404).entity(idmerror).build();
}
- existingGrant = grantStore.deleteGrant(existingGrant);
+ existingGrant = ServiceLocator.INSTANCE.getStore().deleteGrant(existingGrant.getDomainid());
}
- catch (StoreException se) {
+ catch (IDMStoreException se) {
logger.error("StoreException : " + se);
IDMError idmerror = new IDMError();
idmerror.setMessage("Internal error creating grant");
- idmerror.setDetails(se.message);
+ idmerror.setDetails(se.getMessage());
return Response.status(500).entity(idmerror).build();
}
IdmLightProxy.clearClaimCache();
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
+import org.opendaylight.aaa.api.IDMStoreException;
+import org.opendaylight.aaa.api.IIDMStore;
+import org.opendaylight.aaa.api.model.IDMError;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.Roles;
import org.opendaylight.aaa.idm.IdmLightProxy;
-import org.opendaylight.aaa.idm.model.IDMError;
-import org.opendaylight.aaa.idm.model.Role;
-import org.opendaylight.aaa.idm.model.Roles;
-import org.opendaylight.aaa.idm.persistence.RoleStore;
-import org.opendaylight.aaa.idm.persistence.StoreException;
+import org.opendaylight.aaa.idm.ServiceLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("/v1/roles")
public class RoleHandler {
private static Logger logger = LoggerFactory.getLogger(RoleHandler.class);
- private static RoleStore roleStore = new RoleStore();
@GET
@Produces("application/json")
logger.info("get /roles");
Roles roles=null;
try {
- roles = roleStore.getRoles();
+ roles = ServiceLocator.INSTANCE.getStore().getRoles();
}
- catch (StoreException se) {
- return new IDMError(500,"internal error getting roles",se.message).response();
+ catch (IDMStoreException se) {
+ return new IDMError(500,"internal error getting roles",se.getMessage()).response();
}
return Response.ok(roles).build();
}
Role role=null;
try {
- role = roleStore.getRole(id);
+ role = ServiceLocator.INSTANCE.getStore().readRole(id);
}
- catch(StoreException se) {
- return new IDMError(500,"internal error getting roles",se.message).response();
+ catch(IDMStoreException se) {
+ return new IDMError(500,"internal error getting roles",se.getMessage()).response();
}
if (role==null) {
if (role.getName()==null) {
return new IDMError(404,"name must be defined on role create","").response();
}
- else if (role.getName().length()>RoleStore.MAX_FIELD_LEN) {
- return new IDMError(400,"role name max length is :" + RoleStore.MAX_FIELD_LEN,"").response();
+ else if (role.getName().length()>IIDMStore.MAX_FIELD_LEN) {
+ return new IDMError(400,"role name max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
// domain
- if (role.getDomainID()==null) {
+ if (role.getDomainid()==null) {
return new IDMError(404,"The role's domain must be defined on role when creating a role.","").response();
}
- else if (role.getDomainID().length()>RoleStore.MAX_FIELD_LEN) {
- return new IDMError(400,"role domain max length is :" + RoleStore.MAX_FIELD_LEN,"").response();
+ else if (role.getDomainid().length()>IIDMStore.MAX_FIELD_LEN) {
+ return new IDMError(400,"role domain max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
// description
if (role.getDescription()==null) {
role.setDescription("");
}
- else if (role.getDescription().length()>RoleStore.MAX_FIELD_LEN) {
- return new IDMError(400,"role description max length is :" + RoleStore.MAX_FIELD_LEN,"").response();
+ else if (role.getDescription().length()>IIDMStore.MAX_FIELD_LEN) {
+ return new IDMError(400,"role description max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
- role = roleStore.createRole(role);
+ role = ServiceLocator.INSTANCE.getStore().writeRole(role);
}
- catch (StoreException se) {
- return new IDMError(500,"internal error creating role",se.message).response();
+ catch (IDMStoreException se) {
+ return new IDMError(500,"internal error creating role",se.getMessage()).response();
}
return Response.status(201).entity(role).build();
// name
// TODO: names should be unique
- if ((role.getName()!=null) && (role.getName().length()>RoleStore.MAX_FIELD_LEN)) {
- return new IDMError(400,"role name max length is :" + RoleStore.MAX_FIELD_LEN,"").response();
+ if ((role.getName()!=null) && (role.getName().length()>IIDMStore.MAX_FIELD_LEN)) {
+ return new IDMError(400,"role name max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
// description
- if ((role.getDescription()!=null) && (role.getDescription().length()>RoleStore.MAX_FIELD_LEN)) {
- return new IDMError(400,"role description max length is :" + RoleStore.MAX_FIELD_LEN,"").response();
+ if ((role.getDescription()!=null) && (role.getDescription().length()>IIDMStore.MAX_FIELD_LEN)) {
+ return new IDMError(400,"role description max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
- role = roleStore.putRole(role);
+ role = ServiceLocator.INSTANCE.getStore().updateRole(role);
if (role==null) {
return new IDMError(404,"role id not found :" + id,"").response();
}
IdmLightProxy.clearClaimCache();
return Response.status(200).entity(role).build();
}
- catch (StoreException se) {
- return new IDMError(500,"internal error putting role",se.message).response();
+ catch (IDMStoreException se) {
+ return new IDMError(500,"internal error putting role",se.getMessage()).response();
}
}
logger.info("Delete /roles/" + id);
try {
- Role role = new Role();
- role.setRoleid(id);
- role = roleStore.deleteRole(role);
+ Role role = ServiceLocator.INSTANCE.getStore().deleteRole(id);
if (role==null) {
return new IDMError(404,"role id not found :" + id,"").response();
}
}
- catch (StoreException se) {
- return new IDMError(500,"internal error deleting role",se.message).response();
+ catch (IDMStoreException se) {
+ return new IDMError(500,"internal error deleting role",se.getMessage()).response();
}
IdmLightProxy.clearClaimCache();
return Response.status(204).build();
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
+import org.opendaylight.aaa.api.IDMStoreException;
+import org.opendaylight.aaa.api.IIDMStore;
+import org.opendaylight.aaa.api.model.IDMError;
+import org.opendaylight.aaa.api.model.User;
+import org.opendaylight.aaa.api.model.Users;
import org.opendaylight.aaa.idm.IdmLightProxy;
-import org.opendaylight.aaa.idm.model.IDMError;
-import org.opendaylight.aaa.idm.model.User;
-import org.opendaylight.aaa.idm.model.Users;
-import org.opendaylight.aaa.idm.persistence.StoreException;
-import org.opendaylight.aaa.idm.persistence.UserStore;
+import org.opendaylight.aaa.idm.ServiceLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("/v1/users")
public class UserHandler {
private static Logger logger = LoggerFactory.getLogger(UserHandler.class);
- private static UserStore userStore = new UserStore();
protected final static String DEFAULT_PWD = "changeme";
public static final String REDACTED_PASSWORD = "**********";
logger.info("get all users");
Users users=null;
try {
- users = userStore.getUsers();
+ users = ServiceLocator.INSTANCE.getStore().getUsers();
}
- catch (StoreException se) {
- return new IDMError(500,"internal error getting users",se.message).response();
+ catch (IDMStoreException se) {
+ return new IDMError(500,"internal error getting users",se.getMessage()).response();
}
// obsfucate pwd
logger.info("get /users/" + id);
User user=null;
try {
- user = userStore.getUser(id);
+ user = ServiceLocator.INSTANCE.getStore().readUser(id);
}
- catch(StoreException se) {
- return new IDMError(500,"internal error getting user",se.message).response();
+ catch(IDMStoreException se) {
+ return new IDMError(500,"internal error getting user",se.getMessage()).response();
}
if (user==null) {
return new IDMError(404,"user not found! id:" + id,"").response();
logger.info("post /users");
try {
// enabled by default
- if (user.getEnabled()==null) {
+ if (user.isEnabled()==null) {
user.setEnabled(true);
}
if (user.getName()==null) {
return new IDMError(400,"user name is required","").response();
}
- else if (user.getName().length()>UserStore.MAX_FIELD_LEN) {
- return new IDMError(400,"user name max length is :" + UserStore.MAX_FIELD_LEN,"").response();
+ else if (user.getName().length()>IIDMStore.MAX_FIELD_LEN) {
+ return new IDMError(400,"user name max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
// domain id/name is required
- if (user.getDomainID()==null) {
+ if (user.getDomainid()==null) {
return new IDMError(400,"user domain is required","").response();
}
- else if (user.getDomainID().length()>UserStore.MAX_FIELD_LEN) {
- return new IDMError(400,"user domain max length is :" + UserStore.MAX_FIELD_LEN,"").response();
+ else if (user.getDomainid().length()>IIDMStore.MAX_FIELD_LEN) {
+ return new IDMError(400,"user domain max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
// user description is optional
if (user.getDescription()==null) {
user.setDescription("");
}
- else if (user.getDescription().length()>UserStore.MAX_FIELD_LEN) {
- return new IDMError(400,"user description max length is :" + UserStore.MAX_FIELD_LEN,"").response();
+ else if (user.getDescription().length()>IIDMStore.MAX_FIELD_LEN) {
+ return new IDMError(400,"user description max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
// user email is optional
if (user.getEmail()==null) {
user.setEmail("");
}
- else if (user.getEmail().length()>UserStore.MAX_FIELD_LEN) {
- return new IDMError(400,"user email max length is :" + UserStore.MAX_FIELD_LEN,"").response();
+ else if (user.getEmail().length()>IIDMStore.MAX_FIELD_LEN) {
+ return new IDMError(400,"user email max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
// user password optional and will default if not provided
if (user.getPassword()==null) {
user.setPassword(DEFAULT_PWD);
}
- else if (user.getPassword().length()>UserStore.MAX_FIELD_LEN) {
- return new IDMError(400,"user password max length is :" + UserStore.MAX_FIELD_LEN,"").response();
+ else if (user.getPassword().length()>IIDMStore.MAX_FIELD_LEN) {
+ return new IDMError(400,"user password max length is :" + IIDMStore.MAX_FIELD_LEN,"").response();
}
// create user
- User createdUser = userStore.createUser(user);
+ User createdUser = ServiceLocator.INSTANCE.getStore().writeUser(user);
user.setUserid(createdUser.getUserid());
}
- catch (StoreException se) {
- return new IDMError(500,"internal error creating user",se.message).response();
+ catch (IDMStoreException se) {
+ return new IDMError(500,"internal error creating user",se.getMessage()).response();
}
// created!
try {
user.setUserid(id);
- user = userStore.putUser(user);
+ user = ServiceLocator.INSTANCE.getStore().updateUser(user);
if (user==null) {
return new IDMError(404,"user id not found id :"+id,"").response();
}
user.setPassword(REDACTED_PASSWORD);
return Response.status(200).entity(user).build();
}
- catch (StoreException se) {
- return new IDMError(500,"internal error putting user",se.message).response();
+ catch (IDMStoreException se) {
+ return new IDMError(500,"internal error putting user",se.getMessage()).response();
}
}
logger.info("delete /users/" + id);
try {
- User user = new User();
- user.setUserid(id);
- user = userStore.deleteUser(user);
+ User user = ServiceLocator.INSTANCE.getStore().deleteUser(id);
if (user==null) {
return new IDMError(404,"user id not found id :"+id,"").response();
}
}
- catch (StoreException se) {
- return new IDMError(500,"internal error deleting user",se.message).response();
+ catch (IDMStoreException se) {
+ return new IDMError(500,"internal error deleting user",se.getMessage()).response();
}
IdmLightProxy.clearClaimCache();
return Response.status(204).build();
}
-}
\ No newline at end of file
+}
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
+
+import org.opendaylight.aaa.api.model.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.opendaylight.aaa.idm.model.Version;
@Path("/")
public class VersionHandler {
</web-resource-collection>
</security-constraint>
-</web-app>
+</web-app>
\ No newline at end of file
package org.opendaylight.aaa.idm.persistence;
-import java.io.File;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.Mockito;
+import org.opendaylight.aaa.api.IDMStoreException;
+import org.opendaylight.aaa.api.IIDMStore;
import org.opendaylight.aaa.api.PasswordCredentials;
+import org.opendaylight.aaa.api.SHA256Calculator;
+import org.opendaylight.aaa.api.model.Domain;
+import org.opendaylight.aaa.api.model.Grant;
+import org.opendaylight.aaa.api.model.Grants;
+import org.opendaylight.aaa.api.model.Role;
+import org.opendaylight.aaa.api.model.User;
+import org.opendaylight.aaa.api.model.Users;
import org.opendaylight.aaa.idm.IdmLightProxy;
+import org.opendaylight.aaa.idm.ServiceLocator;
/*
* @Author - Sharon Aicler (saichler@cisco.com)
@Before
public void before(){
- File f = new File("idmlight.db.mv.db");
- if(f.exists()){
- f.delete();
- }
- f = new File("idmlight.db.trace.db");
- if(f.exists()){
- f.delete();
- }
- }
+ IIDMStore store = Mockito.mock(IIDMStore.class);
+ ServiceLocator.INSTANCE.setStore(store);
+ Domain domain = new Domain();
+ domain.setName("sdn");
+ domain.setDomainid("sdn");
+ try {
+ Mockito.when(store.readDomain("sdn")).thenReturn(domain);
+ Creds c = new Creds();
+ Users users = new Users();
+ User user = new User();
+ user.setName("admin");
+ user.setUserid(c.username());
+ user.setDomainid("sdn");
+ user.setSalt("ABCD");
+ user.setPassword(SHA256Calculator.getSHA256(c.password(),user.getSalt()));
+ List<User> lu = new LinkedList<>();
+ lu.add(user);
+ users.setUsers(lu);
- @After
- public void after(){
- File f = new File("idmlight.db.mv.db");
- if(f.exists()){
- f.delete();
- }
- f = new File("idmlight.db.trace.db");
- if(f.exists()){
- f.delete();
+ Grants grants = new Grants();
+ Grant grant = new Grant();
+ List<Grant> g = new ArrayList<>();
+ g.add(grant);
+ grant.setDomainid("sdn");
+ grant.setRoleid("admin");
+ grant.setUserid("admin");
+ grants.setGrants(g);
+ Role role = new Role();
+ role.setRoleid("admin");
+ role.setName("admin");
+ Mockito.when(store.readRole("admin")).thenReturn(role);
+ Mockito.when(store.getUsers(c.username(), c.domain())).thenReturn(users);
+ Mockito.when(store.getGrants(c.domain(), c.username())).thenReturn(grants);
+
+ } catch (IDMStoreException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
}
}
@Test
public void testPasswordHash(){
- StoreBuilder b = new StoreBuilder();
- b.init();
IdmLightProxy proxy = new IdmLightProxy();
proxy.authenticate(new Creds());
}
<classifier>features</classifier>
<type>xml</type>
</dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>aaa-h2-store</artifactId>
+ <version>${project.version}</version>
+ </dependency>
</dependencies>
</dependencyManagement>
</dependencyManagement>
<dependencies>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-server</artifactId>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.aaa</groupId>
<artifactId>aaa-authn-api</artifactId>
<repository>mvn:org.opendaylight.mdsal/features-mdsal/{{VERSION}}/xml/features</repository>
<feature name='odl-aaa-api' description='OpenDaylight :: AAA :: APIs'
version='${project.version}'>
+ <bundle>mvn:com.sun.jersey/jersey-server/{{VERSION}}</bundle>
+ <bundle>mvn:com.sun.jersey/jersey-core/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.aaa/aaa-authn-api/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.aaa/aaa-credential-store-api/{{VERSION}}</bundle>
<feature version='${yangtools.version}'>odl-yangtools-common</feature>
<type>cfg</type>
<classifier>config</classifier>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.aaa</groupId>
+ <artifactId>aaa-h2-store</artifactId>
+ </dependency>
<!-- AuthN MD-SAL Cache dependencies -->
<classifier>features</classifier>
<type>xml</type>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-mdsal</artifactId>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-mdsal</artifactId>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-config</artifactId>
<!-- IDMLight -->
+ <bundle>mvn:org.opendaylight.aaa/aaa-h2-store/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.aaa/aaa-idmlight/{{VERSION}}</bundle>
<bundle>mvn:com.fasterxml.jackson.core/jackson-core/{{VERSION}}</bundle>
<bundle>mvn:com.fasterxml.jackson.core/jackson-annotations/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.aaa/aaa-authn-sssd/{{VERSION}}</bundle>
</feature>
-</features>
+</features>
\ No newline at end of file
<module>parent</module>
<module>aaa-shiro</module>
<module>aaa-shiro-act</module>
+ <module>aaa-h2-store</module>
</modules>
<scm>