Как установить истекшее время в узле oAuth2 Server - PullRequest
0 голосов
/ 02 апреля 2020

В настоящее время я работаю над небольшим проектом с oAuth2 с node js. Node js с express и node-oauth2-server в качестве полного полного сервиса для входа в систему et c ...

Все работает просто отлично, они могут зарегистрироваться, проверить свой адрес электронной почты и войти ( забыли пароль и т. д. c. еще не закончено) Но я не могу установить значение срока действия токена.

Моей любимой реализацией будет вход с постоянным входом или без него (в пользовательском интерфейсе это обычный маленький переключатель под формой входа). Также я хотел бы хранить информацию о клиенте с помощью accessToken, что-то вроде Browser, Location et c. Чтобы пользователь мог запросить, где он в данный момент вошел в систему (как вы можете сделать в Facebook).

Большая часть моего кода oAuth2 взята из этого урока: https://blog.cloudboost.io/how-to-make-an-oauth-2-server-with-node-js-a6db02dc2ce7

Моя главная проблема в том, что я не знаю, где обращаться с данными. В моем регистре (et c.) Все точки запускаются через мое промежуточное ПО. Но с узлом-oauth2-сервером у меня нет промежуточного программного обеспечения.

Спасибо!

Крис

Вот мой сервер. js:

if(process.env.NODE_ENV === undefined)
    process.env.NODE_ENV = "dev"


/* REQUIRE */
const oAuth2Server = require('node-oauth2-server');
const express = require('express');
const bodyParser = require('body-parser');
const util = require('util');
const dbCon = require('./subsystem/mySql')
const oAuthModel = require('./endpoints/auth/authModel')(dbCon);

/* CONST */
let port = 3000;
if(process.env.NODE_ENV !== 'production')
    port = 3000;
else
    port = 80;
const debug = true;
const app = express();

/* INIT */
app.oauth = oAuth2Server({
    model: oAuthModel,
    grants: ['password'],
    debug: debug
})

/* ROUTER */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(app.oauth.errorHandler());

const authRoutes = require('./router/auth')(express.Router(), app, dbCon)
app.use('/auth', authRoutes);

app.all('*', (req, res) => {
    res.status(404).send({message: "This service was not found"});
});

/* Start Server */
app.listen(port, () => {
    console.log(`listening on port ${port} in ${process.env.NODE_ENV} mode`)
})

Вот мой authModel:

let dbCon;
module.exports = injectedDbCon => {
    dbCon = injectedDbCon;
    return {
        getClient: getClient,
        saveAccessToken: saveAccessToken,
        getUser: getUser,
        grantTypeAllowed: grantTypeAllowed,
        getAccessToken: getAccessToken
    }
}

const userDB = require('../user/userDB')(dbCon);
const authDB = require('./authDB');

function getClient(clientID, clientSecret, callback){

    const client = {
        clientID,
        clientSecret,
        grants: null,
        redirectUris: null
    }

    callback(false, client);
}

function grantTypeAllowed(clientID, grantType, callback) {

    console.log('grantTypeAllowed called and clientID is: ', clientID, ' and grantType is: ', grantType);

    callback(false, true);
}


function getUser(email, password, callback){

    console.log('getUser() called and email is: ', email, ' and password is: ', password, ' and callback is: ', callback, ' and is userDBHelper null is: ', userDB);

    //try and get the user using the user's credentials
    userDB.getUserFromCrentials(email, password)
    .then(data => {callback(false,data[0][0])})
    .catch(error => {callback(error,null)})
}

/* saves the accessToken along with the userID retrieved the specified user */
function saveAccessToken(accessToken, clientID, expires, user, callback){

    console.log('saveAccessToken() called and accessToken is: ', accessToken,
        ' and clientID is: ',clientID, ' and user is: ', user, ' and accessTokensDBhelper is: ', authDB)

    //save the accessToken along with the user.id
    authDB.saveAccessToken(accessToken, user.id)
    .then(data => {callback(null)})
    .catch(error => {callback(error)})

}

function getAccessToken(bearerToken, callback) {

    //try and get the userID from the db using the bearerToken
    authDB.getUserIDFromBearerToken(bearerToken)
    .then(data => {
        const accessToken = {
            user: {
                id: data,
            },
            expires: null
        }
        callback(true,accessToken)
    })
    .catch(error => {callback(false,error)})
}

Вот мой authDB:

const dbCon = require('../../subsystem/mySql')

const saveAccessToken = (accessToken, userID) => {
    return new Promise((resolve,reject) => {
        //execute the query to get the user
        dbCon.query(`INSERT INTO access_tokens (access_token, user_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE access_token = ?;`,[accessToken,userID,accessToken])
        .then(data => {resolve(true)})
        .catch(error => {reject(error)})
    })
}


const getUserIDFromBearerToken = bearerToken => {
    return new Promise((resolve,reject) => {
        //create query to get the userID from the row which has the bearerToken
        const getUserIDQuery = `SELECT * FROM access_tokens WHERE access_token = ?;`

        //execute the query to get the userID
        dbCon.query(getUserIDQuery,[bearerToken])
        .then(data => {
            if(data.results != null && data.results.length == 1)
                resolve(data.results[0].user_id)
            else
                reject(false)
        })
        .catch(error => {reject(error)})
    })
}


module.exports.saveAccessToken = saveAccessToken
module.exports.getUserIDFromBearerToken = getUserIDFromBearerToken
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...