Add api endpoints for login and registration

This commit is contained in:
QiTao Weng 2022-04-09 20:46:30 -05:00
parent 8e99d91701
commit 54dad8013b
2 changed files with 53 additions and 6 deletions

View File

@ -1,4 +1,4 @@
import {Controller, view, Inject, Injectable, SecurityContext, api} from '@extollo/lib' import {Controller, make, view, Inject, Injectable, SecurityContext, api, Safe, redirect, UserAuthenticationResumedEvent} from '@extollo/lib'
import {User} from '../../../models/User.model' import {User} from '../../../models/User.model'
/** /**
@ -26,7 +26,50 @@ export class Login extends Controller {
return api.one(user) return api.one(user)
} }
public async callbackFromAuth0() { public async login() {
return api.error('Implement me!') const email = this.request.safe('email').string()
const password = this.request.safe('password').string()
const user = await User.query<User>()
.where('username', '=', email).first()
if ( !user ) {
return api.error('Do I know you?')
}
const verify = await user.verifyPassword(password)
if ( !verify ) {
return api.error('Bruv, invalid password.')
}
await this.security.authenticate(user)
return redirect('/')
}
public async register() {
const name = this.request.safe('name').string()
const email = this.request.safe('email').string()
const password = this.request.safe('password').string()
// lookup user for conflict
const user = await User.query<User>()
.where('username', '=', email).first()
if ( user ) {
return api.error('You\'ve got a doppleganger')
}
// else, create new user and save to db
const newUser = make<User>(User)
newUser.firstName = name
newUser.lastName = ''
newUser.username = email
await newUser.setPassword(password)
await newUser.save()
// then login
await this.security.authenticate(newUser)
return redirect('/')
} }
} }

View File

@ -13,14 +13,18 @@ Route.group('/', () => {
})) }))
Route.group('/login', () => { Route.group('/login', () => {
Route.post('/')
.calls<Login>(Login, login => login.login)
Route.get('/status') Route.get('/status')
.calls<Login>(Login, login => login.status) .calls<Login>(Login, login => login.status)
Route.get('/user') Route.get('/user')
.calls<Login>(Login, login => login.user) .calls<Login>(Login, login => login.user)
Route.post('/user')
.calls<Login>(Login, login => login.callbackFromAuth0)
}) })
Route.post('/register')
.calls<Login>(Login, login => login.register)
}) })
}).pre(SessionAuthMiddleware) }).pre(SessionAuthMiddleware)