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

Working Reset Password #11

Merged
merged 10 commits into from
Jul 9, 2024
Merged
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
60 changes: 60 additions & 0 deletions src/app/api/reset-admin/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// API Reset Password. Lokasi : /src/app/api/reset-sandi

// API untuk reset password akun karyawan

import { NextResponse } from "next/server"

import bcrypt from 'bcrypt'

import { getToken } from "next-auth/jwt"

import prisma from "@/app/lib/prisma"


export const PUT = async (req) =>{
const token = await getToken({req, secret: process.env.NEXTAUTH_SECRET})
const resetKey = process.env.ADMIN_KEY

console.log('Token: ', token)

if(!token){
console.log('Unauthorized Access : API Reset Sandi')

return NextResponse.json({error:'Unauthorized Access'}, {status:401})
}

try{
const {email, password, masterKey} =await req.json()

if(!email || !password || !masterKey){
return NextResponse.json({error:"Data tidak boleh kosong!"}, {status:400})
}

if (masterKey !== resetKey) {
return NextResponse.json({ error: "Master Key salah!" }, { status: 403 });
}

const hashedPassword = await bcrypt.hash(password, 12)

try{
const user = await prisma.user.update({
where: {email: email},
data:{
password: hashedPassword,
},
})

return NextResponse.json({message:"Password Berhasil diganti", user }, {status:200})
}
catch(error){
console.error("Error memperbarui password :", error)

return NextResponse.json({error:"Ada kesalahan ketika memperbarui Password"}, {status:500})
}
}catch(error){
console.error("Error tidak dapat parsing request body", error)

return NextResponse.json({error: "Bad Request"}, {status:400})
}
}

55 changes: 55 additions & 0 deletions src/app/api/reset-sandi/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// API Reset Password. Lokasi : /src/app/api/reset-sandi

// API untuk reset password akun karyawan

import { NextResponse } from "next/server"

import bcrypt from 'bcrypt'

import { getToken } from "next-auth/jwt"

import prisma from "@/app/lib/prisma"


export const PUT = async (req) =>{
const token = await getToken({req, secret: process.env.NEXTAUTH_SECRET})

console.log('Token: ', token)

if(!token){
console.log('Unauthorized Access : API Reset Sandi')

return NextResponse.json({error:'Unauthorized Access'}, {status:401})
}

try{
const {email, password} =await req.json()

if(!email || !password){
return NextResponse.json({error:"Data tidak boleh kosong!"}, {status:400})
}

const hashedPassword = await bcrypt.hash(password, 12)

try{
const user = await prisma.user.update({
where: {email: email},
data:{
password: hashedPassword,
},
})

return NextResponse.json({message:"Password Berhasil diganti", user }, {status:200})
}
catch(error){
console.error("Error memperbarui password :", error)

return NextResponse.json({error:"Ada kesalahan ketika memperbarui Password"}, {status:500})
}
}catch(error){
console.error("Error tidak dapat parsing request body", error)

return NextResponse.json({error: "Bad Request"}, {status:400})
}
}

36 changes: 34 additions & 2 deletions src/app/dashboard/reset-password-akun/page.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,42 @@
'use client'

import { useEffect } from 'react'

import { useRouter } from 'next/navigation'

import { useSession } from 'next-auth/react'

import ResetPasswordKaryawan from "@/views/reset-password/resetpassword-karyawan"
import ResetPasswordAdmin from '@/views/reset-password/resetpassword-admin'


const ResetPasswordAkun = () =>{
const { data: session, status } = useSession()
const router = useRouter()

useEffect(() => {
if (status === 'loading') return // Jangan lakukan apa pun saat sesi sedang dimuat

if (!session) {
router.push('/error/401')
}
}, [session, status, router])

if (!session) {
return null
}

return(
<div>
Halaman Reset Password Akun

<h1>Reset Password Akun</h1>
<br />
<div>
<ResetPasswordKaryawan/>
</div>
<br />
<div>
<ResetPasswordAdmin/>
</div>
</div>
)
}
Expand Down
Binary file modified src/app/favicon.ico
Binary file not shown.
6 changes: 3 additions & 3 deletions src/configs/primaryColorConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
const primaryColorConfig = [
{
name: 'primary-1',
light: '#0A4EC3',
main: '#193695',
dark: '#034EB7'
light: '#0066FF',
main: '#0066FF',
dark: '#0066FF'
}
]

Expand Down
2 changes: 1 addition & 1 deletion src/configs/themeConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
*/
const themeConfig = {
templateName: 'KASBON MANAGER',
settingsCookieName: 'materio-mui-next-free-demo',
settingsCookieName: 'kasbon-manager',
mode: 'dark', // 'light', 'dark'
layoutPadding: 24, // Common padding for header, content, footer layout components (in px)
compactContentWidth: 1440, // in px
Expand Down
171 changes: 171 additions & 0 deletions src/views/reset-password/resetpassword-admin.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
"use client"

import { useState, useEffect, useRef } from 'react'

import Card from '@mui/material/Card'
import Grid from '@mui/material/Grid'
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import InputAdornment from '@mui/material/InputAdornment'
import Alert from '@mui/material/Alert'

const ResetPasswordAdmin = () => {
const [status, setStatus] = useState(null)
const [message, setMessage] = useState('')
const formRef = useRef(null)

useEffect(() => {
if (status) {
const timer = setTimeout(() => {
setStatus(null)
setMessage('')
}, 5000)

return () => clearTimeout(timer)
}
}, [status])

const handleSubmit = async (event) => {
event.preventDefault()
const data = new FormData(event.target)

const email = data.get('email')
const password = data.get('password')
const konfirmasiPassword = data.get('konfirmasipassword')
const masterKey = data.get('masterKey')

if (password !== konfirmasiPassword) {
setStatus('error')
setMessage('Password dan konfirmasi password tidak sama.')
formRef.current.reset()

return
}

const formData = { email, password, masterKey }

try {
const response = await fetch('/api/reset-admin', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
})

const result = await response.json()

if (response.ok) {
setStatus('success');
setMessage('Password Admin berhasil diganti!');
formRef.current.reset(); // Kosongkan form setelah berhasil diganti
} else if (response.status === 403) {
setStatus('error');
setMessage('Master Key salah.');
} else {
setStatus('error');
setMessage(result.error || 'Terjadi kesalahan saat mengganti password.');
}
} catch (error) {
setStatus('error');
setMessage('Terjadi kesalahan saat mengganti password.');
}
}

return (
<div>
<Card>
<CardHeader title='Reset Password Admin' />
<CardContent>
{status && (
<Alert severity={status} style={{ marginBottom: '1rem' }}>
{message}
</Alert>
)}
<form onSubmit={handleSubmit} ref={formRef}>
<Grid container spacing={5}>
<Grid item xs={12}>
<TextField
id='email'
name='email'
fullWidth
type='email'
label='Email'
placeholder='Email Admin'
InputProps={{
startAdornment: (
<InputAdornment position='start'>
<i className='ri-mail-line' />
</InputAdornment>
)
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
id='password'
name='password'
fullWidth
type='password'
label='Password'
placeholder='Password'
InputProps={{
startAdornment: (
<InputAdornment position='start'>
<i className='ri-key-2-fill' />
</InputAdornment>
)
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
id='konfirmasipassword'
name='konfirmasipassword'
fullWidth
type='password'
label='Password'
placeholder='Konfirmasi Password'
InputProps={{
startAdornment: (
<InputAdornment position='start'>
<i className='ri-key-2-fill' />
</InputAdornment>
)
}}
/>
</Grid>
<br />
<Grid item xs={12}>
<TextField
id='masterKey'
name='masterKey'
fullWidth
type='password'
label='Master Key'
placeholder='Masukkan Master Key'
InputProps={{
startAdornment: (
<InputAdornment position='start'>
<i className='ri-key-2-fill' />
</InputAdornment>
)
}}
/>
</Grid>
<Grid item xs={12} justifyContent="center" alignItems="center">
<Button variant='contained' type='submit'>
Reset Password Admin
</Button>
</Grid>
</Grid>
</form>
</CardContent>
</Card>
</div>
)
}

export default ResetPasswordAdmin
Loading