Commit e5346cd0 authored by “Yevgeniy's avatar “Yevgeniy

#21 added routers requests for the registration and for login and logout

parent f1a2d847
......@@ -4,7 +4,6 @@ import {
PrimaryGeneratedColumn,
CreateDateColumn,
BeforeInsert,
BeforeUpdate,
BaseEntity,
ManyToMany,
OneToMany
......@@ -80,12 +79,7 @@ export class User extends BaseEntity implements IUser {
protected async beforeInserthashPassword():Promise<void> {
const salt = await bcrypt.genSalt(SALT_WORK_FACTOR);
this.password = await bcrypt.hash(this.password, salt);
}
@BeforeUpdate()
protected async beforeUpdateHashPassword():Promise<void> {
const salt = await bcrypt.genSalt(SALT_WORK_FACTOR);
this.password = await bcrypt.hash(this.password, salt);
}
public generateToken():void{
......@@ -93,11 +87,11 @@ export class User extends BaseEntity implements IUser {
return
}
static async comparePasswords(
public async checkPassword(
candidatePassword: string,
hashedPassword: string
):Promise<boolean> {
return await bcrypt.compare(candidatePassword, hashedPassword);
console.log("Checking password", candidatePassword,'this.password', this.password)
return await bcrypt.compare(candidatePassword, this.password);
}
......@@ -126,144 +120,3 @@ export class User extends BaseEntity implements IUser {
// const UserEntity = new EntitySchema<IUser>({
// name: "user",
// columns: {
// id: {
// type: "uuid",
// primary: true,
// generated: "uuid",
// },
// name: {
// nullable: false,
// type: String,
// length: 20,
// },
// surname: {
// nullable: false,
// type: String,
// length: 50,
// },
// password: {
// nullable: false,
// type: String,
// },
// email: {
// nullable: false,
// type: String,
// },
// displayName: {
// nullable: false,
// type: String,
// },
// role: {
// type: String,
// default: "user",
// enum: ["director","user"]
// },
// createdAt: {
// type: Date,
// default: Date.now(),
// },
// methods?:{
// type:String
// }
// },
// relations: {
// tasks: {
// type: "many-to-many",
// target: "category", // CategoryEntity
// },
// },
// })
// UserEntity.methods.checkPassword=function(password:string):Promise<boolean> {
// return bcrypt.compare(password,this.password);
// }
// export default UserEntity
// import { Schema, model } from 'mongoose';
// import bcrypt from 'bcrypt';
// import {nanoid} from 'nanoid';
// const SALT_WORK_FACTOR= 10;
// // 1. Create an interface representing a document in MongoDB.
// interface IUser {
// name: string;
// surname: string;
// email: string;
// displayName: string;
// password:string;
// role: string;
// }
// // 2. Create a Schema corresponding to the document interface.
// const UserSchema = new Schema<IUser>({
// name: { type: String, required: true },
// surname: { type: String, required: true },
// email: { type: String, required: true },
// displayName: { type: String, required: true },
// password: { type: String, required: true },
// role:{type:String,default: 'user',enum:['user','admin']}
// });
// // How does next's type defined?
// UserSchema.pre('save', async function(next:any):Promise<void>{
// if(!this.isModified('password')) return next();
// console.log('next', next)
// const salt = await bcrypt.genSalt(SALT_WORK_FACTOR);
// const hash = await bcrypt.hash(this.password, salt);
// this.password = hash;
// next();
// })
// UserSchema.set('toJSON',{
// transform:(doc:any, ret:any, options:any)=>{
// delete ret.password;
// return ret;
// }
// })
// UserSchema.methods.checkPassword =function(password:string):Promise<boolean>{
// return bcrypt.compare(password,this.password);
// }
// UserSchema.methods.generateToken =function(){
// this.token=nanoid();
// }
// // 3. Create a Model.
// const User = model<IUser>('User', UserSchema);
// export default User;
import express,{Router, Request, Response} from 'express';
import {User} from '../models/User';
import {myDataSource} from '../app-data-source';
import { nanoid } from 'nanoid';
const router:Router = express.Router();
const dataSource = myDataSource;
......@@ -12,6 +13,8 @@ return res.send({users})
router.post('/', async (req : Request, res : Response):Promise<object> => {
console.log('req.body',req.body)
const {name,surname,password,email} = req.body;
const displayName = surname+' '+name[0]+'.'
const user = new User();
......@@ -20,45 +23,61 @@ router.post('/', async (req : Request, res : Response):Promise<object> => {
user.password = password;
user.displayName= displayName;
user.email = email;
user.generateToken()
await user.save();
return res.send({user})
const userToFront:User|null = await dataSource.manager.findOneBy(User, {
email: user.email
})
return res.send({userToFront})
})
router.post('/sessions/', async (req : Request, res : Response):Promise<object> => {
console.log('req.body',req.body)
const user:User|null = await dataSource.getRepository(User)
.createQueryBuilder()
.select()
.addSelect("User.password")
.getOne()
if (!user) return res.status(400).send({
messageError: "User does not exist"
})
console.log( "user ",user, 'req.body.password',req.body.password)
const isMatch:boolean = await user.checkPassword(req.body.password);
if (!isMatch) return res.status(400).send({
error: "Wrong Password"
})
if (!isMatch) return res.status(400).send({
error: "Wrong Password"
})
const userToFront:User|null = await dataSource.manager.findOneBy(User, {
email: req.body.email
})
return res.send({
message: "message: 'Correct user & password",
user: userToFront
})
})
router.delete('/sessions', async(req: Request, res: Response):Promise<void | object> => {
const token = req.get('Authorization');
const successMsg = {message:'success'};
if(!token) return res.send(successMsg)
const user = await dataSource.manager.findOneBy(User, {
token: token
})
if(!user) return res.send({successMsg});
console.log('token: ' + token)
user.token = nanoid();
await user.save();
})
// router.post('/', async (req : Request, res : Response) => {
// try{
// const {name,surname,password,email} = req.body;
// const displayName = surname+' '+name[0]+'.'
// await User.insert({
// name:name,
// surname:surname,
// email:email,
// password:password,
// displayName:displayName
// })
// const user:User = new User({
// name:name,
// surname:surname,
// email:email,
// password:password,
// displayName:displayName
// })
// await user.save();
// return res.send({message:'created user'})
// }catch(e ){
// if (e instanceof Error){
// return res.status(404).send({'message':e.message});
// }
// return res.status(500).send({'message':'Broke server'});
// }
// })
// router.get('/', async (req : Request, res : Response):Promise<Response<any, Record<string, any>>> => {
// const users = await User.find()
// return res.send({users})
// })
export default router;
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