Skip to content

Commit 79834db

Browse files
committed
done: finish handeling errors invite page
1 parent 96eb46a commit 79834db

12 files changed

+248
-65
lines changed

package-lock.json

+5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+3-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@
2323
"pg": "^7.4.3",
2424
"request": "^2.87.0",
2525
"serve-favicon": "^2.5.0",
26-
"sweetalert": "^2.1.0"
26+
"sweetalert": "^2.1.0",
27+
"sweetalert2": "^7.20.10"
2728
},
2829
"devDependencies": {
2930
"eslint": "^4.19.1",
@@ -36,7 +37,7 @@
3637
},
3738
"scripts": {
3839
"test": "echo \"Error: no test specified\" && exit 1",
39-
"dev": "nodemon src/index.js",
40+
"dev": "ENV=development nodemon src/index.js",
4041
"start": "node src/index.js",
4142
"build": "node src/model/db_build.js"
4243
},

public/js/invite_st.js

+41
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,49 @@ unregisteredUl.addEventListener('click', (e) => {
3333
})
3434
.catch((err) => {
3535
console.log('There has been an error in delete student', err);
36+
swal('Oh no!', 'Some error happen, ple2wase try again', 'error')
37+
.then(() => { location.reload(); });
3638
});
3739
}
3840
});
3941
}
4042
});
43+
44+
const inviteForm = document.querySelector('#inviteByEmail');
45+
46+
inviteForm.addEventListener('submit', (e) => {
47+
e.preventDefault();
48+
const email = document.querySelector('#email').value;
49+
const data = JSON.stringify({ email });
50+
fetch('/invitebygmail', {
51+
credentials: 'include',
52+
headers: {
53+
'content-type': 'application/json',
54+
},
55+
method: 'POST',
56+
body: data,
57+
})
58+
.then(res => res.json())
59+
.then((res) => {
60+
if (res.exist) {
61+
swal('email exists', res.exist, 'error');
62+
} else {
63+
const oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
64+
const form = document.createElement('form');
65+
form.setAttribute('method', 'GET');
66+
form.setAttribute('action', oauth2Endpoint);
67+
// Add form parameters as hidden input values.
68+
// eslint-disable-next-line
69+
for (let p in res) {
70+
const input = document.createElement('input');
71+
input.setAttribute('type', 'hidden');
72+
input.setAttribute('name', p);
73+
input.setAttribute('value', res[p]);
74+
form.appendChild(input);
75+
}
76+
// Add form to page and submit it to open the OAuth 2.0 endpoint.
77+
document.body.appendChild(form);
78+
form.submit();
79+
}
80+
});
81+
});

src/controllers/check-outh.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
exports.isAuthenticated = (req, res, next) => {
22
if (req.isAuthenticated()) {
33
console.log('Authenticated');
4-
next();
4+
if (req.user.err) {
5+
res.redirect('https://google.ps');
6+
} else {
7+
next();
8+
}
59
} else {
610
console.log('Not Authenticated');
711
// IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM TO LOGIN PAGE

src/controllers/email-setup.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
exports.email = (studentEmail, cohortName, githubLoginLink) => {
2+
const emailLines = [];
3+
emailLines.push(`To: ${studentEmail}`);
4+
emailLines.push('Content-type: text/html');
5+
emailLines.push('MIME-Version: 1.0');
6+
emailLines.push('Subject: Invitation for facgtracker');
7+
emailLines.push('');
8+
emailLines.push('<h2>Invitation to sign up at facgtracker</h2>');
9+
emailLines.push(`<b>Hello ${cohortName} students</b><br>`);
10+
emailLines.push(`you are invited to Set up your account at facgtracker web app, please use<br><a href="${githubLoginLink}">this link</a> to log in with your github account that associated with this email ${studentEmail}`);
11+
emailLines.push('<br>if you have any trouble loging in please reply to this email');
12+
const email = emailLines.join('\r\n').trim();
13+
let base64EncodedEmail = Buffer.from(email).toString('base64');
14+
base64EncodedEmail = base64EncodedEmail.replace(/\+/g, '-').replace(/\//g, '_');
15+
return base64EncodedEmail;
16+
};
17+

src/controllers/index.js

-1
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,4 @@ router.get('/', isAuthenticated, home.get)
2828
failureRedirect: '/login',
2929
}), githubLogin.githubCb);
3030

31-
3231
module.exports = router;

src/controllers/invite.js

+60-52
Original file line numberDiff line numberDiff line change
@@ -1,89 +1,97 @@
11
const { google } = require('googleapis');
22
const inviteStudent = require('../model/quires/invite_student');
3+
const emailSetup = require('./email-setup');
34
require('env2')('./config.env');
45

5-
const oauth2Client = new google.auth.OAuth2(
6-
process.env.GMAILCLIENTID,
7-
process.env.GMAILSECRETE,
8-
'http://localhost:3000/gmail/cb'
9-
);
6+
const gmailCbUrl = process.env.ENV === 'production' ? 'https://facgtracker.herokuapp.com/gmail/cb' : 'http://localhost:3000/gmail/cb';
107
const scopes = [
118
'https://www.googleapis.com/auth/gmail.send'
129
];
13-
const url = oauth2Client.generateAuthUrl({
14-
access_type: 'online',
15-
response_type: 'code',
16-
scope: scopes
17-
});
10+
const cohortId = 1;
1811
let studentEmail;
19-
exports.get = (req, res) => {
20-
const cohortId = 1;
21-
inviteStudent.getunregisteredStudents(cohortId, (err, emails) => {
22-
if (err) {
23-
console.error('get unregistered students', err);
12+
13+
exports.get = (req, res, next) => {
14+
inviteStudent.getunregisteredStudents(cohortId, (getUnregisteredError, emails) => {
15+
if (getUnregisteredError) {
16+
console.error('get unregistered students', getUnregisteredError);
17+
next(getUnregisteredError);
18+
} else {
19+
res.render('inviteSt', {
20+
emails,
21+
style: [
22+
'manage_student_style.css', 'invite_students.css'
23+
],
24+
script: [
25+
'manage_st_dom.js',
26+
'invite_st.js'
27+
]
28+
});
2429
}
25-
res.render('inviteSt', { emails, style: ['manage_student_style.css', 'invite_students.css'], script: ['manage_st_dom.js', 'invite_st.js'] });
2630
});
2731
};
2832

29-
exports.getcode = (req, res) => {
30-
studentEmail = req.body.studentEmail;
31-
res.redirect(url);
32-
};
33-
exports.gettoken = (req, res) => {
34-
const cohortId = 1;
33+
exports.getcode = (req, res, next) => {
34+
studentEmail = req.body.email;
3535
inviteStudent.checkInviteEmail(studentEmail, (checkInviteEmailError, exist) => {
3636
if (checkInviteEmailError) {
37-
// handel error
3837
console.error('checkInviteEmail error', checkInviteEmailError);
38+
next(checkInviteEmailError);
3939
} else if (exist[0].exists) {
40-
// sweet alert email already exist
41-
console.log('checkInviteEmail', exist);
42-
res.redirect('/inviteSt');
40+
res.send({ exist: 'The email exist' });
4341
} else {
44-
const githubloginLink = 'http://localhost:3000/github';
45-
oauth2Client.getToken(req.query.code, (err, tokens) => {
46-
console.log('tokens', tokens);
42+
const data = {
43+
client_id: process.env.GMAILCLIENTID,
44+
redirect_uri: gmailCbUrl,
45+
response_type: 'code',
46+
scope: scopes[0]
47+
};
48+
res.send(data);
49+
}
50+
});
51+
};
52+
53+
exports.gettoken = (req, res, next) => {
54+
const oauth2Client = new google.auth.OAuth2(
55+
process.env.GMAILCLIENTID,
56+
process.env.GMAILSECRETE,
57+
gmailCbUrl
58+
);
59+
const githubloginLink = 'https://facgtracker.herokuapp.com/login';
60+
if (!req.query.code) {
61+
console.error('No auth code');
62+
next('No autherisation code');
63+
} else {
64+
oauth2Client.getToken(req.query.code, (err, tokens) => {
65+
if (err) {
66+
console.error('getTokenerr', err);
67+
next(err);
68+
} else {
4769
oauth2Client.setCredentials(tokens);
4870
const gmail = google.gmail('v1');
49-
const emailLines = [];
50-
emailLines.push('From: [email protected]');
51-
emailLines.push(`To: ${studentEmail}`);
52-
emailLines.push('Content-type: text/html;charset=iso-8859-1');
53-
emailLines.push('MIME-Version: 1.0');
54-
emailLines.push('Subject: Invitation for facgtracker');
55-
emailLines.push('');
56-
emailLines.push('<h2>Invitation to sign up at facgtracker</h2>');
57-
emailLines.push('<b>Hello facg5 students</b><br>');
58-
emailLines.push(`you are invited to Set up your account at facgtracker web app, please use<br> this <a href="${githubloginLink}">link</a> to log in with your github account that associated with this email ${studentEmail}`);
59-
emailLines.push('<br>if you have any trouble loging in please reply to this email');
60-
const email = emailLines.join('\r\n').trim();
61-
let base64EncodedEmail = Buffer.from(email).toString('base64');
62-
base64EncodedEmail = base64EncodedEmail.replace(/\+/g, '-').replace(/\//g, '_');
71+
const base64EncodedEmail = emailSetup.email(studentEmail, 'FACG4', githubloginLink);
6372
gmail.users.messages.send({
6473
userId: 'me',
6574
auth: oauth2Client,
6675
resource: {
6776
raw: base64EncodedEmail
6877
}
69-
}, (err1, result) => {
70-
if (err1) {
71-
console.log('send gmail api error', err1);
78+
}, (sendGmailError, result) => {
79+
if (sendGmailError) {
80+
console.error('send gmail api error', sendGmailError);
81+
next(sendGmailError);
7282
} else {
7383
console.log('done', result.data.labelIds);
74-
// sweet alert (email has been sent to ${studentEmail})
7584
inviteStudent.insertInviteEmail(studentEmail, 'student', cohortId, (insertInviteEmailError, insertResponse) => {
7685
if (insertInviteEmailError) {
77-
// sweet alert (email haven't been add to database, please try again)
7886
console.error('insertInviteEmailError', insertInviteEmailError);
87+
next(insertInviteEmailError);
7988
} else {
80-
console.log('insertEmailToDb ', insertResponse);
8189
res.redirect('/inviteSt');
8290
}
8391
});
8492
}
8593
});
86-
});
87-
}
88-
});
94+
}
95+
});
96+
}
8997
};

src/controllers/passport-setup.js

+5-4
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,16 @@ passport.use(new GitHubStrategy(
3939
checkuser.checkuser(info[0].email, (err, result) => {
4040
if (!result.rows.length) {
4141
console.log('not allowed to log in , his email is not in database');
42-
done(null, false, { message: 'Incorrect username.' });
42+
done(null, { err: true, abd: 'potatoes' }, { message: 'Incorrect username.' });
43+
// done(null, false, { message: 'Incorrect username.' });
4344
} else {
44-
insertUser.insertUsers(profile.username, profile._json.bio, profile._json.avatar_url, info[0].email, (err, result) => {
45-
// // handel error
46-
});
4745
selectUserId.selectUserId(info[0].email, (err, result) => {
4846
// // handel error
4947
done(null, result.rows[0].id);
5048
});
49+
insertUser.insertUsers(profile.username, profile._json.bio, profile._json.avatar_url, info[0].email, (err, result) => {
50+
// // handel error
51+
});
5152
}
5253
});
5354
}

src/model/db_build.sql

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
BEGIN;
22

3-
DROP TABLE IF EXISTS users, attendance, flags, feedbacks, weeks, week_mentors, days, workshops, suggestions_complaints, cohort CASCADE;
3+
DROP TABLE IF EXISTS cohort, users, weeks, days, attendance, flags, feedbacks, week_mentors, workshops, suggestions_complaints, CASCADE;
44

55
CREATE TABLE cohort(
66
id SERIAL PRIMARY KEY,
@@ -85,7 +85,7 @@ INSERT INTO users (first_name, last_name, email, bio, phone, password, role, git
8585
('Mohammad', 'Heila', '[email protected]', 'Programming is a dream i live with it everyday', '0599944654', '$2b$10$CCSi5wCZTF5bzspFKvcveeUANKhYuQDaVFXwLZEPMG7s7SH98/iK2', 'student', 'mheila', 1),
8686
('Ahmed', 'M. Shatat', '[email protected]', 'SEO Master', '0599944633', '$2b$10$CCSi5wCZTF5bzspFKvcveeUANKhYuQDaVFXwLZEPMG7s7SH98/iK2', 'student', 'shatat_m', 1),
8787
('Farah', 'Zaqot', '[email protected]', 'Great man', '0599944666', '$2b$10$CCSi5wCZTF5bzspFKvcveeUANKhYuQDaVFXwLZEPMG7s7SH98/iK2', 'student', 'zfarah', 1),
88-
(NULL, NULL, 'abdalsamad.y.m@gamil.com', NULL, NULL, NULL, DEFAULT, NULL, 1),
88+
(NULL, NULL, 'abdalsamad.y.m@gmail.com', NULL, NULL, NULL, DEFAULT, NULL, 1),
8989
(NULL, NULL, '[email protected]', NULL, NULL, NULL, DEFAULT, NULL, 1),
9090
(NULL, NULL, '[email protected]', NULL, NULL, NULL, DEFAULT, NULL, 1),
9191
('Sultan', 'Asi', '[email protected]', 'great mentor', '0599223456', '$2b$10$CCSi5wCZTF5bzspFKvcveeUANKhYuQDaVFXwLZEPMG7s7SH98/iK2', 'mentor', 'sultanasi', NULL),

0 commit comments

Comments
 (0)