- Linty fresh...
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
2023-05-02 02:04:09 -04:00
parent 14fe45fc9c
commit 34acea15a2
17 changed files with 1203 additions and 559 deletions

5
.eslintrc.js Normal file
View File

@@ -0,0 +1,5 @@
module.exports = {
extends: [
'semistandard'
]
};

View File

@@ -18,8 +18,8 @@ app.use(cookie());
app.keys = [process.env.SESSION_KEYS as string];
app.use(session({}, app));
app.use(passport.initialize())
app.use(passport.session())
app.use(passport.initialize());
app.use(passport.session());
// Application error logging.
app.on('error', console.error);

View File

@@ -1,8 +1,149 @@
// const errors = require('restify-errors');
// // const errors = require('restify-errors');
// const config = require('../config');
// // const config = require('../config');
// const handlePassportResponse = (req, res, next) => (err, user, info) => {
// // const handlePassportResponse = (req, res, next) => (err, user, info) => {
// // if (err) {
// // return next(err);
// // }
// // const isVerifiedUser = user &&
// // user.isRegistrationVerified();
// // if (user && isVerifiedUser) {
// // return res.send({ ...user.toAuthJSON() });
// // } else if (user && !isVerifiedUser){
// // return res.send({
// // registrationSuccess: true,
// // nextSteps: 'Check your email for our confirmation email, you will not be able to login without confirming.'
// // });
// // }
// // return res.send(400, info);
// // };
// // module.exports = function (server, auth) {
// // const { passport } = auth;
// // /* Local Auth */
// // server.post('/auth', (req, res, next) => {
// // const { body: { username = null, password = null } = {} } = req;
// // if (!username || !password) {
// // let errors = {};
// // if (!username) {
// // errors.username = 'is required';
// // }
// // if (!password) {
// // errors.password = 'is required';
// // }
// // return res.send(422, { errors });
// // }
// // const callback = handlePassportResponse(req, res, next);
// // return passport.authenticate('local', { session: false }.then(callback)(req, res, next);
// // });
// // /**
// // * SERVICES
// // */
// // /* Google */
// // server.get(
// // '/auth/google',
// // passport.authenticate('google', { scope: 'profile email', session: false }),
// // );
// // server.get(
// // '/auth/google/callback',
// // (req, res, next) => {
// // const callback = handlePassportResponse(req, res, next);
// // return passport.authenticate(
// // 'google',
// // { failureRedirect: '/login' },
// // callback,
// // )(req, res, next);
// // },
// // );
// // /* Facebook */
// // server.get(
// // '/auth/facebook/login',
// // passport.authenticate('facebook', {
// // scope: ['email', 'public_profile'],
// // session: false,
// // }),
// // );
// // server.get(
// // '/auth/facebook/loggedin',
// // (req, res, next) => {
// // const callback = handlePassportResponse(req, res, next);
// // return passport.authenticate(
// // 'facebook',
// // { failureRedirect: '/login' },
// // callback,
// // )(req, res, next);
// // }
// // );
// // server.get(
// // '/auth/facebook/link',
// // auth.secure,
// // (req, res, next) => {
// // req.user.record.setLinkCheckBit((err, linkCheckBit) => {
// // passport.authenticate('facebookLink', {
// // scope: ['email', 'public_profile'],
// // session: false,
// // state: linkCheckbit,
// // })(req, res, next);
// // });
// // },
// // );
// //
// // server.get(
// // '/auth/facebook/linked',
// // (req, res, next) => {
// // const linkCheckBit = req.query.state;
// //
// // return passport.authenticate(
// // 'facebook',
// // { failureRedirect: '/profile' },
// // (err, profile) => {
// // if (err) {
// // return next(err);
// // }
// //
// // User.linkFacebookProfile(linkCheckBit, profile, (err, user) => {
// // if (err) {
// // return next(err);
// // }
// //
// // if (!user) {
// // return next(err, false, 'Linking the account to Facebook was unsuccessful, please try again.');
// // }
// //
// // res.send({
// // success: true,
// // info: 'Facerbook account successfully linked',
// // });
// // });
// // },
// // )(req, res, next);
// // }
// // );
// };
// import Koa from 'koa';
// import Router from 'koa-router';
// import { StatusCodes } from 'http-status-codes';
// import Users from 'grow-db/lib/models/users';
// const handlePassportResponse = (ctx: Koa.Context) => (err, user, info) => {
// if (err) {
// return next(err);
// }
@@ -22,12 +163,41 @@
// return res.send(400, info);
// };
// module.exports = function (server, auth) {
// const { passport } = auth;
// const routerOpts: Router.IRouterOptions = {
// prefix: '/auth',
// };
// /* Local Auth */
// server.post('/auth', (req, res, next) => {
// const { body: { username = null, password = null } = {} } = req;
// const router: Router = new Router(routerOpts);
// router.get('/', async (ctx: Koa.Context) => {
// const data = await Customers.find({}).exec();
// ctx.body = { data };
// });
// router.get('/:customer_id', async (ctx: Koa.Context) => {
// const data = await Customers.findById(ctx.params.customer_id).populate('person').exec();
// if (!data) {
// ctx.throw(StatusCodes.NOT_FOUND);
// }
// ctx.body = { data };
// });
// router.delete('/:customer_id', async (ctx: Koa.Context) => {
// const data = await Customers.findByIdAndDelete(ctx.params.customer_id).exec();
// if (!data) {
// ctx.throw(StatusCodes.NOT_FOUND);
// }
// ctx.body = { success: true, data };
// });
// router.post('/', async (ctx: Koa.Context) => {
// const data = await Customers.create(ctx.body);
// data.save();
// ctx.body = { success: true, data };
// });
// router.post('/', async (ctx: Koa.Context) => {
// const { body: { username = null, password = null } = {} } = ctx;
// if (!username || !password) {
// let errors = {};
@@ -40,192 +210,18 @@
// errors.password = 'is required';
// }
// return res.send(422, { errors });
// ctx.status = StatusCodes.UNPROCESSABLE_ENTITY;
// ctx.throw(422, { errors });
// }
// const callback = handlePassportResponse(req, res, next);
// return passport.authenticate('local', { session: false }.then(callback)(req, res, next);
// return passport.authenticate('local', { session: false }, callback)(req, res, next);
// });
// /**
// * SERVICES
// */
// /* Google */
// server.get(
// '/auth/google',
// passport.authenticate('google', { scope: 'profile email', session: false }),
// );
// server.get(
// '/auth/google/callback',
// (req, res, next) => {
// const callback = handlePassportResponse(req, res, next);
// return passport.authenticate(
// 'google',
// { failureRedirect: '/login' },
// callback,
// )(req, res, next);
// },
// );
// /* Facebook */
// server.get(
// '/auth/facebook/login',
// passport.authenticate('facebook', {
// scope: ['email', 'public_profile'],
// session: false,
// }),
// );
// server.get(
// '/auth/facebook/loggedin',
// (req, res, next) => {
// const callback = handlePassportResponse(req, res, next);
// return passport.authenticate(
// 'facebook',
// { failureRedirect: '/login' },
// callback,
// )(req, res, next);
// router.patch('/:customer_id', async (ctx: Koa.Context) => {
// const data = await Customers.findByIdAndUpdate(ctx.params.customer_id);
// if (!data) {
// ctx.throw(StatusCodes.NOT_FOUND);
// }
// );
// server.get(
// '/auth/facebook/link',
// auth.secure,
// (req, res, next) => {
// req.user.record.setLinkCheckBit((err, linkCheckBit) => {
// passport.authenticate('facebookLink', {
// scope: ['email', 'public_profile'],
// session: false,
// state: linkCheckbit,
// })(req, res, next);
// ctx.body = { success: true, data };
// });
// },
// );
//
// server.get(
// '/auth/facebook/linked',
// (req, res, next) => {
// const linkCheckBit = req.query.state;
//
// return passport.authenticate(
// 'facebook',
// { failureRedirect: '/profile' },
// (err, profile) => {
// if (err) {
// return next(err);
// }
//
// User.linkFacebookProfile(linkCheckBit, profile, (err, user) => {
// if (err) {
// return next(err);
// }
//
// if (!user) {
// return next(err, false, 'Linking the account to Facebook was unsuccessful, please try again.');
// }
//
// res.send({
// success: true,
// info: 'Facerbook account successfully linked',
// });
// });
// },
// )(req, res, next);
// }
// );
};
import Koa from 'koa';
import Router from 'koa-router';
import { StatusCodes } from 'http-status-codes';
import Users from 'grow-db/lib/models/users';
const handlePassportResponse = (ctx: Koa.Context) => (err, user, info) => {
if (err) {
return next(err);
}
const isVerifiedUser = user &&
user.isRegistrationVerified();
if (user && isVerifiedUser) {
return res.send({ ...user.toAuthJSON() });
} else if (user && !isVerifiedUser){
return res.send({
registrationSuccess: true,
nextSteps: 'Check your email for our confirmation email, you will not be able to login without confirming.'
});
}
return res.send(400, info);
};
const routerOpts: Router.IRouterOptions = {
prefix: '/auth',
};
const router: Router = new Router(routerOpts);
router.get('/', async (ctx: Koa.Context) => {
const data = await Customers.find({}).exec();
ctx.body = { data };
});
router.get('/:customer_id', async (ctx: Koa.Context) => {
const data = await Customers.findById(ctx.params.customer_id).populate('person').exec();
if (!data) {
ctx.throw(StatusCodes.NOT_FOUND);
}
ctx.body = { data };
});
router.delete('/:customer_id', async (ctx: Koa.Context) => {
const data = await Customers.findByIdAndDelete(ctx.params.customer_id).exec();
if (!data) {
ctx.throw(StatusCodes.NOT_FOUND);
}
ctx.body = { success: true, data };
});
router.post('/', async (ctx: Koa.Context) => {
const data = await Customers.create(ctx.body);
data.save();
ctx.body = { success: true, data };
});
router.post('/', async (ctx: Koa.Context) => {
const { body: { username = null, password = null } = {} } = ctx;
if (!username || !password) {
let errors = {};
if (!username) {
errors.username = 'is required';
}
if (!password) {
errors.password = 'is required';
}
ctx.status = StatusCodes.UNPROCESSABLE_ENTITY;
ctx.throw(422, { errors });
}
const callback = handlePassportResponse(req, res, next);
return passport.authenticate('local', { session: false }, callback)(req, res, next);
});
router.patch('/:customer_id', async (ctx: Koa.Context) => {
const data = await Customers.findByIdAndUpdate(ctx.params.customer_id);
if (!data) {
ctx.throw(StatusCodes.NOT_FOUND);
}
ctx.body = { success: true, data };
});

View File

@@ -1,11 +1,12 @@
import { StatusCodes } from "http-status-codes";
import { Context, Next } from "koa";
import { StatusCodes } from 'http-status-codes';
import { Context, Next } from 'koa';
export const errorHandler = async (ctx: Context, next: Next) => {
try {
await next();
} catch (error: any) {
ctx.status = error.statusCode || error.status || StatusCodes.INTERNAL_SERVER_ERROR;
ctx.status =
error.statusCode || error.status || StatusCodes.INTERNAL_SERVER_ERROR;
error.status = ctx.status;
ctx.body = { error };
ctx.app.emit('error', error, ctx);

View File

@@ -1,5 +1,11 @@
import { JwtPayload } from 'jsonwebtoken';
import { Document, InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose';
import {
InferSchemaType,
Model,
Schema,
StringSchemaDefinition,
Types,
} from 'mongoose';
import { Strategy } from './strategy';
import { STRATEGIES } from '../constants/strategies';
@@ -11,11 +17,11 @@ export type Auth = {
is2FA?: boolean;
record: StringSchemaDefinition;
username: string;
}
};
export type AuthPrivate = Auth & {
strategies: Types.ArraySubdocument<Strategy>;
}
};
export interface AuthMethods {
authenticate(password: string): boolean;
@@ -30,7 +36,10 @@ export interface AuthModel extends Model<AuthPrivate, {}, AuthMethods> {
authenticate(password: any): boolean;
findByUsername(username: string): Promise<AuthModel & AuthPrivate>;
isUsernameAvailable(username: string): Promise<boolean>;
findUserForReset(strategy: STRATEGIES, token: string): Promise<Strategy | undefined>;
findUserForReset(
strategy: STRATEGIES,
token: string
): Promise<Strategy | undefined>;
resetPassword(token: string, password: string): Promise<boolean>;
}
@@ -44,7 +53,7 @@ export const AuthSchema = new Schema<AuthPrivate, AuthModel, AuthMethods>(
{
minimize: true,
timestamps: true,
},
}
);
AuthSchema.methods = {
@@ -54,7 +63,11 @@ AuthSchema.methods = {
},
getAuthStrategy: function (method = STRATEGIES.LOCAL) {
return this.strategies.filter((strategy: Strategy) => strategy.method === method).pop() || false;
return (
this.strategies
.filter((strategy: Strategy) => strategy.method === method)
.pop() || false
);
},
getToken: function (props = {}) {
@@ -93,17 +106,19 @@ AuthSchema.methods = {
};
if (hasLocalStrategy) {
await this.model('User').findOneAndUpdate(
await this.model('User')
.findOneAndUpdate(
{ _id: this._id, 'strategies.method': STRATEGIES.LOCAL },
{ $set: { 'strategies.$': strategy } },
{ upsert: true },
).catch();
)
.catch();
return true;
}
this.credentials.push(strategy);
await this.save().catch(() => false);
return true;
},
}
};
AuthSchema.statics = {
@@ -120,15 +135,18 @@ AuthSchema.statics = {
},
isUsernameAvailable: async function (username) {
return !!!this.findByUsername(username);
return !this.findByUsername(username);
},
resetPassword: async function (token, password) {
const decoded = verifyJwt(token);
const { sub, key } = decoded as JwtPayload;
const auth = await this.findOne({ _id: sub, 'strategies.resetToken': key }).catch();
const auth = await this.findOne({
_id: sub,
'strategies.resetToken': key,
}).catch();
return !!auth && auth.setPassword(password);
},
}
};
export type AuthSchema = InferSchemaType<typeof AuthSchema>;

View File

@@ -8,18 +8,18 @@ export const Strategy = new Schema(
enum: Object.values(STRATEGIES),
index: true,
required: true,
unique: true,
unique: true
},
externalId: { type: String, index: true },
key: { type: String, required: true, trim: true },
profile: {},
resetToken: { type: String },
forceReset: { type: Boolean },
forceReset: { type: Boolean }
},
{
minimize: true,
timestamps: true,
},
timestamps: true
}
);
export type Strategy = InferSchemaType<typeof Strategy>;

View File

@@ -1,8 +1,8 @@
import dotenv from 'dotenv';
dotenv.config();
import app from './app';
import { connection } from './database/database.connection';
dotenv.config();
const PORT: number = Number(process.env.PORT) || 9000;

View File

@@ -1,11 +1,10 @@
import passport from 'koa-passport';
import { Strategy } from 'passport-local';
import bcrypt from 'bcrypt';
import Auth from '../model/auth';
import { AuthSchema } from '../schema/auth';
export const LocalStrategy = passport.use(new Strategy(async (username, password, done) => {
export const localStrategy = passport.use(
new Strategy(async (username, password, done) => {
const user = await Auth.findOne({
where: {
username,
@@ -16,5 +15,5 @@ export const LocalStrategy = passport.use(new Strategy(async (username, password
} else {
done(null, false);
}
}
));
})
);

View File

@@ -2,7 +2,10 @@ import Auth from '../model/auth';
import { AuthModel, AuthPrivate } from '../schema/auth';
import { sign } from './jwt';
export const getAuthenticationBundle = async (username: string, password: string) => {
export const getAuthenticationBundle = async (
username: string,
password: string,
) => {
const auth = await Auth.findByUsername(username).catch();
const isAuthenticated = !!auth && (auth as AuthModel).authenticate(password);
const record = isAuthenticated ? (auth as AuthPrivate).record : null;

View File

@@ -12,20 +12,29 @@ export type SignProps = string | TokenProps | void;
export const sign = (props: SignProps) => {
const today = new Date();
const { sub = null, ...rest }: TokenProps = typeof props === 'string' || typeof props === 'undefined' ? { sub: props || null } : props;
const { sub = null, ...rest }: TokenProps =
typeof props === 'string' || typeof props === 'undefined'
? { sub: props || null }
: props;
let exp = rest.exp;
if (!exp) {
exp = new Date(today);
exp.setDate(today.getDate() + parseInt(process.env.JWT_DAYS_VALID as string));
exp.setDate(
today.getDate() + parseInt(process.env.JWT_DAYS_VALID as string),
);
exp = exp.getTime() / 1000;
}
return jwt.sign({
aud: rest.aud || process.env.JWT_AUDIENCE,
return jwt.sign(
{
exp,
sub,
aud: rest.aud || process.env.JWT_AUDIENCE,
iat: today.getTime(),
iss: rest.iss || process.env.JWT_ISSUER,
sub,
}, process.env.JWT_SECRET || 'secret');
},
process.env.JWT_SECRET || 'secret',
);
};
export const verify = (token: string) => jwt.verify(token, process.env.JWT_SECRET || 'secret');
export const verify = (token: string) =>
jwt.verify(token, process.env.JWT_SECRET || 'secret');

View File

@@ -1,13 +1,13 @@
import crypto from 'crypto';
import { sign } from "./jwt";
import { sign } from './jwt';
export const generateResetToken = (sub: string) => {
const key = crypto.randomBytes(16).toString('hex');
const token = sign({
sub,
key,
exp: (Date.now() + (24 * 60 * 60 * 1000)),
exp: Date.now() + 24 * 60 * 60 * 1000,
});
return { key, token };
};

View File

@@ -6,14 +6,12 @@
"scripts": {
"build": "tsc",
"lint": "tslint --project tsconfig.json --format stylish",
"prettier:fix": "prettier-eslint --eslint-config-path ./.eslintrc.js --write '**/*.ts'",
"prettier:fix": "prettier-eslint --write '**/*.ts'",
"serve": "ts-node src/server.ts",
"start": "nodemon"
},
"devDependencies": {
"@tsconfig/node16": "^1.0.3",
"@types/bcrypt": "^5.0.0",
"@types/crypto-js": "^4.1.1",
"@types/dotenv": "^8.2.0",
"@types/http-status-codes": "^1.2.0",
"@types/jsonwebtoken": "^9.0.1",
@@ -32,6 +30,12 @@
"@types/passport-google-oauth": "^1.0.42",
"@types/passport-jwt": "^3.0.8",
"@types/passport-local": "^1.0.35",
"eslint": "^8.13.0",
"eslint-config-semistandard": "latest",
"eslint-config-standard": "^17.0.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-n": "^15.0.0",
"eslint-plugin-promise": "^6.0.0",
"jest": "^29.4.2",
"nodemon": "^2.0.20",
"prettier": "^2.8.4",
@@ -45,8 +49,6 @@
},
"dependencies": {
"@simplewebauthn/server": "^7.2.0",
"bcrypt": "^5.1.0",
"crypto": "^1.0.1",
"dotenv": "^16.0.3",
"http-status-codes": "^2.2.0",
"jsonwebtoken": "^9.0.0",

919
yarn.lock

File diff suppressed because it is too large Load Diff