Skip to content

Instantly share code, notes, and snippets.

@RWOverdijk
Created November 21, 2018 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RWOverdijk/678e3acdfdf6ac116086acbb75613507 to your computer and use it in GitHub Desktop.
Save RWOverdijk/678e3acdfdf6ac116086acbb75613507 to your computer and use it in GitHub Desktop.
import { AbstractActionController, ContextInterface, inject } from 'stix';
import { dbActions, WetlandService, BodyParamType } from 'stix-wetland';
import { User } from '../Entity/User';
import { compare } from 'bcrypt';
import { AuthService } from '../Service/AuthService/AuthService';
@dbActions(User)
export class UserController extends AbstractActionController {
@inject(WetlandService)
protected wetlandService: WetlandService;
@inject(AuthService)
protected authService: AuthService;
public async register ({ request: { body } }: BodyParamType) {
const manager = this.wetlandService.getManager();
const newUser = this.wetlandService.getPopulator(manager).assign<User>(User, body, null, false);
await manager.flush();
return this.createdResponse(this.authService.sign(newUser));
}
public async login ({ request: { body } }: BodyParamType) {
const { email, password } = body;
const user = await this.wetlandService.getRepository(User).findOne({ email });
if (!user || !await compare(password, user.password)) {
return this.unauthorizedResponse('invalid_credentials');
}
return this.okResponse(this.authService.sign(user));
}
public async me (ctx: ContextInterface) {
const { payload: { id } } = ctx.state.authorization;
const user = await this.wetlandService.getRepository(User).findOne(id);
if (!user) {
return this.internalServerErrorResponse('no_user');
}
return this.okResponse({ user: this.authService.sign(user) });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment