Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import {
Context, Delete, Get, HttpResponseCreated, HttpResponseNoContent,
HttpResponseNotFound, HttpResponseOK, Post,
TokenRequired, ValidateBody, ValidatePathParam
} from '@foal/core';
import { fetchUser, TypeORMStore } from '@foal/typeorm';
import { getRepository } from 'typeorm';
import { Todo, User } from '../entities';
@TokenRequired({
cookie: true,
store: TypeORMStore,
// Make ctx.user be an instance of User.
user: fetchUser(User),
})
export class ApiController {
@Get('/todos')
async getTodos(ctx: Context) {
const todos = await getRepository(Todo).find({ owner: ctx.user });
return new HttpResponseOK(todos);
}
@Post('/todos')
@ValidateBody({
// The body request should be an object once parsed by the framework.
// Every additional properties that are not defined in the "properties"
// object should be removed.
additionalProperties: false,
properties: {
@Column()
password: string;
}
const credentialsSchema = {
additionalProperties: false,
properties: {
email: { type: 'string', format: 'email' },
password: { type: 'string' }
},
required: [ 'email', 'password' ],
type: 'object',
};
@JWTRequired({ user: fetchUser(User), blackList: isBlackListed })
class ApiController {
@Get('/products')
readProducts(ctx: Context) {
return new HttpResponseOK({
email: ctx.user.email
});
}
}
class AuthController {
@Post('/signup')
@ValidateBody(credentialsSchema)
async signup(ctx: Context) {
const user = new User();
user.email = ctx.request.body.email;
return blackList.includes(token);
}
@Entity()
class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ unique: true })
email: string;
@Column()
password: string;
}
@JWTRequired({ user: fetchUser(User), blackList: isBlackListed, cookie: true })
class ApiController {
@Get('/products')
readProducts(ctx: Context) {
return new HttpResponseOK({
email: ctx.user.email
});
}
}
const credentialsSchema = {
additionalProperties: false,
properties: {
email: { type: 'string', format: 'email' },
password: { type: 'string' }
},
required: [ 'email', 'password' ],
if (!user) {
return new HttpResponseRedirect('/signin');
}
if (!await verifyPassword(ctx.request.body.password, user.password)) {
return new HttpResponseRedirect('/signin');
}
const session = await this.store.createAndSaveSessionFromUser(user);
const response = new HttpResponseRedirect('/home');
setSessionCookie(response, session);
return response;
}
@Get('/home')
@TokenRequired({ redirectTo: '/signin', user: fetchUser(User), store: TypeORMStore, cookie: true })
home() {
return new HttpResponseOK('Home!');
}
@Get('/signin')
signin() {
return new HttpResponseOK('Sign in!');
}
}
class AppController {
subControllers = [
MyController,
AuthController
];
}