Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
callbackURL: domainStr + '/auth/reddit/callback',
state: true
},
Promise.coroutine(function * (token, tokenSecret, profile, done) {
profile.displayName = profile.name;
user = yield settings.createUser(profile, "reddit");
done(null, user);
})
)
);
}
// -- Github
if(typeof config.app.data.passport_github !== "undefined") {
var GitHubStrategy = require('passport-github').Strategy;
passport.use(
new GitHubStrategy(
{
clientID: config.app.data.passport_github.clientId,
clientSecret: config.app.data.passport_github.clientSecret,
callbackURL: domainStr + '/auth/github/callback'
},
Promise.coroutine(function * (accessToken, refreshToken, profile, done) {
console.log(profile);
user = yield settings.createUser(profile, "github");
done(null, user);
})
)
);
}
const app: Koa = new Koa()
// Loading certificates
const options: http2.SecureServerOptions = {
cert: fs.readFileSync(`${process.cwd()}/src/resources/cert/localhost.crt`),
key: fs.readFileSync(`${process.cwd()}/src/resources/cert/localhost.key`)
}
const _use: Function = app.use
app.use = (x: Middleware) => _use.call(app, convert(x))
app.use(helmet())
app.use(logger())
app.use(bodyParser())
app.use(errorMiddleware.errorMiddleware())
app.use(passport.initialize())
app.use(passport.session())
routes(app)
// show swagger only if the NODE_ENV is development and stagging
if (['development', 'staging'].includes(config.environment)) {
app.use(mount('/swagger', serve(`${process.cwd()}/src/resources/swagger`)))
}
http2
.createSecureServer(options, app.callback())
.listen(config.port, () => {
console.log(`Server started on ${config.port}`)
})
const passport = require('koa-passport');
app = new Koa();
koaqs(app);
// sessions
const session = require('koa-session');
app.keys = ['your-session-secret'];
app
.use(logger())
.use(session({}, app))
.use(bodyParser())
.use(koaValidator())
.use(passport.initialize())
.use(passport.session())
.use(router.routes())
.use(router.allowedMethods());
app.listen(PORT, () => {
console.log(`Server listening on port: ${PORT}`);
});
export async function authUser (ctx, next) {
// user local authentication strategy
try {
return passport.authenticate('local', (err, user) => {
if (err || !user) {
ctx.throw(401)
}
const token = user.generateToken()
const response = user.toJSON()
delete response.password
ctx.status = constants.STATUS_CODE.SUCCESS_STATUS
ctx.body = {
user: response
}
ctx.append('Authorization', token);
})(ctx, next)
} catch (error) {
ctx.body = error;
ctx.status = constants.STATUS_CODE.INTERNAL_SERVER_ERROR_STATUS
}
passport.authenticate('bearer', { session: false }),
heroesController.show
);
app.put('/heroes/me/increase/:area(skills)/:id',
passport.authenticate('bearer', { session: false }),
heroesController.increase
);
app.put('/heroes/me/increase/:area(abilities|parameters)/:name',
passport.authenticate('bearer', { session: false }),
heroesController.increase
);
app.patch('/heroes/me',
passport.authenticate('bearer', { session: false }),
heroesController.update
);
app.put('/heroes/me/change-password',
passport.authenticate('bearer', { session: false }),
heroesController.changePassword
);
// TODO: Think about sep heroes controller to sep
// things, complects, island, building
app.del('/heroes/me/things/:id',
passport.authenticate('bearer', { session: false }),
heroesController.removeThing
);
app.put('/heroes/me/things/:id/dress',
done(null, createdUser)
} else {
done(null, false)
}
}
}
))
/**
* Facebook strategy of Passport.js
*
* @param
* @returns
*/
const FacebookStrategy = require('passport-facebook').Strategy
passport.use(new FacebookStrategy({
clientID: 'facebook-app-id',
clientSecret: 'facebook-app-secret',
callbackURL: 'http://localhost:' + (process.env.PORT || 3000) + '/users/auth/facebook/callback',
profileFields: ['id', 'displayName', 'name', 'photos', 'email']
},
async (token, tokenSecret, profile, done) => {
// Retrieve user from database, if exists
const user = await User.findOne({
where: {
email: profile.emails[0].value
}
})
if (user) {
done(null, user)
} else {
// If user not exist, create it
});
passport.deserializeUser(async (email, done) => {
try {
const user = await Users.findOne({ email });
// if no user exists then invalidate the previous session
//
if (!user) return done(null, false);
// otherwise continue along
done(null, user);
} catch (err) {
done(err);
}
});
if (config.auth.local) passport.use(Users.createStrategy());
if (config.auth.providers.google)
passport.use(
new GoogleStrategy(
config.auth.strategies.google,
async (accessToken, refreshToken, profile, done) => {
const email = profile.emails[0].value;
try {
let user = await Users.findByEmail(email);
if (user) {
// store the access token and refresh token
if (accessToken) user.set('google_access_token', accessToken);
if (refreshToken) user.set('google_refresh_token', refreshToken);
user = await user.save();
}))
const FacebookStrategy = require('passport-facebook').Strategy
passport.use(new FacebookStrategy({
clientID: 'your-client-id',
clientSecret: 'your-secret',
callbackURL: 'http://localhost:' + (process.env.PORT || 3000) + '/auth/facebook/callback'
},
function(token, tokenSecret, profile, done) {
// retrieve user ...
fetchUser().then(user => done(null, user))
}
))
const TwitterStrategy = require('passport-twitter').Strategy
passport.use(new TwitterStrategy({
consumerKey: 'your-consumer-key',
consumerSecret: 'your-secret',
callbackURL: 'http://localhost:' + (process.env.PORT || 3000) + '/auth/twitter/callback'
},
function(token, tokenSecret, profile, done) {
// retrieve user ...
fetchUser().then(user => done(null, user))
}
))
const GoogleStrategy = require('passport-google-auth').Strategy
passport.use(new GoogleStrategy({
clientId: 'your-client-id',
clientSecret: 'your-secret',
callbackURL: 'http://localhost:' + (process.env.PORT || 3000) + '/auth/google/callback'
},
}
})
} else {
done(null, false)
}
}
))
/**
* google strategy of Passport.js
*
* @param
* @returns
*/
const GoogleStrategy = require('passport-google-auth').Strategy
passport.use(new GoogleStrategy({
clientId: 'your-google-oauth-client-id',
clientSecret: 'your-google-oauth-client-secret',
callbackURL: 'http://localhost:' + (process.env.PORT || 3000) + '/users/auth/google/callback'
},
async (token, tokenSecret, profile, done) => {
// Retrieve user from database, if exists
const user = await User.findOne({
where: {
email: profile.emails[0].value
}
})
if (user) {
done(null, user)
} else {
// If user not exist, create it
const newUser = {
done(null, false)
}
})
})
// serializeUser 在用户登录验证成功以后将会把用户的数据存储到 session 中
passport.serializeUser(function(user, done) {
done(null, user)
})
// deserializeUser 在每次请求的时候将从 session 中读取用户对象
passport.deserializeUser(function(user, done) {
return done(null, user)
})
passport.use(jwtLogin)
passport.use('email-local', localEmailLogin)
passport.use('username-local', localUsernameLogin)
module.exports = passport