Fresh를 사용한 블로그 엔진: 수퍼유저 만들기




GitHub: https://github.com/Sokhavuth/deno-fresh
데노 배치: https://khmerweb-fresh.deno.dev/login


// controllers/front/login.js

import { setCookie, getCookies, deleteCookie } from "cookies";
import { setting, secret_key, myredis } from 'setting';
import { create, verify, getNumericDate } from "jwt";
import userdb from "../../models/user.ts";
import { bcrypt } from "bcrypt";

userdb.createRootUser();

class Login{
    async getForm(req, ctx){
        const cookies = getCookies(req.headers);

        if((cookies)&&(cookies.session_id)){
            const jwt = await myredis.get(cookies.session_id);
            try{
                const payload = await verify(jwt, secret_key, "HS512");
                if(payload.user){
                    return new Response(undefined, { headers: {location: `/admin/post`}, status: 302 });
                }
            }catch(error){
                console.log(error);
                const config = setting();
                config.page_title = "Login Page";
                const resp = new Response();
                deleteCookie(resp.headers, "session_id");
                return await ctx.render({"setting": config});
            }
        }   

        const config = setting();
        config.page_title = "Login Page";
        return await ctx.render({"setting": config});
    }
}

export default new Login();



// models/user.ts

import { mydb } from "setting";
import { bcrypt } from "bcrypt";

interface UserSchema {
    _id: ObjectId;
    id: string; 
    title: string;
    content: string;
    thumb: string;
    date: string;
    role: string;
    email: string;
    password: string;
}

class User{
    async createRootUser(){
        const id = crypto.randomUUID();
        const salt = await bcrypt.genSalt(8);
        const hashPassword = bcrypt.hashSync('xxxxxxxxxxxxxxxxxx', salt);
        const newUser = {
            id: id, 
            title: 'Guest',
            content: '',
            thumb: '',
            date: '',
            role: 'Guest',
            email: '[email protected]',
            password: hashPassword,
        }

        const users = mydb.collection<UserSchema>("users");
        await users.insertOne(newUser);
    }

    async checkUser(email: string){
        const users = mydb.collection<UserSchema>("users");
        return await users.findOne({email: email});
    }
}

export default new User();

좋은 웹페이지 즐겨찾기