Skip to content

Commit

Permalink
fix: multiple linting and test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
darkmatter18 authored Mar 3, 2024
1 parent 9e37e1e commit d034344
Show file tree
Hide file tree
Showing 10 changed files with 1,313 additions and 1,322 deletions.
8 changes: 1 addition & 7 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,9 @@ module.exports = {
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
'plugin:react/recommended',
"plugin:react/jsx-runtime",
'google',
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.test.json',
'tsconfigRootDir': __dirname,
'ecmaVersion': 2018,
'sourceType': 'module'
},
'plugins': [
'react',
'@typescript-eslint',
Expand Down
2 changes: 1 addition & 1 deletion packages/react-auth-kit/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module.exports = {
'parserOptions': {
'project': './tsconfig.test.json',
'tsconfigRootDir': __dirname,
'ecmaVersion': 2018,
'ecmaVersion': 2021,
'sourceType': 'module'
}
};
127 changes: 65 additions & 62 deletions packages/react-auth-kit/src/RxTokenObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,10 @@ class TokenObject<T> {
this.authValue = this.initialToken_();
this.authSubject = new BehaviorSubject(this.authValue);

this.log(`[Auth Kit] - Initial Value ${this.authValue}`)
this.log(`[Auth Kit] - Initial Value ${this.authValue}`);

this.authSubject.subscribe({
next: this.syncTokens
next: this.syncTokens,
});
}

Expand Down Expand Up @@ -215,48 +215,48 @@ class TokenObject<T> {
set = (data: AuthKitSetState<T>) => {
// Before setting need to check the tokens.
this.log(`Set Function is called with`);
console.dir(data)
console.dir(data);
this.log(`Set Function Old Data`);
console.dir(this.value)
console.dir(this.value);

let obj = this.value;

if(data.userState !== undefined){
obj.userState = data.userState
if (data.userState !== undefined) {
obj.userState = data.userState;
}

if (data.auth) {
try{
let exp = this.getExpireDateTime(data.auth.token);
if(exp > new Date()){
try {
const exp = this.getExpireDateTime(data.auth.token);
if (exp > new Date()) {
obj = {
...obj,
auth: {
'token': data.auth.token,
'type': data.auth.type,
'expiresAt': exp,
},
isSignIn: true
isSignIn: true,
};
}
else{
} else {
obj = {
...obj,
auth: null,
isSignIn: false,
userState: null,
};
new AuthError("Given Auth Token is already expired.");
new AuthError('Given Auth Token is already expired.');
}
}
catch(e){
} catch (e) {
obj = {
...obj,
auth: null,
isSignIn: false,
userState: null,
};
new AuthError("Error pursing the Auth Token. Make sure you provided a valid JWT.");
new AuthError(
'Error pursing the Auth Token. Make sure you provided a valid JWT.',
);
}
} else if (data.auth === null) {
// sign out
Expand All @@ -269,44 +269,44 @@ class TokenObject<T> {
}

if (this.isUsingRefreshToken) {
if (obj.auth === null){
if (obj.auth === null) {
obj = {
...obj,
refresh: null,
};
}
else if (data.refresh) {
try{
let ref_exp = this.getExpireDateTime(data.refresh);
if(ref_exp > new Date()){
} else if (data.refresh) {
try {
const refreshExpireTime = this.getExpireDateTime(data.refresh);
if (refreshExpireTime > new Date()) {
obj = {
...obj,
refresh: {
'token': data.refresh,
'expiresAt': ref_exp,
'expiresAt': refreshExpireTime,
},
};
}
else {
} else {
obj = {
...obj,
auth: null,
isSignIn: false,
userState: null,
refresh: null
refresh: null,
};
new AuthError("Given Refresh Token is already expired.");
new AuthError('Given Refresh Token is already expired.');
}
}
catch(e){
} catch (e) {
obj = {
...obj,
auth: null,
isSignIn: false,
userState: null,
refresh: null
refresh: null,
};
new AuthError("Error pursing the Auth Token. Make sure you provided a valid JWT.");
new AuthError(
'Error pursing the Auth Token.'+
' Make sure you provided a valid JWT.',
);
}
} else if (data.refresh === null) {
obj = {
Expand All @@ -316,7 +316,7 @@ class TokenObject<T> {
}
}
this.log(`[Auth Kit] - Set Function New Data`);
this.log(obj)
this.log(obj);
this.authValue = obj;
this.authSubject.next(obj);
};
Expand Down Expand Up @@ -423,31 +423,31 @@ class TokenObject<T> {
): AuthKitStateInterface<T> => {
this.log('checkTokenExist_ is called');
this.log(
`Params: authToken: ${authToken}, authTokenType: ${authTokenType},
stateCookie: ${stateCookie}, refreshToken: ${refreshToken}`
)
`Params: authToken: ${authToken}, authTokenType: ${authTokenType},
stateCookie: ${stateCookie}, refreshToken: ${refreshToken}`,
);

try {
// Work on refresh first
let refresh;
if (this.isUsingRefreshToken && !!refreshToken) {
this.log(
`checkTokenExist - isUsingRefreshToken
= ${this.isUsingRefreshToken} refrehToken - ${refreshToken}`
`checkTokenExist - isUsingRefreshToken
= ${this.isUsingRefreshToken} refrehToken - ${refreshToken}`,
);
// If the refresh token is tampered,
// then it'll stop the execution and will go at catch.
const refreshTokenExpiresAt = this.getExpireDateTime(refreshToken);
if (refreshTokenExpiresAt < new Date()) {
this.log(
`checkTokenExist - refresh token is expired
${refreshTokenExpiresAt} ${new Date()}`
`checkTokenExist - refresh token is expired
${refreshTokenExpiresAt} ${new Date()}`,
);
refresh = null;
} else {
this.log(
`checkTokenExist - new refresh token is assigned
${refreshToken}`
`checkTokenExist - new refresh token is assigned
${refreshToken}`,
);
refresh = {
token: refreshToken,
Expand All @@ -456,8 +456,8 @@ class TokenObject<T> {
}
} else {
this.log(
`checkTokenExist - Refesh Token is invalid or not using
refresh feature ${this.isUsingRefreshToken} ${refreshToken}`
`checkTokenExist - Refesh Token is invalid or not using
refresh feature ${this.isUsingRefreshToken} ${refreshToken}`,
);
refresh = null;
}
Expand All @@ -469,7 +469,7 @@ class TokenObject<T> {
// And will delete any token, if there's any
if (this.isUsingRefreshToken && !refresh) {
this.log(
`checkTokenExist - Removing Refresh Token`
`checkTokenExist - Removing Refresh Token`,
);
this.removeAllToken();
return {
Expand All @@ -487,51 +487,55 @@ class TokenObject<T> {
if (!!authToken && !!authTokenType && !!stateCookie) {
// Using a local Try catch, as we don't want
// the auth token to make the refrsh token to be null;
this.log(`checkTokenExist - authToken, authTokenType, stateCookie exists`);
this.log(
`checkTokenExist - authToken, authTokenType, stateCookie exists`,
);
try {
const expiresAt = this.getExpireDateTime(authToken);
if (expiresAt < new Date()) {
this.log(
`checkTokenExist - auth token is expired
${expiresAt} ${new Date()}`
`checkTokenExist - auth token is expired
${expiresAt} ${new Date()}`,
);
auth = null;
authState = null;
} else {
try{
authState = JSON.parse(stateCookie.replaceAll("\\", "")) as T;
try {
authState = JSON.parse(stateCookie.replaceAll('\\', '')) as T;
auth = {
token: authToken,
type: authTokenType,
expiresAt: expiresAt,
};
}
catch (err) {
} catch (err) {
this.log('state cookie JSON parsing failed');
this.log(err);
auth = null;
authState = null;
authState = null;
}
}
} catch (e) {
this.log(
`checkTokenExist - auth token or auth state is invalid
${authToken} ${stateCookie}`
`checkTokenExist - auth token or auth state is invalid
${authToken} ${stateCookie}`,
);
this.log(e);
auth = null;
authState = null;
}
} else {
this.log(`checkTokenExist - authToken, authTokenType, stateCookie doesn't exists`);
this.log(
`checkTokenExist `+
`- authToken, authTokenType, stateCookie doesn't exists`,
);
auth = null;
authState = null;
}


if (refresh) {
if (!!auth && !!authState) {
this.log("checkTokenExist - Returning auth and refrsh");
this.log('checkTokenExist - Returning auth and refrsh');
this.log({
auth: auth,
refresh: refresh,
Expand All @@ -547,7 +551,7 @@ class TokenObject<T> {
isSignIn: true,
};
}
this.log("checkTokenExist - Removing Auth Token")
this.log('checkTokenExist - Removing Auth Token');
this.removeAuth();
this.log({
auth: null,
Expand All @@ -564,7 +568,7 @@ class TokenObject<T> {
isSignIn: false,
};
} else if (!this.isUsingRefreshToken && !!auth && !!authState) {
this.log("checkTokenExist - Returning auth");
this.log('checkTokenExist - Returning auth');
this.log({
auth: auth,
refresh: null,
Expand Down Expand Up @@ -722,8 +726,7 @@ class TokenObject<T> {
secure: this.cookieSecure,
});
}
}
else if (
} else if (
this.isUsingRefreshToken &&
!!this.refreshTokenName && !!refreshToken
) {
Expand Down Expand Up @@ -850,11 +853,11 @@ class TokenObject<T> {

/**
* Log function
* @param msg to log
* @param msg - The Message to log to the console
*/
private log = (msg: any, ...optionalParams: any[]): void => {
if (this.debug) {
console.log(`[Auth Kit] - ${msg}`, optionalParams)
console.log(`[Auth Kit] - ${msg}`, optionalParams);
}
};
}
Expand Down
44 changes: 44 additions & 0 deletions packages/react-auth-kit/src/__tests__/AuthContext.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//@ts-ignore
import React from 'react';

import AuthKitContext from '../AuthContext';
import {useReactAuthKit} from '../AuthContext';
import {render} from '@testing-library/react';
import Cookies from 'js-cookie';
import TokenObject from '../RxTokenObject';

test('All Expected Exports are there', ()=>{
expect(AuthKitContext).toBeTruthy();
expect(useReactAuthKit).toBeTruthy();
});

test('Testing Conext Workflow', ()=>{
const TestComponent = () => {
const c = useReactAuthKit();
return <div id="test"> {JSON.stringify(c.value)} </div>;
};

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM'+
'0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiZXhwIjo4MDA4NjA1MTk1fQ.ijw60'+
'3AjpAqNwnUXmv6YB5L6m5aL-llIgBsTJo-k2r8';
Cookies.set('__', token);

const tokenObject = new TokenObject<object>(
'__',
'cookie',
null,
false,
window.location.hostname,
window.location.protocol === 'https:',
);


render(
<AuthKitContext.Provider value={tokenObject as any}>
<TestComponent/>
</AuthKitContext.Provider>,
);

const data = document.querySelector('#test');
expect(data?.innerHTML).toEqual(` ${JSON.stringify(tokenObject.value)} `);
});
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ describe('AuthProvider renders successfully', ()=>{
});
});
});

describe('Authprovider with refresh Token', ()=> {
afterEach(() => {
jest.useRealTimers();
Expand Down
Loading

0 comments on commit d034344

Please sign in to comment.