Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added change password feature #1439

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
357 changes: 355 additions & 2 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

90 changes: 90 additions & 0 deletions src/actions/user/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
'use server';
import db from '@/db';
import { InputTypeChangePassword, ReturnTypeChangePassword } from './types';
import { getServerSession } from 'next-auth';
import { authOptions, validateUser } from '@/lib/auth';
import bcrypt from 'bcrypt';
import { createSafeAction } from '@/lib/create-safe-action';
import { ChangePasswordSchema } from './schema';

export const logoutUser = async (email: string, adminPassword: string) => {
if (adminPassword !== process.env.ADMIN_SECRET) {
Expand All @@ -25,3 +31,87 @@ export const logoutUser = async (email: string, adminPassword: string) => {

return { message: 'User logged out' };
};

const changePasswordHandler = async (
data: InputTypeChangePassword,
): Promise<ReturnTypeChangePassword> => {
const session = await getServerSession(authOptions);

if (!session || !session.user.id) {
return {
error: 'Unauthorized',
};
}

const { currentpassword, confirmpassword, newpassword } = data;

if (newpassword !== confirmpassword) {
return {
error: 'New and Confirm password does not match',
};
}
const { email } = session.user;

// Get user token(require to update password)
const user = await validateUser(email, currentpassword);
if (!user.data)
return {
error: 'User not found',
};

const { userid, token } = user.data;

// End point to change password
const url = `https://harkiratapi.classx.co.in/post/changesecurity`;

const myHeaders = new Headers();
myHeaders.append('auth-key', process.env.APPX_AUTH_KEY || '');
myHeaders.append('client-service', process.env.APPX_CLIENT_SERVICE || '');
myHeaders.append('authorization', token);

const body = new FormData();
body.append('currentpassword', currentpassword);
body.append('newpassword', newpassword);
body.append('confirmpassword', confirmpassword);
body.append('userid', userid);

try {
// Changing password to Appx
const response = await fetch(url, {
method: 'POST',
headers: myHeaders,
body,
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

// Store new password in DB
const hashedPassword = await bcrypt.hash(newpassword, 10);
await db.user.update({
where: {
email,
},
data: {
password: hashedPassword,
token,
},
});

return {
data: {
message: 'Password updated',
},
};
} catch (error) {
console.error('Error updating password user:', error);
return {
error: 'Fail to update password',
};
}
};

export const changePassword = createSafeAction(
ChangePasswordSchema,
changePasswordHandler,
);
11 changes: 11 additions & 0 deletions src/actions/user/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import z from 'zod';

export const ChangePasswordSchema = z.object({
currentpassword: z.string({ message: 'Required' }),
newpassword: z
.string({ message: 'Required' })
.min(6, { message: 'Min length 6 required' }),
confirmpassword: z
.string({ message: 'Required' })
.min(6, { message: 'Min length 6 required' }),
});
14 changes: 14 additions & 0 deletions src/actions/user/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ActionState } from '@/lib/create-safe-action';
import { z } from 'zod';
import { ChangePasswordSchema } from './schema';

export type InputTypeChangePassword = z.infer<typeof ChangePasswordSchema>;

interface ReturnChangePassword {
message: string;
}

export type ReturnTypeChangePassword = ActionState<
InputTypeChangePassword,
ReturnChangePassword
>;
16 changes: 16 additions & 0 deletions src/app/password/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { PasswordChange } from '@/components/account/PasswordChange';
import { authOptions } from '@/lib/auth';
import { getServerSession } from 'next-auth';
import { redirect } from 'next/navigation';

export default async function PasswordChangePage() {
const session = await getServerSession(authOptions);
if (!session?.user) {
redirect('/');
}
return (
<section className="wrapper relative flex min-h-screen items-center justify-center overflow-hidden antialiased">
<PasswordChange />
</section>
);
}
5 changes: 4 additions & 1 deletion src/components/ContentCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { formatTime } from '@/lib/utils';
import VideoThumbnail from './videothumbnail';
import CardComponent from './CardComponent';
import { motion } from 'framer-motion';
import { KeyboardEvent } from 'react';

export const ContentCard = ({
title,
Expand Down Expand Up @@ -33,7 +34,9 @@ export const ContentCard = ({
onClick={onClick}
tabIndex={0}
role="button"
onKeyDown={(e:React.KeyboardEvent) => (['Enter', ' '].includes(e.key) && onClick())}
onKeyDown={(e: KeyboardEvent) =>
['Enter', ' '].includes(e.key) && onClick()
}
className={`group relative flex h-fit w-full max-w-md cursor-pointer flex-col gap-2 rounded-2xl transition-all duration-300 hover:-translate-y-2`}
>
{markAsCompleted && (
Expand Down
18 changes: 9 additions & 9 deletions src/components/CourseView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ export const CourseView = ({
rest: string[];
course: any;
courseContent:
| {
folder: true;
value: ChildCourseContent[];
}
| {
folder: false;
value: ChildCourseContent;
}
| null;
| {
folder: true;
value: ChildCourseContent[];
}
| {
folder: false;
value: ChildCourseContent;
}
| null;
nextContent: any;
searchParams: QueryParams;
possiblePath: string;
Expand Down
4 changes: 3 additions & 1 deletion src/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,9 @@ export function Sidebar({
variants={sidebarVariants}
className="fixed right-0 top-0 z-[99999] flex h-screen w-full flex-col gap-4 overflow-y-auto rounded-r-lg border-l border-primary/10 bg-neutral-50 dark:bg-neutral-900 md:max-w-[30vw]"
>
<div className="sticky top-0 z-10 flex items-center justify-between border-b border-primary/10 bg-neutral-50 p-5 dark:bg-neutral-900"> <h4 className="text-xl font-bold tracking-tighter text-primary lg:text-2xl">
<div className="sticky top-0 z-10 flex items-center justify-between border-b border-primary/10 bg-neutral-50 p-5 dark:bg-neutral-900">
{' '}
<h4 className="text-xl font-bold tracking-tighter text-primary lg:text-2xl">
Course Content
</h4>
<Button
Expand Down
168 changes: 168 additions & 0 deletions src/components/account/PasswordChange.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
'use client';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { Input } from '../ui/input';
import { Button } from '../ui/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { useRef, useState } from 'react';
import { changePassword } from '@/actions/user';
import { toast } from 'sonner';
import { signOut } from 'next-auth/react';
import { ChangePasswordSchema } from '@/actions/user/schema';
import { Eye, EyeOff } from 'lucide-react';
import { motion } from 'framer-motion';

export function PasswordChange() {
const [checkingPassword, setCheckingPassword] = useState<boolean>(false);
const [viewPassword, setViewPassword] = useState<boolean>(false);
const [viewNewPassword, setViewNewPassword] = useState<boolean>(false);
const [viewConfirmPassword, setViewConfirmPassword] =
useState<boolean>(false);

const isValidPass = useRef<boolean>(true);
const formSchema = ChangePasswordSchema;

const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
});

async function onSubmit(values: z.infer<typeof formSchema>) {
if (values.newpassword === values.confirmpassword)
isValidPass.current = true;
else isValidPass.current = false;

if (!isValidPass.current) return;

setCheckingPassword(true);

const res = await changePassword({
currentpassword: values.currentpassword,
newpassword: values.newpassword,
confirmpassword: values.confirmpassword,
});
if (!res?.error) {
toast.success('Password Changed\nLogin Again');
await signOut();
} else {
toast.error('oops something went wrong..!');
}
setCheckingPassword(false);
}

return (
<motion.div
initial={{ y: -40, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{
duration: 0.5,
ease: 'easeInOut',
type: 'spring',
damping: 10,
}}
className="flex w-full flex-col justify-between gap-12 rounded-2xl bg-primary/5 p-8 md:max-w-[30vw]"
>
<h2 className="text-center text-xl font-bold">Change Password</h2>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="currentpassword"
render={({ field }) => (
<FormItem>
<FormLabel>Current Password</FormLabel>
<FormControl>
<div className="flex items-center justify-evenly space-x-1">
<Input
placeholder="Enter your current Password"
{...field}
type={viewPassword ? 'text' : 'password'}
/>
<span
onClick={() => setViewPassword((prev) => !prev)}
className="hover:cursor-pointer"
>
{viewPassword ? <EyeOff /> : <Eye />}
</span>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="newpassword"
render={({ field }) => (
<FormItem>
<FormLabel>New Password</FormLabel>
<FormControl>
<div className="flex items-center justify-evenly space-x-1">
<Input
placeholder="Enter your new Password"
{...field}
type={viewNewPassword ? 'text' : 'password'}
/>
<span
onClick={() => setViewNewPassword((prev) => !prev)}
className="hover:cursor-pointer"
>
{viewNewPassword ? <EyeOff /> : <Eye />}
</span>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmpassword"
render={({ field }) => (
<FormItem>
<FormLabel>Confirm New Password</FormLabel>
<FormControl>
<div className="flex items-center justify-evenly space-x-1">
<Input
placeholder="Confirm your current Password"
{...field}
type={viewConfirmPassword ? 'text' : 'password'}
/>
<span
onClick={() => setViewConfirmPassword((prev) => !prev)}
className="hover:cursor-pointer"
>
{viewConfirmPassword ? <EyeOff /> : <Eye />}
</span>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{isValidPass.current ? null : (
<p className="text-md text-red-800">
New and Confirm password does not match
</p>
)}
<div className="flex items-center justify-center">
<Button
type="submit"
variant={'branding'}
disabled={checkingPassword as boolean}
>
Change Password
</Button>
</div>
</form>
</Form>
</motion.div>
);
}
2 changes: 1 addition & 1 deletion src/components/comment/CommentVoteForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,4 @@ const CommentVoteForm: React.FC<CommentVoteFormProps> = ({
);
};

export default CommentVoteForm;
export default CommentVoteForm;
11 changes: 6 additions & 5 deletions src/components/posts/PostCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -216,10 +216,10 @@ const PostCard: React.FC<IProps> = ({
</div>

{enableReply && (
<form
onSubmit={handleSubmit}
className="mt-4"
onClick={handleEditorClick}
<form
onSubmit={handleSubmit}
className="mt-4"
onClick={handleEditorClick}
>
<div data-color-mode={theme} className="flex w-full flex-col gap-4">
<MDEditor
Expand Down Expand Up @@ -255,7 +255,8 @@ const PostCard: React.FC<IProps> = ({
sessionUser={sessionUser}
reply={false}
parentAuthorName={post.author.name}
isAnswer={true} />
isAnswer={true}
/>
</div>
))}
</div>
Expand Down
Loading
Loading