//pages/admin/index.js
//npm install next-absolute-url
import settings from '../../settings.js'
import {withIronSessionSsr} from "iron-session/next"
import absoluteUrl from 'next-absolute-url'

export const getServerSideProps = withIronSessionSsr(
    async function getServerSideProps(ctx) {
        let mySettings = await settings()
        
        if(ctx.req.session.user){
            if(ctx.params.page === 'post'){
                mySettings.pageTitle = 'ទំព័រ​ការផ្សាយ'
                mySettings.page = 'post'
            }else if(ctx.params.page === 'user'){
                mySettings.pageTitle = 'ទំព័រ​អ្នក​ប្រើប្រាស់'
                mySettings.page = 'user'
                mySettings.route = '/admin/user'

                const {origin} = absoluteUrl(ctx.req)

                const res = await fetch(`${origin}/api/user/read`)
                const data = await res.json()
                mySettings.items = data.items
                mySettings.count = data.count
            }

            return {
                props: mySettings,
            }
        }else{
            return {
                redirect: {
                    permanent: false,
                    destination: "/login",
                },
            }
        }
    },
    {
        cookieName: process.env.COOKIE_NAME,
        password: process.env.SECRET_KEY,
        cookieOptions: {
            secure: process.env.NODE_ENV === "production",
        },
    },
)

import _index from '../../views/_index.js'
export default (props)=>{
    return(
    <_index
        mySettings={props}
    />
    )
}

 

//pages/api/user/[action].js
import {withIronSessionApiRoute} from "iron-session/next"
import { redirect } from "next/dist/server/api-utils"

export default withIronSessionApiRoute(
    async function user(req,res){
        const loggedUser = await req.session.user
        const {action} = req.query

            if(action === 'create'){
                if(loggedUser.category === 'Admin'){
                    const create = await import('../../../models/user/create.js')
                    create.default(req,res)
                }
                redirect('/admin/user')
                
            }else if(action === 'read'){
                const read = await import('../../../models/user/read.js')
                const items = await read.default()
                const module = await import('../../../models/count.js')
                const count = await module.default('users')

                res.json({items:items,count:count})
            }
    },
    {
        cookieName: process.env.COOKIE_NAME,
        password: process.env.SECRET_KEY,
        ookieOptions:{
            secure: process.env.NODE_ENV === "production",
        },
    },
  )

 

//models/user/read.js
import  db from '../setConSqlite.js'
import settings from '../../settings.js'

export default async (req,res)=>{
    const mydb = db()
    const mySettings = await settings()

    return new Promise((resolve, reject)=>{

        let sql = `SELECT * FROM users ORDER BY date DESC LIMIT ?`

        mydb.all(sql,[mySettings._itemListing],async function(err,result){
            if (err) {
                console.log(err.message)
                reject(err)
            }else{
                resolve(result)
            }
        })
    })
}

 

//models/count.js
import  db from './setConSqlite.js'

export default async (table)=>{
    const mydb = db()

    return new Promise((resolve, reject)=>{

        let sql = `SELECT COUNT(*) as total FROM ${table}`

        mydb.get(sql,async function(err,result){
            if (err) {
                console.log(err.message)
                reject(err)
            }else{
                resolve(result.total)
            }
        })
    })
}

 

//views/_index.js
import Head from 'next/head'
import styles from '../styles/admin/Index.module.css'
import Link from 'next/link'
import dynamic from 'next/dynamic'

export default function Index(args){
    const props = args.mySettings
    let Page = null
    
    if(props.page === 'post'){
        Page = dynamic(() => import('./_post.js'),{ ssr: false })
    }else if(props.page === 'user'){
        Page = dynamic(() => import('./_user.js'),{ ssr: false })
    }

    return(
        <div className={styles.Index}>
            <Head>
                <title>{props.siteTitle} | {props.pageTitle}</title>
                <link rel="icon" href="/images/siteLogo.png" />
            </Head>

            <div className={styles.menuWrapper}>
                <div className={`${styles.menu} region`}>
                    <div className={styles.logo}>{props.pageTitle}</div>
                    <form>
                        <select name='label'>
                            <option>ការផ្សាយ</option>
                        </select>
                        <input type='text' name='querry' placeholder='ស្វែង​រក'/>
                        <input type='submit' value='បញ្ជូន' />
                    </form>
                    <div className={styles.logout}>
                        <Link href="/"><a>ទំព័រ​មុខ</a></Link> | <Link href="/api/logout"><a>ចេញ​ក្រៅ</a></Link>
                    </div>
                </div>
            </div>

            <div className={`${styles.main} region`}>
                <div className={styles.sidebar}>
                    <div className={styles.inner}>
                        <Link href='/admin/post'><a><img src='/images/movie.png' /></a></Link>
                        <Link href='/admin/post'><a>ការផ្សាយ</a></Link>
            
                        <Link href='/admin/category'><a><img src='/images/category.png' /></a></Link>
                        <Link href='/admin/category'><a>ជំពូក</a></Link>
            
                        <Link href='/admin/book'><a><img src='/images/books.png' /></a></Link>
                        <Link href='/admin/book'><a>សៀវភៅ</a></Link>
            
                        <Link href='/admin/upload'><a><img src='/images/upload.png' /></a></Link>
                        <Link href='/admin/upload'><a>Upload</a></Link>
            
                        <Link href='/admin/user'><a><img src='/images/users.png' /></a></Link>
                        <Link href='/admin/user'><a>អ្នក​ប្រើប្រាស់</a></Link>
            
                        <Link href='/admin/setting'><a><img src='/images/setting.png' /></a></Link>
                        <Link href='/admin/setting'><a>Setting</a></Link>
                    </div>
                </div>
                <div className={styles.content}>
                    <Page />
                </div>
            </div>

            <div className={`${styles.status} region`}>សរុប​ទាំងអស់​មានចំនួនៈ {props.count}</div>

            <ul className={`${styles.items} region`}>
            {props.items.map((item,index) => (
                <li key={index}>
                    <Link href={`/user/${item.userid}`}>
                        <a className={styles.thumb}><img src={item.thumb} /></a>
                    </Link>
                    <div>
                        <Link href={`/user/${item.userid}`}>
                            <a className={styles.title}>{item.title}</a>
                        </Link>
                        <div className={styles.date}>
                            {(new Date(item.date)).toLocaleDateString()}
                        </div>
                    </div>
                    <Link href={`${props.route}/edit/${item.userid}`}>
                        <a title="កែប្រែ" className={styles.edit}>
                            <img src='/images/edit.png' />
                        </a>
                    </Link>
                    <Link href={`${props.route}/delete/${item.userid}`}>
                    <a title="លុប" className={styles.edit}>
                        <img src='/images/delete.png' />
                    </a>
                    </Link>
                </li>
            ))}
            </ul>

            <div className={`${styles.paginate} region`}>
                <a><img src="/images/paginate.png" /></a>
            </div>
        </div>
    )
}

 

GitHub: https://github.com/Sokhavuth/nblog

Vercel: https://khmerweb-nblog.vercel.app/admin/user