1 /*
2  * SessionScope.java
3  *
4  * Copyright (C) 2021 by RStudio, PBC
5  *
6  * Unless you have received this program directly from RStudio pursuant
7  * to the terms of a commercial license agreement with RStudio, then
8  * this program is licensed to you under the terms of version 3 of the
9  * GNU Affero General Public License. This program is distributed WITHOUT
10  * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
11  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
12  * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
13  *
14  */
15 package org.rstudio.studio.client.application.model;
16 
17 import org.rstudio.core.client.dom.DomUtils;
18 
19 /**
20  * Utility to crack apart components of a full or partially qualified
21  * scope as found in session Urls.
22  *
23  * Assumes the session ID is present. The userId+ProjectId component
24  * is optional.
25  *
26  * Caller needs to check each field for null.
27  */
28 public class SessionScope
29 {
SessionScope(String sessionScope)30    public SessionScope(String sessionScope)
31    {
32       userId_ = null;
33       projectId_ = null;
34       sessionId_ = null;
35 
36       if (sessionScope.length() == SESSION_ID_LEN)
37       {
38          sessionId_ = sessionScope;
39          return;
40       }
41 
42       if (sessionScope.length() == (USER_ID_LEN + PROJECT_ID_LEN + SESSION_ID_LEN))
43       {
44          userId_ = sessionScope.substring(0, USER_ID_LEN);
45          projectId_ = sessionScope.substring(USER_ID_LEN, USER_ID_LEN + PROJECT_ID_LEN);
46          sessionId_ = sessionScope.substring(USER_ID_LEN + PROJECT_ID_LEN);
47       }
48 
49       // Otherwise leave everything null.
50    }
51 
52    /**
53     * Parse session scope from a session URL.
54     */
scopeFromUrl(String url)55    public static SessionScope scopeFromUrl(String url)
56    {
57       String path = DomUtils.getUrlPath(url);
58 
59       // remove trailing slash, if any
60       if (path.endsWith("/"))
61          path = path.substring(0, path.length() - 1);
62 
63       // everything after final slash, if any
64       int pos = path.lastIndexOf('/');
65       if (pos >= 0)
66          path = path.substring(pos + 1);
67 
68       return new SessionScope(path);
69    }
70 
getUserId()71    public String getUserId()
72    {
73       return userId_;
74    }
75 
getProjectId()76    public String getProjectId()
77    {
78       return projectId_;
79    }
80 
getSessionId()81    public String getSessionId()
82    {
83       return sessionId_;
84    }
85 
86    public static final int USER_ID_LEN = 5;
87    public static final int PROJECT_ID_LEN= 8;
88    public static final int SESSION_ID_LEN = 8;
89 
90    private String userId_;
91    private String projectId_;
92    private String sessionId_;
93 }
94