Skip to content

Commit c55bfa9

Browse files
Merge pull request #4 from kennie-larkson/authentication
feat(): added auth service, auth controller and cookies is set
2 parents 300e36f + 51b6860 commit c55bfa9

10 files changed

+66
-38
lines changed

README.md

+1-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
## How to run the code
44

55
1. Clone to repo in your favorite directory using the command `git clone https://github.com/kennie-larkson/weblog.git`
6-
2. CD into the `teesas` folder and run the command `npm install` to install the dependencies.
6+
2. CD into the `weblog` folder and run the command `npm install` to install the dependencies.
77
3. Create a .env file with the contents of .env.local. Also ensure to have docker running on your machine and create your docker.env file since the docker-compose.yml will be needing the environment variables.
88
4. Run the command `npm start` to start the application
99
5. Visit the postman collection file for a link to test all endpoint
@@ -12,6 +12,3 @@
1212

1313
1. User
1414
2. Post
15-
3. Topic
16-
17-
## Data structure :

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"main": "index.js",
66
"scripts": {
77
"start": "nodemon index.js",
8-
"dev": "npx nodemon ./src/server.ts",
8+
"dev": "ts-node ./src/server.ts",
99
"test": "nyc mocha --timeout 10000"
1010
},
1111
"keywords": [],

src/authentication/authentication.controller.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export default class AuthController {
2828
const userData: ICreateUser = request.body;
2929
try {
3030
const { cookie, user } = await this.authService.register(userData);
31-
console.log({ user, cookie });
31+
// console.log({ user, cookie });
3232
response.setHeader("Set-Cookie", [cookie]);
3333
response.send(user);
3434
} catch (error) {

src/authentication/authentication.service.ts

+11-5
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import AppDataSource from "./../data-source";
55
import User from "./../entity/users/user.entity";
66
import ITokenData from "./../interfaces/tokenData.interface";
77
import IDataStoredInToken from "./../interfaces/dataStoredInToken.interface";
8+
import ThereIsAlreadyAUserWithThatEmail from "../exceptions/DuplicateEmailRegistrationException";
89

910
export default class AuthenticationService {
1011
public async register(userData: ICreateUser) {
@@ -13,9 +14,11 @@ export default class AuthenticationService {
1314
.getRepository(User)
1415
.findOneBy({ email: userData.email })
1516
) {
16-
throw new Error(
17-
"Sorry there is a user with that email already. Please, try another."
18-
);
17+
throw new ThereIsAlreadyAUserWithThatEmail(userData.email);
18+
19+
// throw new Error(
20+
// "Sorry there is a user with that email already. Please, try another."
21+
// );
1922
}
2023

2124
const hashedPassword = await bcrypt.hash(userData.password, 10);
@@ -33,11 +36,14 @@ export default class AuthenticationService {
3336
}
3437

3538
public createToken(user: User): ITokenData {
36-
const expiresIn = 60 * 60;
39+
const expiresIn = 60 * 60; // an hour
3740
const secret = process.env.JWT_SECRET;
3841
const dataStoredInToken: IDataStoredInToken = { id: user.id };
3942

40-
return { expiresIn, token: jwt.sign(dataStoredInToken, secret, {}) };
43+
return {
44+
expiresIn,
45+
token: jwt.sign(dataStoredInToken, secret, { expiresIn }),
46+
};
4147
}
4248

4349
public createCookie(tokenData: ITokenData) {

src/entity/posts/post.controller.ts

+27-23
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import express from "express";
22
import IPost from "./post.interface";
33
import { validatePostForm } from "./../../middleware/validation.middleware";
4+
import PostNotFoundException from "./../../exceptions/PostNotFoundException";
45

56
import AppDataSource from "./../../data-source";
67
import { NextFunction, Request, Response } from "express";
@@ -22,73 +23,76 @@ export default class PostController {
2223
this.router.patch(`${this.path}/:id`, this.updatePost);
2324
}
2425

25-
public async getAllPosts(
26-
request: Request,
27-
response: Response,
28-
next: NextFunction
29-
) {
26+
public async getAllPosts(req: Request, res: Response, next: NextFunction) {
3027
try {
3128
const posts = await AppDataSource.manager
3229
.getRepository(Post)
3330
.find({ relations: { author: true } });
34-
return response.json(posts);
31+
return res.json(posts);
3532
} catch (error) {
36-
return response.json(error);
33+
return res.json(error);
3734
}
3835
}
3936

40-
async getPostById(request: Request, response: Response, next: NextFunction) {
41-
const { id } = request.params;
42-
return AppDataSource.manager.findOneBy(Post, { id: Number(id) });
37+
async getPostById(req: Request, res: Response, next: NextFunction) {
38+
const { id } = req.params;
39+
const post: IPost = await AppDataSource.manager.findOneBy(Post, {
40+
id: Number(id),
41+
});
42+
if (post) {
43+
return res.status(200).json(post);
44+
}
45+
next(new PostNotFoundException(Number(id)));
4346
}
4447

45-
async createPost(request: Request, response: Response, next: NextFunction) {
46-
const post: IPost = request.body;
47-
//const post = request.body;
48+
async createPost(req: Request, res: Response, next: NextFunction) {
49+
const post: IPost = req.body;
50+
4851
try {
4952
const createdPost = AppDataSource.manager
5053
.getRepository(Post)
5154
.create(post);
5255
const result = await AppDataSource.manager
5356
.getRepository(Post)
5457
.save(createdPost);
55-
return response.json(result);
58+
return res.json(result);
5659
} catch (error) {
57-
return response.json(error);
60+
//return res.json(error);
61+
next(error);
5862
}
5963
}
6064

61-
async removePost(request: Request, response: Response, next: NextFunction) {
62-
const { id } = request.params;
65+
async removePost(req: Request, res: Response, next: NextFunction) {
66+
const { id } = req.params;
6367
let postToRemove = await AppDataSource.manager.findOneBy(Post, {
6468
id: Number(id),
6569
});
6670
await AppDataSource.manager.remove(postToRemove);
6771
}
6872

69-
async updatePost(request: Request, response: Response, next: NextFunction) {
70-
const { id } = request.params;
71-
const update = request.body;
73+
async updatePost(req: Request, res: Response, next: NextFunction) {
74+
const { id } = req.params;
75+
const update = req.body;
7276
console.log(update);
7377

7478
try {
7579
const postToUpdate = await AppDataSource.getRepository(Post).findOneBy({
7680
id: Number(id),
7781
});
7882
if (!postToUpdate) {
79-
return response.json({ message: `Unable to find post with id ${id}` });
83+
return res.json({ message: `Unable to find post with id ${id}` });
8084
}
8185
AppDataSource.getRepository(Post).merge(postToUpdate, update);
8286
const updatedPost = await AppDataSource.getRepository(Post).save(
8387
postToUpdate
8488
);
8589

86-
return response.json({
90+
return res.json({
8791
message: `Successfully updated data for post with id: ${id}.`,
8892
updatedPost,
8993
});
9094
} catch (error) {
91-
return response.json(error);
95+
return res.json(error);
9296
}
9397
}
9498
}

src/entity/posts/post.interface.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import User from "entity/users/user.entity";
22

33
interface IPost {
4+
id?: number;
45
content: string;
56
title: string;
67
author: Partial<User>;

src/entity/users/user.entity.ts

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from "typeorm";
1+
import {
2+
Entity,
3+
Column,
4+
PrimaryGeneratedColumn,
5+
OneToMany,
6+
JoinColumn,
7+
} from "typeorm";
28
import "reflect-metadata";
39
import Post from "../posts/post.entity";
410

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import HttpExceptions from "./HttpExceptions";
2+
3+
export default class ThereIsAlreadyAUserWithThatEmail extends HttpExceptions {
4+
constructor(email: string) {
5+
super(400, `A user with the email ${email} already exists.`);
6+
}
7+
}
+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import HttpExceptions from "./HttpExceptions";
2+
3+
export default class PostNotFoundException extends HttpExceptions {
4+
constructor(id: number) {
5+
super(400, `Cannot find Post with id ${id}.`);
6+
}
7+
}

tsconfig.json

+3-3
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"experimentalDecorators": true,
1010
"moduleResolution": "node",
1111
"allowSyntheticDefaultImports": true
12-
}
13-
// "include": ["src/**/*.ts"],
14-
// "exclude": ["node_modules"]
12+
},
13+
"include": ["src/**/*.ts"],
14+
"exclude": ["node_modules"]
1515
}

0 commit comments

Comments
 (0)