import {
  auth,
  config,
  method,
  route,
  swagger,
  validate,
} from "@noderun/hapi-router";
import UploadFunc from "../demo/_upload";
import Joi from "joi";
import User from "@/model/User";
import * as bcrypt from "bcrypt";
export default class {
  @auth()
  @config({
    auth: {
      mode: "try",
    },
  })
  index(request, h) {
    // console.log(request.auth);
    if (request.isAuthenticated) {
      // 登录了
    } else {
      // 未登录
    }
    return h.view("views/index.pug");
  }
  @method("GET")
  @route("/login")
  loginView(request, h) {
    return h.view("views/login.ejs");
  }

  @method("POST")
  @auth(false)
  @route("/login")
  async login(request, h) {
    const { username, password } = request.payload;
    const account = <any>await User.findOne({ where: { username: username } });

    if (!account || !(await bcrypt.compare(password, account.password))) {
      return h.view("/login");
    }

    request.cookieAuth.set({ id: account.id });

    return h.redirect("/");
  }

  @route("/about")
  @auth()
  about(request, h) {
    console.log(request.auth);
    return h.view("views/about.ejs");
  }

  @route("/{path*}")
  async 404(req, h) {
    // 404页面
    return h.view("404.pug");
  }
}