Skip to content

Commit

Permalink
Filtering out the patient and doctor roles for login
Browse files Browse the repository at this point in the history
  • Loading branch information
kiran-rean committed Aug 23, 2024
1 parent 99011d2 commit 814bb2b
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 73 deletions.
2 changes: 1 addition & 1 deletion src/lib/types/domain.models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export interface LoginModel {
Phone ?: string;
Password ?: string;
Otp ?: string;
LoginRoleId ?: string;
LoginRoleId ?: number;
};

export interface ResponseData {
Expand Down
90 changes: 40 additions & 50 deletions src/routes/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { login } from './api/services/reancare/user';
import { getUserRoles } from './api/services/reancare/types';
import { zfd } from 'zod-form-data';
import { z } from 'zod';
import { getPersonRolesForEmail, getPersonRolesForPhone } from './api/services/reancare/persons';

////////////////////////////////////////////////////////////////

Expand All @@ -31,52 +32,7 @@ export const load: PageServerLoad = async (event: RequestEvent) => {

//////////////////////////////////////////////////////////////////////////////////////////

// export const actions = {
// login: async (event: RequestEvent) => {
// const request = event.request;
// const data = await request.formData(); // or .json(), or .text(), etc
// console.log(Object.fromEntries(data));

// const username = data.has('username') ? (data.get('username') as string) : null;
// const password = data.has('password') ? (data.get('password') as string) : null;
// const loginRoleId_ = data.has('loginRoleId') ? data.get('loginRoleId') : null;
// const loginRoleId = loginRoleId_.valueOf() as number;
// if (!username || !password) {
// throw error(400, `Username or password are not valid!`);
// }
// console.log(`data....... = ${JSON.stringify(request, null, 2)}`);
// // const response = await login(username, password, loginRoleId ?? 1);
// const response = await login(username, password);
// if (response.Status === 'failure' || response.HttpCode !== 200) {
// console.log(response.Message);
// throw redirect(303, '/', errorMessage(response.Message), event);
// }
// console.log('response ....', response);
// const user = response.Data.User;
// user.SessionId = response.Data.SessionId;
// const accessToken = response.Data.AccessToken;
// const refreshToken = response.Data.RefreshToken;
// const expiryDate = new Date(response.Data.SessionValidTill);
// const sessionId = response.Data.SessionId;
// const userId: string = response.Data.User.id;

// const session = await SessionManager.constructSession(user, accessToken, expiryDate, refreshToken);
// if (!session) {
// console.log(`Session cannot be constructed!`);
// throw redirect(303, `/`, errorMessage(`Use login session cannot be created!`), event);
// }
// console.log('Session - ' + JSON.stringify(session, null, 2));
// const userSession = await SessionManager.addSession(session.sessionId, session);
// console.log(JSON.stringify(userSession, null, 2));

// CookieUtils.setCookieHeader(event, 'sessionId', sessionId);

// throw redirect(303, `/users/${userId}/home`, successMessage(`Login successful!`), event);
// }
// };

const loginSchema = zfd.formData({
roleId: z.string(),
const LoginSchema = zfd.formData({
password: z.string(),
username: z.string().optional(),
email: z.string().optional(),
Expand All @@ -90,14 +46,13 @@ export const actions = {
const request = event.request;
const data = await request.formData();
const formData = Object.fromEntries(data);
type loginSchema = z.infer<typeof loginSchema>;
type loginSchema = z.infer<typeof LoginSchema>;

let result: loginSchema = {
roleId: '',
password: ''
};
try {
result = loginSchema.parse(formData);
result = LoginSchema.parse(formData);
console.log('result', result);
} catch (err: any) {
const { fieldErrors: errors } = err.flatten();
Expand All @@ -110,13 +65,47 @@ export const actions = {
}

let phone;
const allRoles: PersonRole[] = await getUserRoles();
let availableRoles: PersonRole = [];
let filteredRoles: PersonRole = [];
let loginRoleId = null;

if (result.phone && result.countryCode){
phone = result.countryCode + '-' + result.phone;
var res_ = availableRoles = await getPersonRolesForPhone(phone);
availableRoles = res_.Data?.Roles ?? [];
}
else if (result.email){
var res_ = await getPersonRolesForEmail(result.email);
availableRoles = res_.Data?.Roles ?? [];
}

if (availableRoles.length > 0) {
filteredRoles = availableRoles.filter((x) => x.RoleName !== 'Doctor' && x.RoleName !== 'Patient');
if (filteredRoles.length > 0) {
loginRoleId = filteredRoles[0].id;
}
}
else {
if (allRoles.length > 0) {
if (result.username && result.username === 'admin') {
filteredRoles = allRoles.filter((x) => x.RoleName === 'System admin');
if (filteredRoles.length > 0) {
loginRoleId = filteredRoles[0].id;
}
}
else {
// KK: Should we throw an error here?
filteredRoles = allRoles.filter((x) => x.RoleName === 'System user' || x.RoleName === 'Tenant admin' || x.RoleName === 'Tenant user');
if (filteredRoles.length > 0) {
loginRoleId = filteredRoles[0].id;
}
}
}
}

const response = await login(
result.roleId,
loginRoleId,
result.password,
result.username,
result.email,
Expand All @@ -133,6 +122,7 @@ export const actions = {
if (!['System admin','System user','Tenant admin','Tenant user'].includes(response.Data.User.Role.RoleName)) {
throw redirect(303, '/', errorMessage("Permission Denied!"), event);
}

console.log('response ....', response);
const user = response.Data.User;
user.SessionId = response.Data.SessionId;
Expand Down
35 changes: 17 additions & 18 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,21 @@
getSystemName,
} from '$lib/themes/theme.selector';
import { errorMessage } from '$lib/utils/message.utils';
import { z } from 'zod';
import toast from 'svelte-french-toast';
import PasswordInput from '$lib/components/input/password.input.svelte';
import { z } from 'zod';
import toast from 'svelte-french-toast';
import PasswordInput from '$lib/components/input/password.input.svelte';
/////////////////////////////////////////////////////////////////////////////
const logoImageSource = getPublicLogoImageSource();
const footerText = `© ${new Date().getFullYear()} ${getPublicFooterText()}`;
const footerLink = getPublicFooterLink();
const footerText = `© ${new Date().getFullYear()} ${getPublicFooterText()}`;
const footerLink = getPublicFooterLink();
export let data: PageServerData;
personRolesStore.set(data.roles);
LocalStorageUtils.setItem('personRoles', JSON.stringify(data.roles));
let personRoles = [];
let loginRoleId = 1;
let showForgotPassword = false;
let showResetPassword = false;
Expand All @@ -34,15 +33,15 @@
let newPassword = '';
let confirmPassword = '';
let errors: Record<string, string[]> = {};
let activeTab = 'username';
let activeTab = 'email';
if (browser) {
const tmp = LocalStorageUtils.getItem('personRoles');
personRoles = JSON.parse(tmp);
const adminRole = personRoles?.find((x) => x.RoleName === 'System admin');
if (adminRole) {
loginRoleId = adminRole.id;
}
// const adminRole = personRoles?.find((x) => x.RoleName === 'System admin');
// if (adminRole) {
// loginRoleId = adminRole.id;
// }
LocalStorageUtils.removeItem('prevUrl');
}
Expand Down Expand Up @@ -140,7 +139,7 @@
<form on:submit|preventDefault={handleResetPassword}>
<label class="hidden">
<span class="text-primary-500">Email</span>
<input type="email"value={email} required class="input mb-4" />
<input type="email" value={email} required class="input mb-4" />
</label>
<label>
<span class="text-primary-500">Reset Code</span>
Expand All @@ -155,7 +154,7 @@
<div class="mb-4 mt-2">
<PasswordInput bind:password ={newPassword} name = "newPassword"/>
</div>

<!-- <input type="password" bind:value={newPassword} required class="input mb-4 mt-2" /> -->
{#if errors.newPassword}
<span class="text-error-500">{errors.newPassword}</span>
Expand All @@ -167,7 +166,7 @@
<div class="mb-4 mt-2">
<PasswordInput bind:password= {confirmPassword} name = 'confirmPassword'/>
</div>

<!-- <input type="password" bind:value={confirmPassword} required class="input mb-4" /> -->
{#if errors.confirmPassword}
<span class="text-error-500">{errors.confirmPassword}</span>
Expand All @@ -179,19 +178,19 @@
</div>
{:else}
<form method="post" action="?/login" class="shadow-bottom-right p-8 pb-1 pt-5 rounded-lg mt-5 bg-secondary-50 border border-slate-300 shadow-xl w-96 max-w-full">
<input name="roleId" bind:value={loginRoleId} class="hidden"/>
<!-- <input name="roleId" bind:value={loginRoleId} class="hidden"/> -->
<!-- svelte-ignore a11y-label-has-associated-control -->
<div class="justify-center w-full mt-5 h-50">
<div class="flex gap-6 mb-4">
<div class="flex gap-2">
<input type="radio" class="radio rounded-full" name="loginType" value="username" bind:group={activeTab} />Username
</div>
<div class="flex gap-2">
<input type="radio" class="radio rounded-full" name="loginType" value="email" bind:group={activeTab} /> Email
</div>
<div class="flex gap-2">
<input type="radio" class="radio rounded-full" name="loginType" value="phone" bind:group={activeTab} /> Phone
</div>
<div class="flex gap-2">
<input type="radio" class="radio rounded-full" name="loginType" value="username" bind:group={activeTab} />Username
</div>
</div>
{#if activeTab === 'username'}
<label class="mb-2" for="username">
Expand Down
31 changes: 31 additions & 0 deletions src/routes/api/services/reancare/persons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { API_CLIENT_INTERNAL_KEY, BACKEND_API_URL } from '$env/static/private';

////////////////////////////////////////////////////////////////

export const getPersonRolesForPhone = async (phone: string) => {
const headers = {};
headers['Content-Type'] = 'application/json';
headers['x-api-key'] = API_CLIENT_INTERNAL_KEY;
const url = BACKEND_API_URL + '/persons/roles-for-phone?phone=' + phone;
const res = await fetch(url, {
method: 'GET',
headers
});
const response = await res.json();
console.log('response', response);
return response;
};

export const getPersonRolesForEmail = async (email: string) => {
const headers = {};
headers['Content-Type'] = 'application/json';
headers['x-api-key'] = API_CLIENT_INTERNAL_KEY;
const url = BACKEND_API_URL + '/persons/roles-for-email?email=' + email;
const res = await fetch(url, {
method: 'GET',
headers
});
const response = await res.json();
console.log('response', response);
return response;
};
17 changes: 13 additions & 4 deletions src/routes/api/services/reancare/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { Helper } from '$lib/utils/helper';
import { API_CLIENT_INTERNAL_KEY, BACKEND_API_URL } from '$env/static/private';
import { del, get, post, put } from './common.reancare';
import { searchPersonRoleTypes } from './person-role-types';

////////////////////////////////////////////////////////////////

export const login = async (roleId: string, password: string, username?: string, email?: string, phone?: string) => {
const model: LoginModel = getLoginModel(roleId, password, username, email, phone);
export const login = async (loginRoleId: number|null, password: string, username?: string, email?: string, phone?: string) => {
try {
const model: LoginModel = getLoginModel(loginRoleId, password, username, email, phone);
console.log(JSON.stringify(model, null, 2));
const headers = {};
headers['Content-Type'] = 'application/json';
Expand All @@ -22,13 +24,20 @@ export const login = async (roleId: string, password: string, username?: string,
const response = await res.json();
console.log('response', response);
return response;
}
catch (error) {
console.log('error', error);
return { Success: false, Message: error.message, Data: null };
}
};

const getLoginModel = (roleId: string, password: string, username?: string, email?: string, phone?: string): LoginModel => {
const getLoginModel = (loginRoleId: number|null, password: string, username?: string, email?: string, phone?: string): LoginModel => {
const loginModel: LoginModel = {
Password: password,
LoginRoleId: roleId
};
if (loginRoleId) {
loginModel.LoginRoleId = loginRoleId;
}

if (username) {
loginModel.UserName = username;
Expand Down

0 comments on commit 814bb2b

Please sign in to comment.