Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 1b4a084

Browse filesBrowse files
Merge pull request #22 from app-generator/evolution3/roles-authorization
Implemented roles authorization
2 parents 32aa30a + f9e3324 commit 1b4a084
Copy full SHA for 1b4a084

File tree

7 files changed

+39
-11
lines changed
Filter options

7 files changed

+39
-11
lines changed

‎src/constants/index.ts

Copy file name to clipboard
+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const DEFAULT_ROLE = 'user'
2+
3+
export {DEFAULT_ROLE}

‎src/controllers/auth.controller.ts

Copy file name to clipboardExpand all lines: src/controllers/auth.controller.ts
+3-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
} from '../services/session.service';
66
import { createUserWithToken } from '../services/user.service';
77

8+
const frontend_url = process.env.FRONTEND_URL ?? '/'
89

910
export const githubOauthHandler = async (
1011
req: Request,
@@ -14,7 +15,7 @@ export const githubOauthHandler = async (
1415
const code = req.query.code as string;
1516

1617
if (req.query.error) {
17-
return res.redirect(`http://localhost:3000/login`);
18+
return res.redirect(`${frontend_url}/login`);
1819
}
1920

2021
if (!code) {
@@ -29,7 +30,7 @@ export const githubOauthHandler = async (
2930

3031
const returnedUser = await createUserWithToken(userData)
3132
if(returnedUser) {
32-
res.redirect(`http://localhost:3000`);
33+
res.redirect(frontend_url);
3334
}else {
3435
res.json({error: 'no user returned'})
3536
}

‎src/migrations/1626737786922-init.ts

Copy file name to clipboardExpand all lines: src/migrations/1626737786922-init.ts
+4-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ export class init1626737786922 implements MigrationInterface {
55

66
public async up(queryRunner: QueryRunner): Promise<void> {
77
await queryRunner.query(`CREATE TABLE "active_session" ("id" varchar PRIMARY KEY NOT NULL, "token" text NOT NULL, "userId" text NOT NULL, "date" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP))`);
8-
await queryRunner.query(`CREATE TABLE "user" ("id" varchar PRIMARY KEY NOT NULL, "username" text NOT NULL, "email" text, "password" text, "date" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP))`);
8+
await queryRunner.query(`CREATE TABLE "user" ("id" varchar PRIMARY KEY NOT NULL, "username" text NOT NULL, "email" text, "password" text, "user_role" varchar, "date" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP))`);
9+
await queryRunner.query(`CREATE TABLE "role" ("id" varchar PRIMARY KEY NOT NULL, "name" text NOT NULL, "date" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP))`)
10+
await queryRunner.query(`INSERT INTO role ("id", "name") VALUES(1, 'admin')`)
11+
await queryRunner.query(`INSERT INTO role ("id", "name") VALUES(2, 'user')`)
912
}
1013

1114
public async down(queryRunner: QueryRunner): Promise<void> {

‎src/models/role.ts

Copy file name to clipboard
+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
2+
3+
@Entity()
4+
export default class Role {
5+
@PrimaryGeneratedColumn('uuid')
6+
id!: string;
7+
8+
@Column({ type: 'text', nullable: false })
9+
name!: string;
10+
11+
@Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })
12+
date?: string;
13+
}

‎src/models/user.ts

Copy file name to clipboardExpand all lines: src/models/user.ts
+3
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,7 @@ export default class User {
1616

1717
@Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })
1818
date?: string;
19+
20+
@Column({type: 'text'})
21+
user_role!: string
1922
}

‎src/server/database.ts

Copy file name to clipboardExpand all lines: src/server/database.ts
+2-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { Connection, ConnectionOptions, createConnection } from 'typeorm';
44

55
import ActiveSession from '../models/activeSession';
66
import User from '../models/user';
7+
import Role from '../models/role';
78

89
if (!process.env.SQLITE_PATH) {
910
throw new Error('SQLITE_PATH environment variable is not set.');
@@ -12,7 +13,7 @@ if (!process.env.SQLITE_PATH) {
1213
const options: ConnectionOptions = {
1314
type: 'sqlite',
1415
database: process.env.SQLITE_PATH,
15-
entities: [User, ActiveSession],
16+
entities: [User, ActiveSession, Role],
1617
logging: true,
1718
};
1819

‎src/services/user.service.ts

Copy file name to clipboardExpand all lines: src/services/user.service.ts
+11-7
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,35 @@
11
import jwt from "jsonwebtoken";
22
import User from "../models/user";
3+
import Role from '../models/role'
34
import ActiveSession from "../models/activeSession";
45
import { connection } from "../server/database";
6+
import {DEFAULT_ROLE} from '../constants'
57

68
export const createUserWithToken = async (userData: any) => {
9+
const userRole = DEFAULT_ROLE
710
const userRepository = connection!.getRepository(User);
811
const activeSessionRepository = connection!.getRepository(ActiveSession);
12+
const roleRepository = connection!.getRepository(Role)
913

1014
const { login: username, email } = userData;
1115
let requiredUser: any = null;
1216

1317
const user = await userRepository.findOne({ username });
18+
const role = await roleRepository.findOne({name: userRole})
19+
if(!role) {
20+
throw new Error(`no role exists for ${userRole} in db`)
21+
}
1422

1523
if (user) {
1624
requiredUser = user;
1725
} else {
1826
const query = {
1927
username,
2028
email,
29+
user_role: role.id
2130
};
22-
userRepository.save(query).then((u) => {
23-
console.log("u", u);
24-
requiredUser = u;
25-
});
31+
const u = await userRepository.save(query)
32+
requiredUser = u;
2633
}
2734

2835
if (!process.env.SECRET) {
@@ -40,10 +47,7 @@ export const createUserWithToken = async (userData: any) => {
4047
expiresIn: 86400, // 1 week
4148
}
4249
);
43-
4450
const query = { userId: requiredUser.id, token };
45-
46-
console.log("query", query);
4751
activeSessionRepository.save(query);
4852
requiredUser.token = token;
4953
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.