diff --git a/README.md b/README.md index 1926627..05a4af5 100644 --- a/README.md +++ b/README.md @@ -41,10 +41,11 @@ http://localhost:8000/v1/chats Here's the map of API's HTTP routes: -* `/` — routes related to authentication. +* `/` — routes related to authentication. * `/signup` **POST** — create new user with `username` and `password`. * `/login` **POST** — log user in with `username` and `password`. * `/logout` **GET** — log out active user. + * `/user-exists?username=john` **GET** — check, whether username is already taken. * `/users` — routes related to users. * `/users` **GET** — retrieve data about all users. * `/users/me` **GET** — retrieve my user's data. diff --git a/controllers/auth.js b/controllers/auth.js index 96d7524..17aa854 100644 --- a/controllers/auth.js +++ b/controllers/auth.js @@ -102,8 +102,31 @@ function logout() { }); } +function userExists(username) { + if (!username) { + return Promise.reject({ + success: false, + message: 'Username is not provided', + }); + } + return User.findOne({ username }) + .exec() + .then((user) => { + if (user) { + return Promise.reject({ + success: false, + message: 'Username is already taken', + }); + } + return Promise.resolve({ + success: true, + }); + }); +} + module.exports = { signUp, login, logout, + userExists, }; diff --git a/routes/auth.js b/routes/auth.js index 87564d4..d4da0ea 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -67,4 +67,22 @@ authRouter.get('/logout', (req, res, next) => { }); }); +authRouter.get('/user-exists', (req, res, next) => { + const { username } = req.query; + authConroller + .userExists(username) + .then((result) => { + res.json({ + success: result.success, + }); + }) + .catch((error) => { + res.json({ + success: false, + message: error.message, + }); + next(error); + }); +}); + module.exports = authRouter;