96b8013f49cdb7e51eb87c02fc6f7f766ca86043
[moon.git] /
1 /*
2  * Copyright (c) 2014, 2016 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.aaa.h2.persistence;
10
11 import com.google.common.base.Preconditions;
12
13 import java.sql.Connection;
14 import java.sql.PreparedStatement;
15 import java.sql.ResultSet;
16 import java.sql.SQLException;
17 import java.sql.Statement;
18
19 import org.apache.commons.lang3.StringEscapeUtils;
20 import org.opendaylight.aaa.api.IDMStoreUtil;
21 import org.opendaylight.aaa.api.SHA256Calculator;
22 import org.opendaylight.aaa.api.model.User;
23 import org.opendaylight.aaa.api.model.Users;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  *
29  * @author peter.mellquist@hp.com
30  *
31  */
32 public class UserStore extends AbstractStore<User> {
33     private static final Logger LOG = LoggerFactory.getLogger(UserStore.class);
34
35     protected final static String SQL_ID = "userid";
36     protected final static String SQL_DOMAIN_ID = "domainid";
37     protected final static String SQL_NAME = "name";
38     protected final static String SQL_EMAIL = "email";
39     protected final static String SQL_PASSWORD = "password";
40     protected final static String SQL_DESCR = "description";
41     protected final static String SQL_ENABLED = "enabled";
42     protected final static String SQL_SALT = "salt";
43     private static final String TABLE_NAME = "USERS";
44
45     protected UserStore() {
46         super(TABLE_NAME);
47     }
48
49     @Override
50     protected String getTableCreationStatement() {
51         return "CREATE TABLE users "
52                 + "(userid    VARCHAR(128) PRIMARY KEY,"
53                 + "name       VARCHAR(128)      NOT NULL, "
54                 + "domainid   VARCHAR(128)      NOT NULL, "
55                 + "email      VARCHAR(128)      NOT NULL, "
56                 + "password   VARCHAR(128)      NOT NULL, "
57                 + "description VARCHAR(128)     NOT NULL, "
58                 + "salt        VARCHAR(15)      NOT NULL, "
59                 + "enabled     INTEGER          NOT NULL)";
60     }
61
62     @Override
63     protected User fromResultSet(ResultSet rs) throws SQLException {
64         User user = new User();
65         try {
66             user.setUserid(rs.getString(SQL_ID));
67             user.setDomainid(rs.getString(SQL_DOMAIN_ID));
68             user.setName(rs.getString(SQL_NAME));
69             user.setEmail(rs.getString(SQL_EMAIL));
70             user.setPassword(rs.getString(SQL_PASSWORD));
71             user.setDescription(rs.getString(SQL_DESCR));
72             user.setEnabled(rs.getInt(SQL_ENABLED) == 1);
73             user.setSalt(rs.getString(SQL_SALT));
74         } catch (SQLException sqle) {
75             LOG.error("SQL Exception: ", sqle);
76             throw sqle;
77         }
78         return user;
79     }
80
81     protected Users getUsers() throws StoreException {
82         Users users = new Users();
83         users.setUsers(listAll());
84         return users;
85     }
86
87     protected Users getUsers(String username, String domain) throws StoreException {
88         LOG.debug("getUsers for: {} in domain {}", username, domain);
89
90         Users users = new Users();
91         try (Connection conn = dbConnect();
92              PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM USERS WHERE userid = ? ")) {
93             pstmt.setString(1, IDMStoreUtil.createUserid(username, domain));
94             LOG.debug("query string: {}", pstmt.toString());
95             users.setUsers(listFromStatement(pstmt));
96         } catch (SQLException s) {
97             throw new StoreException("SQL Exception : " + s);
98         }
99         return users;
100     }
101
102     protected User getUser(String id) throws StoreException {
103         try (Connection conn = dbConnect();
104              PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM USERS WHERE userid = ? ")) {
105             pstmt.setString(1, id);
106             LOG.debug("query string: {}", pstmt.toString());
107             return firstFromStatement(pstmt);
108         } catch (SQLException s) {
109             throw new StoreException("SQL Exception : " + s);
110         }
111     }
112
113     protected User createUser(User user) throws StoreException {
114         Preconditions.checkNotNull(user);
115         Preconditions.checkNotNull(user.getName());
116         Preconditions.checkNotNull(user.getDomainid());
117
118         user.setSalt(SHA256Calculator.generateSALT());
119         String query = "insert into users (userid,domainid,name,email,password,description,enabled,salt) values(?,?,?,?,?,?,?,?)";
120         try (Connection conn = dbConnect();
121              PreparedStatement statement = conn.prepareStatement(query)) {
122             user.setUserid(IDMStoreUtil.createUserid(user.getName(), user.getDomainid()));
123             statement.setString(1, user.getUserid());
124             statement.setString(2, user.getDomainid());
125             statement.setString(3, user.getName());
126             statement.setString(4, user.getEmail());
127             statement.setString(5, SHA256Calculator.getSHA256(user.getPassword(), user.getSalt()));
128             statement.setString(6, user.getDescription());
129             statement.setInt(7, user.isEnabled() ? 1 : 0);
130             statement.setString(8, user.getSalt());
131             int affectedRows = statement.executeUpdate();
132             if (affectedRows == 0) {
133                 throw new StoreException("Creating user failed, no rows affected.");
134             }
135             return user;
136         } catch (SQLException s) {
137             throw new StoreException("SQL Exception : " + s);
138         }
139     }
140
141     protected User putUser(User user) throws StoreException {
142
143         User savedUser = this.getUser(user.getUserid());
144         if (savedUser == null) {
145             return null;
146         }
147
148         if (user.getDescription() != null) {
149             savedUser.setDescription(user.getDescription());
150         }
151         if (user.getName() != null) {
152             savedUser.setName(user.getName());
153         }
154         if (user.isEnabled() != null) {
155             savedUser.setEnabled(user.isEnabled());
156         }
157         if (user.getEmail() != null) {
158             savedUser.setEmail(user.getEmail());
159         }
160         if (user.getPassword() != null) {
161             // If a new salt is provided, use it.  Otherwise, derive salt from existing.
162             String salt = user.getSalt();
163             if (salt == null) {
164                 salt = savedUser.getSalt();
165             }
166             savedUser.setPassword(SHA256Calculator.getSHA256(user.getPassword(), salt));
167         }
168
169         String query = "UPDATE users SET email = ?, password = ?, description = ?, enabled = ? WHERE userid = ?";
170         try (Connection conn = dbConnect();
171              PreparedStatement statement = conn.prepareStatement(query)) {
172             statement.setString(1, savedUser.getEmail());
173             statement.setString(2, savedUser.getPassword());
174             statement.setString(3, savedUser.getDescription());
175             statement.setInt(4, savedUser.isEnabled() ? 1 : 0);
176             statement.setString(5, savedUser.getUserid());
177             statement.executeUpdate();
178         } catch (SQLException s) {
179             throw new StoreException("SQL Exception : " + s);
180         }
181
182         return savedUser;
183     }
184
185     protected User deleteUser(String userid) throws StoreException {
186         userid = StringEscapeUtils.escapeHtml4(userid);
187         User savedUser = this.getUser(userid);
188         if (savedUser == null) {
189             return null;
190         }
191
192         String query = String.format("DELETE FROM USERS WHERE userid = '%s'", userid);
193         try (Connection conn = dbConnect();
194              Statement statement = conn.createStatement()) {
195             int deleteCount = statement.executeUpdate(query);
196             LOG.debug("deleted {} records", deleteCount);
197             return savedUser;
198         } catch (SQLException s) {
199             throw new StoreException("SQL Exception : " + s);
200         }
201     }
202 }