#4 89 создание функционала регистрации

parent 1bd96b6b
This diff is collapsed.
...@@ -10,7 +10,9 @@ ...@@ -10,7 +10,9 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@types/bcrypt": "^5.0.0",
"@types/node": "^18.15.3", "@types/node": "^18.15.3",
"bcrypt": "^5.1.0",
"body-parser": "^1.20.2", "body-parser": "^1.20.2",
"class-validator": "^0.14.0", "class-validator": "^0.14.0",
"cors": "^2.8.5", "cors": "^2.8.5",
...@@ -19,6 +21,7 @@ ...@@ -19,6 +21,7 @@
"express-validator": "^6.15.0", "express-validator": "^6.15.0",
"http-status-codes": "^2.2.0", "http-status-codes": "^2.2.0",
"joi": "^17.9.1", "joi": "^17.9.1",
"jsonwebtoken": "^9.0.0",
"mongoose": "^7.0.1", "mongoose": "^7.0.1",
"multer": "^1.4.5-lts.1", "multer": "^1.4.5-lts.1",
"ts-node-dev": "^2.0.0" "ts-node-dev": "^2.0.0"
...@@ -26,6 +29,7 @@ ...@@ -26,6 +29,7 @@
"devDependencies": { "devDependencies": {
"@types/cors": "^2.8.13", "@types/cors": "^2.8.13",
"@types/express": "^4.17.17", "@types/express": "^4.17.17",
"@types/jsonwebtoken": "^9.0.1",
"@types/mongoose": "^5.11.97", "@types/mongoose": "^5.11.97",
"@types/multer": "^1.4.7" "@types/multer": "^1.4.7"
} }
......
import {Request, Response} from 'express';
import {getErrorMessage} from '../utils/errors.util';
import * as userServices from '../services/user';
// import {CustomRequest} from '../middleware/auth';
// export const loginOne = async (req: Request, res: Response) => {
// try {
// const foundUser = await userServices.login(req.body);
// res.status(200).send(foundUser);
// } catch (error) {
// return res.status(500).send(getErrorMessage(error));
// }
// };
export const registerOne = async (req: Request, res: Response) => {
try {
await userServices.register(req.body);
res.status(200).send('Inserted successfully');
} catch (error) {
return res.status(500).send(getErrorMessage(error));
}
};
...@@ -5,6 +5,7 @@ import {mongoose} from './repository/mongoose'; ...@@ -5,6 +5,7 @@ import {mongoose} from './repository/mongoose';
import {ArtistRouter} from './routes/artist'; import {ArtistRouter} from './routes/artist';
import {AlbumRouter} from './routes/albums'; import {AlbumRouter} from './routes/albums';
import {TrackRouter} from './routes/track'; import {TrackRouter} from './routes/track';
import {UsersRouter} from './routes/user';
mongoose.run(); mongoose.run();
...@@ -17,6 +18,7 @@ app.use(express.static('images')); ...@@ -17,6 +18,7 @@ app.use(express.static('images'));
app.use('/artists', ArtistRouter); app.use('/artists', ArtistRouter);
app.use('/albums', AlbumRouter); app.use('/albums', AlbumRouter);
app.use('/tracks', TrackRouter); app.use('/tracks', TrackRouter);
app.use('/users', UsersRouter);
app.listen(process.env.PORT, () => { app.listen(process.env.PORT, () => {
console.log(`App started on port ${process.env.PORT}`); console.log(`App started on port ${process.env.PORT}`);
......
import mongoose from 'mongoose';
export default interface IUser extends mongoose.Document {
username: string;
password: string;
token: string;
}
import jwt, {Secret, JwtPayload} from 'jsonwebtoken';
import {Request, Response, NextFunction} from 'express';
export const SECRET_KEY: Secret =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsZW4gQm9sYXRvdiIsImlhdCI6MTUxNjIzOTAyMn0.d2_x9z4HZivq8qQUvKEhgROH_zLKwV82bC0a0hXaIvY';
export interface CustomRequest extends Request {
token: string | JwtPayload;
}
export const auth = async (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
throw new Error();
}
const decoded = jwt.verify(token, SECRET_KEY);
(req as CustomRequest).token = decoded;
next();
} catch (err) {
res.status(401).send('Please authenticate');
}
};
import mongoose, {model} from 'mongoose';
import IUser from '../interfaces/IUser';
import bcrypt from 'bcrypt';
const UserSchema: mongoose.Schema<IUser> = new mongoose.Schema<IUser>(
{
username: {
type: String,
required: [true, 'Username is required'],
trim: true,
unique: true,
index: true,
},
password: {
type: String,
required: [true, 'Password is required'],
},
token: {
type: String,
},
},
{versionKey: false}
);
const saltRounds = 8;
UserSchema.pre('save', async function (next) {
const user = this;
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, saltRounds);
}
next();
});
const UserModel = model<IUser>('user', UserSchema);
UserModel.createIndexes();
export default UserModel;
import {Router} from 'express';
import * as userController from '../controllers/user';
const router: Router = Router();
router.post('/', userController.registerOne);
router.post('/sessions', userController.loginOne);
export {router as UsersRouter};
import IUser from '../interfaces/IUser';
import UserModel from '../models/user';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import {SECRET_KEY} from '../middleware/auth';
export async function register(user: IUser): Promise<void> {
try {
await UserModel.create(user);
} catch (error) {
throw error;
}
}
export async function login(user: IUser) {
try {
const foundUser = await UserModel.findOne({username: user.username});
if (!foundUser) {
throw new Error('Name of user is not correct');
}
const isMatch = bcrypt.compareSync(user.password, foundUser.password);
if (isMatch) {
const token = jwt.sign(
{_id: foundUser._id?.toString(), username: foundUser.username},
SECRET_KEY,
{
expiresIn: '2 days',
}
);
await UserModel.findOneAndUpdate({username: user.username}, {token});
return {token: token};
} else {
throw new Error('Password is not correct');
}
} catch (error) {
throw error;
}
}
declare global { declare global {
namespace NodeJS { namespace NodeJS {
interface ProcessEnv { interface ProcessEnv {
PORT: string; PORT: string;
MONGO_URL: string; MONGO_URL: string;
} }
} }
} }
export {}; export {};
export function getErrorMessage(error: unknown) {
if (error instanceof Error) return error.message;
return String(error);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment