1   /*
2    * Copyright 2017 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package com.linecorp.centraldogma.server.internal.admin.auth;
18  
19  import static java.util.Objects.requireNonNull;
20  
21  import javax.annotation.Nullable;
22  
23  import com.google.common.annotations.VisibleForTesting;
24  
25  import com.linecorp.armeria.common.RequestContext;
26  import com.linecorp.armeria.server.ServiceRequestContext;
27  import com.linecorp.centraldogma.common.Author;
28  import com.linecorp.centraldogma.server.metadata.User;
29  
30  import io.netty.util.AttributeKey;
31  
32  /**
33   * A utility class to manage a {@link User} and its {@link Author} instances of the current login user.
34   */
35  public final class AuthUtil {
36  
37      @VisibleForTesting
38      public static final AttributeKey<User> CURRENT_USER =
39              AttributeKey.valueOf(AuthUtil.class, "CURRENT_USER");
40  
41      public static Author currentAuthor(ServiceRequestContext ctx) {
42          final User user = ctx.attr(CURRENT_USER);
43          assert user != null;
44          return user == User.DEFAULT ? Author.DEFAULT
45                                      : new Author(user.name(), user.email());
46      }
47  
48      public static Author currentAuthor() {
49          return currentAuthor(RequestContext.current());
50      }
51  
52      public static User currentUser(ServiceRequestContext ctx) {
53          return ctx.attr(CURRENT_USER);
54      }
55  
56      public static User currentUser() {
57          return currentUser(RequestContext.current());
58      }
59  
60      @Nullable
61      public static User currentUserOrNull() {
62          final ServiceRequestContext currentOrNull = ServiceRequestContext.currentOrNull();
63          if (currentOrNull == null) {
64              return null;
65          }
66          return currentUser(currentOrNull);
67      }
68  
69      public static void setCurrentUser(ServiceRequestContext ctx, User currentUser) {
70          requireNonNull(ctx, "ctx");
71          requireNonNull(currentUser, "currentUser");
72          ctx.setAttr(CURRENT_USER, currentUser);
73      }
74  
75      private AuthUtil() {}
76  }