Skip to content

Commit

Permalink
feat(user controller): created API for email update
Browse files Browse the repository at this point in the history
feat #49
  • Loading branch information
alejandrosaenz117 committed Oct 9, 2020
1 parent 4aef2fe commit bcbab8f
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 8 deletions.
8 changes: 5 additions & 3 deletions frontend/src/app/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Tokens } from './interfaces/Tokens';
providedIn: 'root',
})
export class AuthService {
constructor(private http: HttpClient) { }
constructor(private http: HttpClient) {}

api = environment.apiUrl;
isLoggedIn = false;
Expand Down Expand Up @@ -54,8 +54,10 @@ export class AuthService {
});
}

updateUserEmail(newEmail: string) {

updateUserEmail(email: string) {
return this.http.post(`${this.api}/user/email`, {
email,
});
}

refreshSession() {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/app/interfaces/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export interface User {
firstName: string;
lastName: string;
title: string;
email?: string;
}
2 changes: 1 addition & 1 deletion frontend/src/app/user-profile/user-profile.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ <h4>Contact Information</h4>
</div>
</div>
<div id="formContent">
<form [formGroup]="emailForm" (ngSubmit)="onSubmit(emailForm)" id="emailForm">
<form [formGroup]="emailForm" (ngSubmit)="onEmailFormSubmit(emailForm)" id="emailForm">
<div class="col-md-12">
<div class="form-group row">
<label for="email" class="col-4 col-form-label">Email:</label>
Expand Down
14 changes: 12 additions & 2 deletions frontend/src/app/user-profile/user-profile.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export class UserProfileComponent implements OnInit {
this.user = user;
this.rebuildForm();
this.rebuildSecurityForm();
this.rebuildEmailForm();
});
}

Expand Down Expand Up @@ -79,7 +80,9 @@ export class UserProfileComponent implements OnInit {
}

rebuildEmailForm() {
this.emailForm.reset({});
this.emailForm.reset({
email: this.user.email,
});
}
onSubmit(form: FormGroup) {
if (!this.isEdit) {
Expand Down Expand Up @@ -124,7 +127,14 @@ export class UserProfileComponent implements OnInit {
this.isEmailEdit = true;
this.emailForm.enable();
} else {
// this.authService.updateUserEmail
this.authService
.updateUserEmail(form.value.email)
.subscribe((res: string) => {
this.alertService.success(res);
this.isEmailEdit = false;
this.emailForm.disable();
this.emailForm.reset();
});
}
}
}
6 changes: 4 additions & 2 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,14 @@ app.set('serverIpAddress', serverIpAddress);
app.listen(serverPort, () => console.info(`Server running on ${serverIpAddress}:${serverPort}`));
// create typeorm connection
createConnection().then((_) => {
// Check for initial configuration
// If none exist, insert it
// Check for initial configuration and user
// If none exist, insert
configController.initialInsert();
// register routes
app.post('/api/user/register', userController.register);
app.post('/api/user/invite', jwtMiddleware.checkToken, userController.invite);
app.post('/api/user/email', jwtMiddleware.checkToken, userController.updateUserEmail);
// app.get('/api/user/email', jwtMiddleware.checkToken);
app.patch('/api/user', jwtMiddleware.checkToken, userController.patch);
app.get('/api/user', jwtMiddleware.checkToken, userController.getUser);
app.get('/api/users', jwtMiddleware.checkToken, userController.getUsers);
Expand Down
37 changes: 37 additions & 0 deletions src/routes/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,40 @@ export const getUsersById = async (userIds: number[]) => {
}
return userArray;
};
/**
* @description Send email update request
* @param {UserRequest} req
* @param {Response} res
* @returns string
*/
export const updateUserEmail = async (req: UserRequest, res: Response) => {
const email = req.body.email;
if (!email) {
return res.status(400).json('Email is invalid');
}
const user = await getConnection().getRepository(User).findOne(req.user);
const emails = await getConnection()
.getRepository(User)
.find({ select: ['email'] });
const existingEmails = emails.map((x) => x.email);
if (existingEmails.includes(email)) {
return res.status(400).json('Email is already taken');
}
user.uuid = uuidv4();
user.newEmail = email;
const errors = await validate(user);
if (errors.length > 0) {
return res.status(400).json('Email is invalid');
} else {
await getConnection().getRepository(User).save(user);
emailService.sendUpdateUserEmail(user, (err, info) => {
if (err) {
return res
.status(400)
.json('There was a problem updating your email address. Please contact an administrator for assistance.');
} else {
return res.status(200).json(`A confirmation email has been sent to ${user.newEmail}`);
}
});
}
};
22 changes: 22 additions & 0 deletions src/services/email.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import nodemailer = require('nodemailer');
import { getConnection } from 'typeorm';
import { Config } from '../entity/Config';
import { decrypt } from '../utilities/crypto.utility';
import { User } from '../entity/User';

/**
* @description Send email
Expand Down Expand Up @@ -104,3 +105,24 @@ export const sendInvitationEmail = (uuid, userEmail) => {
}
});
};

/**
* @description Prepare invitation email
* @param {string} uuid
* @returns string
*/
export const sendUpdateUserEmail = (user: User, callback) => {
const mailOptions = {
from: process.env.FROM_EMAIL,
subject: 'Bulwark - Email update request',
text: `An email update has been requested for Bulwark. Please click the link to confirm this update. ${process.env.PROD_URL}/#/register/${user.uuid}`,
to: user.newEmail
};
sendEmail(mailOptions, (err, info) => {
if (err) {
callback(err);
} else {
callback(null, info);
}
});
};

0 comments on commit bcbab8f

Please sign in to comment.