001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.petstore.console.users;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022
023import org.apache.juneau.commons.beanquery.*;
024import org.apache.juneau.http.*;
025import org.apache.juneau.http.response.*;
026import org.apache.juneau.marshall.collections.*;
027import org.apache.juneau.petstore.console.*;
028import org.apache.juneau.petstore.console.pages.*;
029import org.apache.juneau.petstore.dto.*;
030import org.apache.juneau.petstore.service.*;
031import org.apache.juneau.rest.server.*;
032import org.apache.juneau.console.datatables.*;
033import org.apache.juneau.console.datatables.adapter.*;
034import org.apache.juneau.rest.server.view.*;
035import org.apache.juneau.rest.server.view.freemarker.*;
036import org.apache.juneau.console.views.*;
037import org.apache.juneau.console.widgets.*;
038
039/**
040 * The Users page and its endpoints.  The password is write-only: every read goes through {@link UserView}, which has
041 * no password, so it never leaves the server; an update with no password keeps the stored one.
042 *
043 * <h2 class='section'>Example:</h2>
044 * <p class='bjava'>
045 *    <jc>// The wire shape of a create (JSON5): the password is accepted but never echoed.</jc>
046 *    { username:<js>'newbie'</js>, firstName:<js>'New'</js>, lastName:<js>'Bie'</js>, password:<js>'s3cret'</js> }
047 * </p>
048 * <p class='bcode'>
049 *    &lt;@card type="datatables" id="users"&gt;
050 *    { dataMode:'server', dataUrl:'/console/users/query', columns:[{key:'username', label:'Username'}, ...] }
051 *    &lt;/@card&gt;
052 * </p>
053 */
054@Rest(path="/users", title="Users")
055@SuppressWarnings({
056   "java:S110", // Inheritance depth comes from the BasicRestServlet hierarchy, not this page.
057   "java:S1192" // Route paths and field names repeat as inline literals by design.
058})
059public class UsersRest extends PetstoreConsolePage implements RowDetailMixin {
060
061   private static final long serialVersionUID = 1L;
062
063   /** The query context over {@link UserView}, so the password is neither searchable nor serialized. */
064   private static final InMemoryBeanQueryContext<UserView> VIEW_QUERY = InMemoryBeanQueryContext.create(UserView.class).build();
065
066   /**
067    * A user as the console shows it: everything but the password.
068    *
069    * <h2 class='section'>Example:</h2>
070    * <p class='bcode'>
071    *    { username:'mwatson', firstName:'Mary', lastName:'Watson', userStatus:'ACTIVE' }
072    * </p>
073    *
074    * @param username The username (primary key).
075    * @param firstName The first name.
076    * @param lastName The last name.
077    * @param userStatus The account status.
078    */
079   public record UserView(String username, String firstName, String lastName, UserStatus userStatus) {
080
081      /**
082       * @param u The stored user.
083       * @return Its password-free view.
084       */
085      public static UserView of(User u) {
086         return new UserView(u.getUsername(), u.getFirstName(), u.getLastName(), u.getUserStatus());
087      }
088   }
089
090   /**
091    * The Users page.
092    *
093    * @param req The request; {@code ?builder} renders the builder twin.
094    * @return The page.
095    */
096   @RestGet(path="/")
097   public View page(RestRequest req) {
098      return builder(req) ? twin(req, UsersPageBuilders.users()) : FreemarkerView.of("users.ftlh");
099   }
100
101   @SuppressWarnings({
102      "java:S1948" // Servlets are nominally Serializable, but these REST resources are never serialized.
103   })
104   private final RowDetail userDetail = RowDetails.user(this::lookup);
105
106   @Override
107   public Collection<RowDetail> rowDetails() {
108      return List.of(userDetail);
109   }
110
111   private UserView lookup(String username) {
112      var u = store().getUser(username);
113      return u == null ? null : UserView.of(u);
114   }
115
116   /**
117    * The Orders tab of the user row detail: the orders a user placed from the console, by id.
118    *
119    * @param username The username.
120    * @return The orders, whose create was audited under this user.
121    * @throws NotFound If {@code username} is missing or names no user.
122    */
123   @RestGet(path="/orders/rows")
124   public List<Order> orderRows(@Query("username") String username) {
125      var u = require(username == null ? "" : username);
126      var actor = "console:" + u.getUsername();
127      var ids = store().getAudit().stream()
128         .filter(x -> "Order".equals(x.getEntity()) && "CREATE".equals(x.getAction()) && actor.equals(x.getActor()))
129         .map(AuditEntry::getEntityId).collect(java.util.stream.Collectors.toSet());
130      return store().getOrders().stream().filter(o -> ids.contains(String.valueOf(o.getId()))).sorted(Comparator.comparingLong(Order::getId)).toList();
131   }
132
133   /**
134    * The add/edit dialog form.  The password field is write-only: it is never pre-filled.
135    *
136    * @param username The user to edit, or <jk>null</jk> to add.
137    * @return The modal.
138    * @throws NotFound If {@code username} names no user.
139    */
140   @RestGet(path="/form")
141   public ModalDef form(@Query("username") String username) {
142      var u = username == null ? new User() : require(username);
143      var form = FormDef.create();
144      if (username == null)
145         form.field(FormDef.Input.of("username", "Username", "text").required());
146      form.field(FormDef.Input.of("firstName", "First name", "text").value(u.getFirstName()));
147      form.field(FormDef.Input.of("lastName", "Last name", "text").value(u.getLastName()));
148      var password = FormDef.Input.of("password", "Password", "password");
149      form.field(username == null ? password.required().help("Write-only; it is never shown again") : password.help("Leave blank to keep the current password"));
150      return ModalDef.create(username == null ? "Add user" : f("Edit '%s'", username)).form(form);
151   }
152
153   /**
154    * Server-mode DataTables query over all users, as password-free views.
155    *
156    * @param req The DataTables request.
157    * @return One page of users, or a 200 {@code error} envelope for a malformed search expression.
158    */
159   @RestPost(path="/query")
160   public DataTablesResults<UserView> query(@Content DataTablesRequest req) {
161      try (var s = VIEW_QUERY.getSession(store().getUsers().stream().map(UserView::of).toList())) {
162         return DataTablesQuery.run(req, s);
163      } catch (BeanQuerySyntaxException e) {
164         return DataTablesResults.error(req.getDraw(), e.getMessage());
165      }
166   }
167
168   /**
169    * @param username The username.
170    * @return The user, without the password.
171    * @throws NotFound If it does not exist.
172    */
173   @RestGet(path="/{username}")
174   public UserView get(@Path("username") String username) {
175      return UserView.of(require(username));
176   }
177
178   /**
179    * Creates a user.
180    *
181    * @param req The request (write gate, audit actor).
182    * @param body {@code {username, firstName, lastName, password}}, either plain or as the dialog envelope {@code {fields:{...}}}.
183    * @return The result toast, carrying the user without the password.
184    * @throws BadRequest On a blank username.
185    * @throws Conflict If the username is taken.
186    */
187   @RestPost(path="/")
188   public ActionResult create(RestRequest req, @Content JsonMap body) {
189      var actor = ConsoleWrites.actor(req);
190      var f = fields(body);
191      var username = f.getString("username");
192      if (ib(username))
193         throw new BadRequest("Username must not be blank");
194      if (store().getUser(username) != null)
195         throw new Conflict("User '%s' already exists", username);
196      var u = new User().setUsername(username).setFirstName(f.getString("firstName")).setLastName(f.getString("lastName"))
197         .setPassword(f.getString("password")).setUserStatus(status(f, UserStatus.ACTIVE));
198      store().createUser(u, actor);
199      return ActionResult.success(UserView.of(u)).message(f("Added '%s'", username));
200   }
201
202   /**
203    * Updates a user.  A field left out of the body, and a null or blank password, keep their stored values.
204    *
205    * @param req The request.
206    * @param username The username.
207    * @param body The new state, either plain or as the dialog envelope {@code {fields:{...}}}.
208    * @return The result toast, carrying the user without the password.
209    * @throws NotFound If the user does not exist.
210    */
211   @RestPut(path="/{username}")
212   public ActionResult update(RestRequest req, @Path("username") String username, @Content JsonMap body) {
213      var actor = ConsoleWrites.actor(req);
214      var old = require(username);
215      var f = fields(body);
216      var pw = f.getString("password");
217      var u = new User().setUsername(username)
218         .setFirstName(f.containsKey("firstName") ? f.getString("firstName") : old.getFirstName())
219         .setLastName(f.containsKey("lastName") ? f.getString("lastName") : old.getLastName())
220         .setEmail(old.getEmail()).setPhone(old.getPhone())
221         .setUserStatus(status(f, old.getUserStatus()))
222         .setPassword(pw == null || pw.isBlank() ? old.getPassword() : pw);
223      store().updateUser(u, actor);
224      return ActionResult.success(UserView.of(u)).message(f("Saved '%s'", username));
225   }
226
227   /**
228    * Deletes a user.
229    *
230    * @param req The request.
231    * @param username The username.
232    * @return The result toast.
233    * @throws NotFound If the user does not exist.
234    */
235   @RestDelete(path="/{username}")
236   public ActionResult delete(RestRequest req, @Path("username") String username) {
237      var actor = ConsoleWrites.actor(req);
238      require(username);
239      store().deleteUser(username, actor);
240      return ActionResult.success(null).message(f("Deleted '%s'", username));
241   }
242
243   private User require(String username) {
244      var u = store().getUser(username);
245      if (u == null)
246         throw new NotFound("Unknown user '%s'", username);
247      return u;
248   }
249
250   /** Unwraps the dialog envelope ({@code fields}) if present; otherwise the body is the form itself. */
251   private static JsonMap fields(JsonMap body) {
252      if (body == null)
253         return new JsonMap();
254      var f = body.getMap("fields");
255      return f != null ? f : body;
256   }
257
258   private static UserStatus status(JsonMap f, UserStatus dflt) {
259      var s = f.getString("userStatus");
260      if (ib(s))
261         return dflt;
262      try {
263         return UserStatus.valueOf(s);
264      } catch (IllegalArgumentException e) {
265         throw new BadRequest("Unknown user status '%s'", s);
266      }
267   }
268}