Skip to content

Instantly share code, notes, and snippets.

// lib/app.ts
import express = require('express');
// Create a new express application instance
const app: express.Application = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
import {
Entity,
PrimaryGeneratedColumn,
Column,
Unique,
CreateDateColumn,
UpdateDateColumn
} from "typeorm";
import { Length, IsNotEmpty } from "class-validator";
import * as bcrypt from "bcryptjs";
import { Request, Response } from "express";
import * as jwt from "jsonwebtoken";
import { getRepository } from "typeorm";
import { validate } from "class-validator";
import { User } from "../entity/User";
import config from "../config/config";
class AuthController {
static login = async (req: Request, res: Response) => {
import { Request, Response } from "express";
import { getRepository } from "typeorm";
import { validate } from "class-validator";
import { User } from "../entity/User";
class UserController{
static listAll = async (req: Request, res: Response) => {
//Get users from database
export default {
jwtSecret: "@QEGTUI"
};
import { Request, Response, NextFunction } from "express";
import * as jwt from "jsonwebtoken";
import config from "../config/config";
export const checkJwt = (req: Request, res: Response, next: NextFunction) => {
//Get the jwt token from the head
const token = <string>req.headers["auth"];
let jwtPayload;
//Try to validate the token and get data
import { Request, Response, NextFunction } from "express";
import { getRepository } from "typeorm";
import { User } from "../entity/User";
export const checkRole = (roles: Array<string>) => {
return async (req: Request, res: Response, next: NextFunction) => {
//Get the user ID from previous midleware
const id = res.locals.jwtPayload.userId;
import { Router } from "express";
import AuthController from "../controllers/AuthController";
import { checkJwt } from "../middlewares/checkJwt";
const router = Router();
//Login route
router.post("/login", AuthController.login);
//Change my password
router.post("/change-password", [checkJwt], AuthController.changePassword);
import { Router } from "express";
import UserController from "../controllers/UserController";
import { checkJwt } from "../middlewares/checkJwt";
import { checkRole } from "../middlewares/checkRole";
const router = Router();
//Get all users
router.get("/", [checkJwt, checkRole(["ADMIN"])], UserController.listAll);
import { Router, Request, Response } from "express";
import auth from "./auth";
import user from "./user";
const routes = Router();
routes.use("/auth", auth);
routes.use("/user", user);
export default routes;