Last active
September 14, 2020 10:43
-
-
Save kingsley-einstein/fa88da14b3a10998d98fe3679a613398 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from "express"; | |
import jwt from "jsonwebtoken"; | |
import bcrypt from "bcryptjs"; | |
import { v4 as uuid } from "uuid"; | |
import { User, Session } from "../db"; | |
import { ErrorResponse } from "../custom"; | |
export class UserController { | |
static async register(req: express.Request, res: express.Response) { | |
try { | |
const username = req.body.username; | |
const password = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(14)); | |
const user = await User.create({ username, password }); | |
const token = jwt.sign({ | |
id: user._id, | |
password: user.password, | |
sessionId: uuid() | |
}, "secret"); | |
res.status(200).json({ | |
...user, | |
token | |
}); | |
} catch (error) { | |
res.status(500).json({ | |
message: error.message | |
}); | |
} | |
} | |
static async login(req: express.Request, res: express.Response) { | |
try { | |
const { username, password } = req.body; | |
const user = await User.findByUsername(username); | |
// Throw error if user is not found | |
if (!user) | |
throw new ErrorResponse(404, "User not found"); | |
// Throw error for incorrect password | |
if (!bcrypt.compareSync(password, user.password)) | |
throw new ErrorResponse(400, "Password is incorrect"); | |
const token = jwt.sign({ | |
id: user._id, | |
password: user.password, | |
sessionId: uuid() | |
}, "secret"); | |
res.status(200).json({ | |
...user, | |
token | |
}); | |
} catch (error) { | |
res.status(error.c || 500).json({ | |
message: error.message | |
}); | |
} | |
} | |
static async getLoggedUser(req: express.Request & { user: any; }, res: express.Response) { | |
try { | |
const user = req.user; | |
res.status(200).json(user); | |
} catch (error) { | |
res.status(500).json({ | |
message: error.message | |
}); | |
} | |
} | |
static async logout(req: express.Request & { sessionId: string; user: any; }, res: express.Response) { | |
try { | |
const session = await Session.invalidate(req.sessionId); | |
res.status(200).json({ | |
...session, | |
message: `User ${req.user.username} successfully signed out` | |
}); | |
} catch (error) { | |
res.status(500).json({ | |
message: error.message | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment