Skip to content

Commit

Permalink
Merge pull request #46 from REAN-Foundation/release/uat-0.2.5
Browse files Browse the repository at this point in the history
Release/uat 0.2.5
  • Loading branch information
kiran-rean authored Aug 26, 2024
2 parents 3a6df03 + 5a191e4 commit 38b56ef
Show file tree
Hide file tree
Showing 9 changed files with 175 additions and 136 deletions.
25 changes: 16 additions & 9 deletions src/lib/components/input/password.input.svelte
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
<script lang="ts">
import Icon from '@iconify/svelte';
//////////////////////////////////////////////////////////////////
import { createEventDispatcher } from 'svelte';
export let name = 'password';
export let password = '';
let showPassword = false;
function togglePasswordVisibility() {
showPassword = !showPassword;
}
const dispatch = createEventDispatcher();
function onFocus() {
dispatch('focus');
}
function onBlur() {
dispatch('blur');
}
</script>

<div class="flex relative items-center">
<!-- <input
type={showPassword ? 'text' : 'password'}
name = {name}
bind:value={password}
required
class="input mb-4 mt-2"
/> -->
{#if showPassword}
<input
type="text"
{name}
bind:value={password}
required
class="input"
on:focus={onFocus}
on:blur={onBlur}
/>
{:else}
<input
Expand All @@ -34,6 +39,8 @@
bind:value={password}
required
class="input"
on:focus={onFocus}
on:blur={onBlur}
/>
{/if}
{#if password !== ''}
Expand Down
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
98 changes: 44 additions & 54 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,53 +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 @@ -86,18 +41,18 @@ const loginSchema = zfd.formData({
});

export const actions = {

login: async (event: RequestEvent) => {
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,11 +122,12 @@ 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;
const accessToken = response.Data.AccessToken;
const refreshToken = response.Data.RefreshToken;
const refreshToken = response.Data.RefreshToken;
const expiryDate = new Date(response.Data.SessionValidTill);
const sessionId = response.Data.SessionId;
const userId: string = response.Data.User.id;
Expand All @@ -152,7 +142,7 @@ export const actions = {
console.log(JSON.stringify(userSession, null, 2));

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

throw redirect(303, `/users/${userId}/home`, successMessage(`Login successful!`), event);
}
};
};
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
10 changes: 5 additions & 5 deletions src/routes/api/server/notifications/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ export const DELETE = async (event: RequestEvent) => {
const data = await request.json();
console.log('Inside notification server endpoints');
let response;
try{
try {
response = await deleteNotification(data.sessionId, data.notificationId);
}catch(error){
} catch (error) {
throw redirect(
errorMessage('Error deleting notification.'),
errorMessage('Error deleting notification.'),
event
);
);
}
throw redirect(
successMessage(response.Message),
event
);
);
};
20 changes: 10 additions & 10 deletions src/routes/api/server/users/search/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import { searchUsers, addPermissionMatrix } from '$routes/api/services/reancare/

export const GET = async (event: RequestEvent) => {
const sessionId = event.locals.sessionUser.sessionId;
const tenantId = event.locals.sessionUser.tenantId;
const userRole = event.locals.sessionUser.roleName;
const userId = event.locals.sessionUser.userId;
const userRoleId = event.locals.sessionUser.roleId;
const tenantId = event.locals.sessionUser.tenantId;
const userRole = event.locals.sessionUser.roleName;
const userId = event.locals.sessionUser.userId;
const userRoleId = event.locals.sessionUser.roleId;
const searchParams: URLSearchParams = event.url.searchParams;
const firstName = searchParams.get('firstName') ?? undefined;
const email = searchParams.get('email') ?? undefined;
const phone = searchParams.get('phone') ?? undefined;
const roleIds = searchParams.get('roleIds') ?? undefined;
const roleIds = searchParams.get('roleIds') ?? undefined;
const sortBy = searchParams.get('sortBy') ?? 'CreatedAt';
const sortOrder = searchParams.get('sortOrder') ?? 'ascending';
const itemsPerPage_ = searchParams.get('itemsPerPage');
Expand All @@ -25,19 +25,19 @@ export const GET = async (event: RequestEvent) => {
firstName,
phone,
email,
roleIds,
roleIds,
orderBy: sortBy,
order: sortOrder,
itemsPerPage,
pageIndex
};
const response = await searchUsers(sessionId, searchParams);

const users = response.Data.Users;
// console.log("---", users);
users.Items = await addPermissionMatrix(sessionId, users.Items, userRole, userId, tenantId, userRoleId);
// console.log("---", users);
users.Items = await addPermissionMatrix(sessionId, users.Items, userRole, userId, tenantId, userRoleId);
// console.log("***", users);
return new Response(JSON.stringify(users));
return new Response(JSON.stringify(users));
} catch (err) {
console.error(`Error retriving users: ${err.message}`);
return new Response(err.message);
Expand Down
Loading

0 comments on commit 38b56ef

Please sign in to comment.