import { Router , Request , Response } from 'express' ; import { User } from '../models/User' ; import * as bcrypt from 'bcrypt' ; import * as jwt from 'jsonwebtoken' ; import { NextFunction } from 'connect' ; import * as EmailValidator from 'email-validator' ; const router = Router ( ) ; async function generatePassword ( plainTextPassword ) { return "NotYetImplemented" ; } async function comparePasswords ( plainTextPassword , hash ) { return true ; } function generateJWT ( user ) { return "NotYetImplemented" ; } export function requireAuth ( req , res , next ) { console . warn ( "auth.router not yet implemented, you'll cover this in lesson 5" ) ; return next ( ) ; } router . get ( '/verification' , requireAuth , async ( req , res ) => { return res . status ( 200 ) . send ( { auth : true , message : 'Authenticated.' } ) ; } ) ; router . post ( '/login' , async ( req , res ) => { const email = req . body . email ; const password = req . body . password ; if ( ! email || ! EmailValidator . validate ( email ) ) { return res . status ( 400 ) . send ( { auth : false , message : 'Email is required or malformed' } ) ; } if ( ! password ) { return res . status ( 400 ) . send ( { auth : false , message : 'Password is required' } ) ; } const user = await User . findByPk ( email ) ; if ( ! user ) { return res . status ( 401 ) . send ( { auth : false , message : 'Unauthorized' } ) ; } const authValid = await comparePasswords ( password , user . password_hash ) ; if ( ! authValid ) { return res . status ( 401 ) . send ( { auth : false , message : 'Unauthorized' } ) ; } const jwt = generateJWT ( user ) ; res . status ( 200 ) . send ( { auth : true , token : jwt , user : user . short ( ) } ) ; } ) ; router . post ( '/' , async ( req , res ) => { const email = req . body . email ; const plainTextPassword = req . body . password ; if ( ! email || ! EmailValidator . validate ( email ) ) { return res . status ( 400 ) . send ( { auth : false , message : 'Email is required or malformed' } ) ; } if ( ! plainTextPassword ) { return res . status ( 400 ) . send ( { auth : false , message : 'Password is required' } ) ; } const user = await User . findByPk ( email ) ; if ( user ) { return res . status ( 422 ) . send ( { auth : false , message : 'User may already exist' } ) ; } const password_hash = await generatePassword ( plainTextPassword ) ; const newUser = await new User ( { email : email , password_hash : password_hash } ) ; let savedUser ; try { savedUser = await newUser . save ( ) ; } catch ( e ) { throw e ; } const jwt = generateJWT ( savedUser ) ; res . status ( 201 ) . send ( { token : jwt , user : savedUser . short ( ) } ) ; } ) ; router . get ( '/' , async ( req , res ) => { res . send ( 'auth' ) ; } ) ; export const AuthRouter = router ;