aboutsummaryrefslogtreecommitdiff
path: root/src/server/authentication/config/passport.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/server/authentication/config/passport.ts')
-rw-r--r--src/server/authentication/config/passport.ts49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/server/authentication/config/passport.ts b/src/server/authentication/config/passport.ts
new file mode 100644
index 000000000..05f6c3133
--- /dev/null
+++ b/src/server/authentication/config/passport.ts
@@ -0,0 +1,49 @@
+import * as passport from 'passport'
+import * as passportLocal from 'passport-local';
+import * as mongodb from 'mongodb';
+import * as _ from "lodash";
+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<any, any>((id, done) => {
+ User.findById(id, (err, user) => {
+ done(err, user);
+ });
+});
+
+// AUTHENTICATE JUST WITH EMAIL AND PASSWORD
+passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
+ User.findOne({ email: email.toLowerCase() }, (error: any, user: any) => {
+ if (error) return done(error);
+ if (!user) return done(undefined, false, { message: "Invalid email or password" }) // invalid email
+ user.comparePassword(password, (error: Error, isMatch: boolean) => {
+ if (error) return done(error);
+ if (!isMatch) return done(undefined, false, { message: "Invalid email or password" }); // invalid password
+ // valid authentication HERE
+ return done(undefined, user);
+ });
+ });
+}));
+
+export let isAuthenticated = (req: Request, res: Response, next: NextFunction) => {
+ if (req.isAuthenticated()) {
+ return next();
+ }
+ return res.redirect("/login");
+}
+
+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}`);
+ }
+}; \ No newline at end of file