Skip to content

Commit

Permalink
Adds api endpoints in UI to fetch access token and logout
Browse files Browse the repository at this point in the history
Adds `/user/accesstoken` endpoint on UI to get the access
toke for user to show it on user profile
Adds `/user/logout` to delete the http cookie on server

Sigend-off-by: Shiv Verma <[email protected]>
  • Loading branch information
pratap0007 committed May 9, 2022
1 parent 89637eb commit 73b9b4f
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 122 deletions.
91 changes: 50 additions & 41 deletions ui/src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import axios from 'axios';
import { API_URL, AUTH_BASE_URL, API_VERSION } from '../config/constants';
import { API_URL, API_VERSION } from '../config/constants';
import { ICategory } from '../store/category';
import { IResource, IVersion } from '../store/resource';
import { ITokenInfo, IUserProfile } from '../store/auth';
import { ICatalog } from '../store/catalog';
import { IProvider } from '../store/provider';

interface Token {
token: string;
refreshInterval: string;
expiresAt: number;
}
Expand All @@ -21,6 +20,14 @@ export interface AuthResponse {
data: TokenData;
}

export interface AccessTokenResponse {
data: string;
}

export interface LogoutResponse {
data: boolean;
}

export interface Rating {
rating: number;
}
Expand All @@ -34,12 +41,14 @@ export interface Api {
authentication(authCode: string): Promise<AuthResponse>;
readme(resourceKey: string, version: string): Promise<string>;
yaml(resourceKey: string, version: string): Promise<string>;
getRating(resourceId: number, token: string): Promise<Rating>;
setRating(resourceId: number, token: string, rating: number): Promise<void | null>;
getRefreshToken(refreshToken: string): Promise<ITokenInfo>;
getAccessToken(accessToken: string): Promise<ITokenInfo>;
profile(token: string): Promise<IUserProfile>;
getRating(resourceId: number): Promise<Rating>;
setRating(resourceId: number, rating: number): Promise<void | null>;
getRefreshToken(): Promise<ITokenInfo>;
getAccessToken(): Promise<ITokenInfo>;
profile(): Promise<IUserProfile>;
providers(): Promise<IProvider>;
logout(): Promise<LogoutResponse>;
accessToken(): Promise<AccessTokenResponse>;
}

export class Hub implements Api {
Expand Down Expand Up @@ -70,7 +79,7 @@ export class Hub implements Api {
async authentication(authCode: string) {
try {
return axios
.post(`${AUTH_BASE_URL}/auth/login?code=${authCode}`)
.post(`/auth/login?code=${authCode}`)
.then((response) => response.data)
.catch((err) => Promise.reject(err.response));
} catch (err) {
Expand Down Expand Up @@ -119,48 +128,33 @@ export class Hub implements Api {
}
}

async getRating(resourceId: number, token: string) {
async getRating(resourceId: number) {
try {
return axios
.get(`${API_URL}/resource/${resourceId}/rating`, {
headers: {
Authorization: `Bearer ${token}`
}
})
.get(`/resource/${resourceId}/rating`)
.then((response) => response.data)
.catch((err) => Promise.reject(err.response));
} catch (err) {
return err;
}
}

async setRating(resourceId: number, token: string, rating: number) {
async setRating(resourceId: number, rating: number) {
try {
return axios
.put(
`${API_URL}/resource/${resourceId}/rating`,
{ rating: rating },
{
headers: {
Authorization: `Bearer ${token}`
}
}
)
.put(`/resource/${resourceId}/rating`, { rating: rating })
.then((response) => response.data)
.catch((err) => Promise.reject(err.response));
} catch (err) {
return err;
}
}

async getRefreshToken(refreshToken: string) {
async getRefreshToken() {
try {
return axios({
method: 'post',
url: `${AUTH_BASE_URL}/user/refresh/refreshtoken`,
headers: {
Authorization: `Bearer ${refreshToken}`
}
url: `/user/refresh/refreshtoken`
})
.then((response) => response.data)
.catch((err) => Promise.reject(err.response));
Expand All @@ -169,14 +163,11 @@ export class Hub implements Api {
}
}

async getAccessToken(refreshToken: string) {
async getAccessToken() {
try {
return axios({
method: 'post',
url: `${AUTH_BASE_URL}/user/refresh/accesstoken`,
headers: {
Authorization: `Bearer ${refreshToken}`
}
url: `/user/refresh/accesstoken`
})
.then((response) => response.data)
.catch((err) => Promise.reject(err.response));
Expand All @@ -185,14 +176,10 @@ export class Hub implements Api {
}
}

async profile(token: string) {
async profile() {
try {
return axios
.get(`${AUTH_BASE_URL}/user/info`, {
headers: {
Authorization: `Bearer ${token}`
}
})
.get(`/user/info`)
.then((response) => response.data)
.catch((err) => Promise.reject(err.response));
} catch (err) {
Expand All @@ -202,9 +189,31 @@ export class Hub implements Api {

async providers() {
try {
return axios.get(`${AUTH_BASE_URL}/auth/providers`).then((response) => response.data);
return axios.get(`/auth/providers`).then((response) => response.data);
} catch (err) {
return err.response;
}
}

async logout() {
try {
return axios
.post(`/user/logout `)
.then((response) => response.data)
.catch((err) => Promise.reject(err.response));
} catch (err) {
return err;
}
}

async accessToken() {
try {
return axios
.post(`/user/accesstoken`)
.then((response) => response.data)
.catch((err) => Promise.reject(err.response));
} catch (err) {
return err;
}
}
}
17 changes: 16 additions & 1 deletion ui/src/api/testutil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as fs from 'fs';
import { ICategory } from '../store/category';
import { IResource, IVersion } from '../store/resource';
import { ITokenInfo, IUserProfile } from '../store/auth';
import { Api, AuthResponse } from './';
import { Api, AuthResponse, AccessTokenResponse, LogoutResponse } from './';
import { ICatalog } from '../store/catalog';
import { IProvider } from '../store/provider';

Expand Down Expand Up @@ -130,4 +130,19 @@ export class FakeHub implements Api {
setTimeout(() => resolve(ret()), 1000);
});
}

async logout() {
const data = `${this.dataDir}/provider.json`;
const ret = () => JSON.parse(fs.readFileSync(data).toString());
return new Promise<LogoutResponse>((resolve) => {
setTimeout(() => resolve(ret()), 1000);
});
}
async accessToken() {
const data = `${this.dataDir}/existing_token.json`;
const ret = () => JSON.parse(fs.readFileSync(data).toString());
return new Promise<AccessTokenResponse>((resolve) => {
setTimeout(() => resolve(ret()), 1000);
});
}
}
17 changes: 7 additions & 10 deletions ui/src/containers/UserProfile/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const UserProfile: React.FC = observer(() => {

useEffect(() => {
user.getProfile();
user.accessToken();
}, [user.profile.userName]);

const triggerInterval = useCallback(() => {
Expand All @@ -32,9 +33,6 @@ const UserProfile: React.FC = observer(() => {
// To get a new refresh token
// Update the refresh token before 20 seconds of current refresh token's expiry time
const tempRefreshId = window.setInterval(() => {
if (!user.isAuthenticated) {
clearInterval(tempRefreshId);
}
user.updateRefreshToken();
}, refreshTokenInterval - 20000);
setRefreshId(tempRefreshId);
Expand All @@ -45,9 +43,6 @@ const UserProfile: React.FC = observer(() => {
// To get a new access token
// Update the access token before 10 seconds of current access token's expiry time
const tempAccessId = window.setInterval(() => {
if (!user.isAuthenticated) {
clearInterval(tempAccessId);
}
user.updateAccessToken();
}, accessTokenInterval - 10000);
setAccessId(tempAccessId);
Expand All @@ -63,11 +58,13 @@ const UserProfile: React.FC = observer(() => {

const hubLogout = () => {
user.logout();
localStorage.clear();
clearInterval(refreshId);
clearInterval(accessId);
};

setTimeout(() => {
localStorage.clear();
}, 1000);
};
const onToggle = (isOpen: React.SetStateAction<boolean>) => set(isOpen);

const dropdownItems = [
Expand All @@ -76,7 +73,7 @@ const UserProfile: React.FC = observer(() => {
<DropdownItem key="copyToken" onClick={() => setIsModalOpen(!isModalOpen)}>
Copy Hub Token
</DropdownItem>,
<DropdownItem key="logout" onClick={hubLogout}>
<DropdownItem key="logout" onClick={() => hubLogout()}>
Logout
</DropdownItem>
];
Expand Down Expand Up @@ -104,7 +101,7 @@ const UserProfile: React.FC = observer(() => {
<hr />
<div>
<ClipboardCopy isReadOnly variant={ClipboardCopyVariant.expansion}>
{user.accessTokenInfo.token}
{user.existingToken.token}
</ClipboardCopy>
</div>
</Modal>
Expand Down
Loading

0 comments on commit 73b9b4f

Please sign in to comment.