This repository has been archived on 2024-12-15. You can view files and clone it, but cannot push or open issues or pull requests.
seepur/app/Controllers/Http/AuthController.js
Sagi Dayan accbc5c35c First implementation of email service
- Sending welcome email uppon register
 - Test email configuration API for admins
 - basic reset password - not implemented
2020-05-12 21:30:11 -04:00

85 lines
2.2 KiB
JavaScript

'use strict'
const User = use('App/Models/User');
const EmailUtils = use('App/Utils/EmailUtils');
class AuthController {
async registerIndex({view, auth, response}) {
if (auth.user) {
response.redirect('/');
return;
}
return view.render('register')
}
async loginIndex({view, auth, response}) {
if (auth.user) {
response.redirect('/');
return;
}
return view.render('login')
}
async register({request, response, view, session, auth}) {
const user = await User.create({
email: request.input('email'),
name: request.input('name'),
password: request.input('password'),
avatar:
`https://api.adorable.io/avatars/285/${request.input('email')}.png`
});
if (user.id == 1) {
user.is_admin = true;
}
await user.save();
await auth.login(user);
await EmailUtils.sendWelcomeEmail(user);
response.redirect('/');
}
async login({request, response, auth, session}) {
console.log('login');
const {email, password} = request.all()
console.log({email, password})
try {
const token = await auth.attempt(email, password);
const user = auth.user;
// user.last_logged_in = new Date();
// await user.save();
console.log('logged in');
} catch (e) {
console.error(e);
session.withErrors({loginError: 'Invalid Credentials'}).flashAll()
return response.redirect('back')
}
response.redirect('/');
}
async resetPassword({request, response, session}) {
const email = request.body.email;
const token = 'token'; // TODO: Token system
const sent =
await EmailUtils.sendResetPassword({name: 'test name', email}, token);
if (sent) {
response.redirect('/');
return;
}
session.withErrors({message: 'Email provider error'}).flashAll()
return response.redirect('back')
}
async resetPasswordIndex({request, auth, response, view}) {
if (auth.user) {
response.redirect('/');
return;
}
return view.render('reset-password');
}
async resetPasswordForm({request}) {}
async logout({auth, response}) {
await auth.logout();
response.redirect('/');
}
}
module.exports = AuthController