如何为通行证设置令牌

时间:2019-05-06 19:55:13

标签: reactjs express redux react-redux passport.js

我试图弄清楚如何在调用此api时从react中获取令牌。

router.get('/auth/github', passport.authenticate('github', { 
  session: false, 
  scope:[ 'profile', 'id']
}));
router.get('/auth/github/callback', 
  passport.authenticate('github', { session:true, failureRedirect: 'http:localhost:8001/signIn' }),
  function(req, res) {

    const token = jwt.sign({id: req.user.id}, process.env.JWT_SECRET, { expiresIn: 86400 })
    // res.redirect(`http://localhost:8001/?token=${token}`)
    res.send({
      token:token
    })

  });

router.get("/current_user", (req, res) => {
  if(req.user){
    res.status(200).send({ user: req.user});
  } else {
    res.json({ user:null})
  }
});

我想在本地存储反应中设置此令牌,但是不确定如何使用护照的此功能。理想情况下,如果我可以为会话设置令牌,则可以创建路由回调,该路由回调将让我知道当前用户是否有令牌,这可以用作检查当前用户是否已登录的方式。 / p>

我有一个登录策略,可以很好地处理令牌。

例如,在此处的api调用中传递令牌

router.post('/loginUser',  passport.authenticate('login', {session: true}), (req, res, next) => {
  passport.authenticate('login', (err, user, info) => {
    if (err) {
      console.log(err);
    }
    if (info != undefined) {
      console.log(info.message);
      res.status(401).send(info.message);
    } else {
      req.logIn(user, err => {
       models.User.findOne({
          where: {
            username: req.body.username,
          },
        }).then(user => {
          const token = jwt.sign({ id: user.id  }, process.env.JWT_SECRET);
          // res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
          jwt.verify(token, process.env.JWT_SECRET, function(err, data){
            console.log(err, data);
          })
          res.status(200).send({
            auth: true,
            token: token,
            message: 'user found & logged in',
          });
          // console.log(req.user)
        });
      });
    }
  })(req, res, next);
});

这里是用户尝试登录时调用的操作

export const logIn =  (user) => { 
    return (dispatch) => {
        Axios.post('/api/users/loginUser',{
            username: user.username,
            password: user.password,
        }).then( (res) => {
            const token = res.data.token; // gets token from response
            localStorage.setItem('auth', token);
            setAuthToken(token);
            history.push('/dashboard');
            dispatch({type: SET_USER, user});
        }).catch((err)=> {
            dispatch({type:  LOG_FAIL, err});
            console.log(err.response.data); // not even showing err console.
        })
    }
}

它在 减速器

中传递
import { SET_USER,  GET_CURRENT_USER, GET_USER,  REG_SUC, REG_FAIL, LOG_FAIL} from '../actions/';


const initialState = {
    authError: null,
    isAuthenticated:localStorage.getItem('auth'),
    user: [],
    isAuthenticated2:[],
    redirectPath: null

}

export default (state = initialState, action) => {
    switch (action.type) {
        case SET_USER:
        console.log(action.payload);
            return ({
                ...state,
                user:action.user,
                token: action.payload,
                isAuthenticated:action.isAuthenticated

App.js获取令牌

import React, { Component } from 'react';
// import axios from 'axios';
import Navbar from './components/layout/Navbar';
import { withStyles } from '@material-ui/core/styles';
import {compose} from 'redux';
import { connect } from 'react-redux';
import { getUser, setCurrentUser} from './actions/';
import setAuthToken from './setAuthToken';
import jwt_decode from 'jwt-decode';
import ourStyles from './styles/ourStyles';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      user: "",
      isAuthenticated: false,
    }
}
componentWillMount(){
  if (localStorage.auth != null) {
    // Set auth token header auth
    setAuthToken(localStorage.auth);
    const token = localStorage.getItem('auth');
    // // Decode token and get user info and exp
    const decoded = jwt_decode(token);
    // console.log(decoded);
    // // Set user and isAuthenticated
    this.props.setCurrentUser(decoded);
  }
    this.props.getUser();
    console.log(this.props.owl);
}

componentDidUpdate(){
  // const currentUser = localStorage.getItem('myAuth');
  console.log(this.props.owl);
}
  render() {
    const { classes, isAuthenticated } = this.props;
    return (
      <div className="App">
        <Navbar />
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  isAuthenticated: state.user.isAuthenticated,

})
const mapDispatchToProps = (dispatch) => ({
  getUser: () => dispatch (getUser()),
  setCurrentUser: () => dispatch( setCurrentUser()),
});
export default compose(connect(mapStateToProps, mapDispatchToProps), withStyles(ourStyles))(App);

然后我可以使用此isAuthenticated道具来确定用户是否登录或注销。

像这样在导航栏中使用

const logout = (e) => {
    e.preventDefault()
    Axios.get(process.env.REACT_APP_LOGOUT, {withCredentials: true})
        .then(res => {
            // console.log(res);
            if (res.status === 200) {
                localStorage.removeItem('auth')
                localStorage.removeItem('myAuth')
                history.push('/')
            }
        })
        .catch(err => {
        //     // their will be an inevitable error, so you would need this for it to work
            localStorage.removeItem('auth')
             localStorage.removeItem('myAuth')
            history.push('/')
         })
}

const Navbar = ({classes, isAuthenticated}) => (

<Router history={history}>

        <div className={classes.navRoot}>

            <AppBar position="static" className={classes.navbar}>
                <Toolbar>

                    <Typography variant="h6" color="inherit">
                        Express Seqeuelize App
                    </Typography>

                    <Typography classcolor="inherit" className={classes.rightt}>

                        {!isAuthenticated && (

                            <Button>
                                <Link to="/" className={classes.rightToolbar}>
                                    Home
                                </Link>
                            </Button>

                        )}
                        {isAuthenticated && (
                            <Button>
                                <Link className={classes.rightToolbar} to="/posts">
                                    Posts
                                </Link>
                            </Button>

                        )}

                        {!isAuthenticated && (

                            <Button>
                                <Link to="/signUp" className={classes.rightToolbar}>
                                    Sign Up
                                </Link>
                            </Button>

                        )}

                        {!isAuthenticated && (

                            <Button>
                                <Link to="/signIn" className={classes.rightToolbar}>
                                    Sign In
                                </Link>
                            </Button>

                        )}

                        {isAuthenticated && (
                            <Button>
                                <Link className={classes.rightToolbar} to="/Post">
                                    New Post
                                </Link>
                            </Button>

                        )}

                        {isAuthenticated && (
                            <Button>
                                <Link to="/dashboard" className={classes.rightToolbar}>
                                    Dashboard
                                </Link>
                            </Button>

                        )}

                        {isAuthenticated && (
                            <Button onClick={logout}>

                                LogOut

                            </Button>
                        )}

                    </Typography>

                </Toolbar>
            </AppBar>
            <Switch>
            <Route exact path="/github" />
            <Route exact path="/signUp" component={signUp}/>
            <Route exact path="/" component={Home}/>
            <Route exact path="/signIn" component={signIn}/>
            <Route exact path="/Post" component={Post}/>
            <Route exact path="/Posts" component={Posts}/>
            <Route path="/Forgot" component={Forgot}/>
            <Route path="/users" component={Users}/>
            <Route exact path="/logout"/>
            <Route exact path="/dashboard" component={Dashboard}/>
            <Route path="/test"/>
            <Route path="/reset/:token" component={ResetPassword}/>
            <Route exact path="/updatePassword/:username" component={updatePassword}/>
            </Switch>
        </div>
 </Router>

);

const mapStateToProps = (state) => ({
    isAuthenticated: state.user.isAuthenticated
})

我希望能够对github策略采取相同的方法。我应该采取什么方法。我的主要目标是能够从api获取令牌以做出反应。

但是,调用/auth/github的方式是在地址栏中输入手动输入,例如

  

localhost:8000 / api / users / auth / github /

那我明白了

enter image description here

然后在我的current_user路由中,我得到了

enter image description here

passport-github

const GitHubStrategy = require('passport-github2').Strategy;
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const models = require("../models/");

// passport.serializeUser((user, done) => {
//   // push to session
//   done(null, user.id);
//   console.log(user.id)
// });


// passport.deserializeUser((id, done) => {
//   models.User.findOne({
//     where: {
//       id,
//     },
//   }).then(user => done(null, user))
//   .catch(done);
// });
module.exports = async  (passport) => {

passport.use(
  new GitHubStrategy(
    {
      clientID: process.env.clientID,
      clientSecret: process.env.secret,
      callbackURL: 'http://localhost:8000/api/users/auth/github/callback',
      passReqToCallback: true,
      profileFields: ['id', 'login']
    },
     (req, accessToken, refreshToken, profile, done) => {
       const { id,  login, email} = profile._json;  
       console.log(`backbro ${id}`);
      //  console.log(req)
       models.User.findOne({
         where:{
           id: id
         }
       }).then( user => {
        //  if user is found
         if(user){
           return done(null, user)
         }
        //  else create new user
         else{
           models.User.create({
             id: id,
             username:login,
             email: email,
             createdAt: Date.now()
           }).then( user => {
             console.log('github user created');
             return done(null, user);
           })
         }
       })
    }
  )
);

passport.serializeUser((user, done) => {
  // push to session
 done(null, user.id);
});

passport.deserializeUser((userId, done) => {

  // console.log('calling deserial' + userId); 
  // // TODO: findByPk syntax? findById deprecated? Try later after sucessfully record data in DB
  models.User
      .findOne({ where: { id: userId } })
      .then(function(user){
        // console.log(user);
         done(null, userId);
      }).catch(function(err){
        done(err, null);
      });
  // return done(null, id);
});


}

0 个答案:

没有答案