forked from nodejsapps/TypeScript-Node-Starter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpassport.ts
More file actions
79 lines (68 loc) · 2.19 KB
/
Copy pathpassport.ts
File metadata and controls
79 lines (68 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import * as passport from "passport";
import * as request from "request";
import * as passportLocal from "passport-local";
import * as _ from "lodash";
// import { User, UserType } from '../models/User';
import { default as User } from "../models/User";
import { Request, Response, NextFunction } from "express";
const LocalStrategy = passportLocal.Strategy;
passport.serializeUser<any, any>((user, done) => {
done(undefined, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
/**
* Sign in using Email and Password.
*/
passport.use(new LocalStrategy({ usernameField: "email" }, (email, password, done) => {
User.findOne({ email: email.toLowerCase() }, (err, user: any) => {
if (err) { return done(err); }
if (!user) {
return done(undefined, false, { message: `Email ${email} not found.` });
}
user.comparePassword(password, (err: Error, isMatch: boolean) => {
if (err) { return done(err); }
if (isMatch) {
return done(undefined, user);
}
return done(undefined, false, { message: "Invalid email or password." });
});
});
}));
/**
* OAuth Strategy Overview
*
* - User is already logged in.
* - Check if there is an existing account with a provider id.
* - If there is, return an error message. (Account merging not supported)
* - Else link new OAuth account with currently logged-in user.
* - User is not logged in.
* - Check if it's a returning user.
* - If returning user, sign in and we are done.
* - Else check if there is an existing account with user's email.
* - If there is, return an error message.
* - Else create a new account.
*/
/**
* Login Required middleware.
*/
export let isAuthenticated = (req: Request, res: Response, next: NextFunction) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect("/login");
};
/**
* Authorization Required middleware.
*/
export let isAuthorized = (req: Request, res: Response, next: NextFunction) => {
const provider = req.path.split("/").slice(-1)[0];
if (_.find(req.user.tokens, { kind: provider })) {
next();
} else {
res.redirect(`/auth/${provider}`);
}
};